Failed half-hour project

June 25th, 2009

My attempt at a half-hour project before going to sleep failed. It took a little more than a half-hour, and my input of the following:

      version proto

      character paul
        image paul.png
      end

      character angie
        image angie.png
      end

      angie says I thought you were going to bed!
      paul say But I really wanted to try and write a comic markup language prototype.
      angie says What? What the heck is wrong with you? Go to sleep.
      paul says Just give me a half hour.
      angie says Ok, fine, but only a half hour. Crazy person.

only resulted in the following output:

Unrecognized command at line 3: "character"

Ah well, there’s always tomorrow…

Nitrogen module auto-reloading

June 20th, 2009

This is a really simple tip, but it was handy for me, and it could be helpful for someone else, too.

While playing around with Nitrogen, which is a great project by the way (more in a later blog post, I guarantee it), I noticed that I had to restart the server to re-load modules as I changed them (or I could manually, reload them, I know, I know..).

Since I was using Mochiweb as my backend, and I’m used to the development version of Mochiweb auto-reloading modules as you recompile, I wanted the same functionality here.

Turns out it’s as simple as changing the default start.sh from

#!/bin/sh
cd `dirname $0`
 
echo Starting Nitrogen.
erl \
	-name nitrogen@localhost \
	-pa ./ebin -pa ./include \
	-s make all \
	-eval "application:start(appname)"

to this

#!/bin/sh
cd `dirname $0`
 
echo Starting Nitrogen.
erl \
	-name nitrogen@localhost \
	-pa ./ebin -pa ./include \
	-s make all \
	-s reloader \
	-eval "application:start(appname)"

… and bam, modules now reload as you recompile them.

simple textarea auto-resizer

April 24th, 2009

Today I was having issues with a textarea resizer (a hacked-up version of SmartArea) that I had been using for a while in a work project. It was working fine for textareas of a certain width, but it got less and less useful as the textareas got less wide, not wrapping lines until it already had scrollbars for a word or two.

It seemed to me that it needn’t be as complex as it was, so I decided to try and write my own, and here’s what I came up with:

function growTextArea(e) {
    if (!this.rows || this.rows < 1) this.rows = 1;
    while (this.clientHeight >= this.scrollHeight && this.rows > 1) this.rows -= 1;
    while (this.clientHeight < this.scrollHeight) this.rows += 1;
}

A working example, embedded using jQuery:

$('#example-resizing-textarea')
    .keyup(growTextArea).keyup();

Type some text in here:

Compatibility

This works for me in Firefox, IE6, IE7, Chrome and Chromium, Safari (for Windows, testing in a Windows VM along with the IEs and Chrome), and Opera 9.62. As you may have noticed I’ve avoided using any JS-library or browser-specific code, so this should work equally well with jQuery, Prototype, or with no library at all.

IE actually gives incorrect values for scrollHeight, but that is easily made up for by using “this.clientHeight >= this.scrollHeight” in the first while loop rather than “this.clientHeight == this.scrollHeight”

Minimum and Maximum rows

If you want to set a minimum and maximum height, it takes a little more work:

function sizeTextArea(min, max) {
    return function(e) {
        if (!this.rows || this.rows < min) this.rows = min;
        while ((this.clientHeight >= this.scrollHeight 
                && this.rows > 1 && this.rows <= max) 
               || this.rows > max) this.rows -= 1;
        while ((this.clientHeight < this.scrollHeight 
                || this.rows < min) 
               && this.rows < max) this.rows += 1;
        if (this.rows == max
            && this.clientHeight < this.scrollHeight) this.style.overflow = 'auto';
        else this.style.overflow = 'hidden';
    }
}

Another example, limited to having between 4 and 8 rows:

var sizer48 = sizeTextArea(4, 8);
$('#example-resizing-textarea')
    .keyup(sizer48).keyup();

Type some text in here, too:

Possible modifications could include using pixel sizes instead of changing the “row” attribute and animating the resizing.

This could easily be packaged into a plugin for jQuery or Prototype, and I might just do that, but right now it’s getting late, so I’m going to sleep instead.

I got hacked, via RoundCube

April 23rd, 2009

So for the last couple of weeks or so, there has been potentially participating in DDOS attacks (more likely it was sending spam, actually), unbeknownst to me until today. Well, it explains some of the server instability I’ve been having lately.

For some reason, Apache had been dying on me every few days.

I finally looked in my error.log file, and saw the output of wget, downloading a file called k.c from http://66.90.103.116/k.c (they’ve taken it down since, sometime within the last couple of hours. Perhaps they noticed my poking around at their server). Anyway, somehow they were getting in through apache somewhere, downloading this file, compiling it, and running it.

The code itself (a derivative of kaiten.c logs into an IRC server and watches for commands on which servers to attack or commands to run.

I eventually located the point of entry as a bug in the version of Roundcube webmail I was running. I was running a really old version of it (something like version 0.1 beta, I think), and all it took was an apt-get install of the latest version and the security hole is gone.

I’m going to add the news feeds of any software I’m using on this server to my RSS reader in the hopes that I will find out about such security holes (or at least software updates) a bit sooner in the future. I’ll also try to make it a habit to do a apt-get upgrade more often as well.

EDIT: I’ve set up cron-apt as suggested, so that should help me keep things up to date.

q, textual queue manager

April 21st, 2009

I wanted a quick, command-line way to handle a list of to-do items and to show me the next item that I want to work on, so I hacked together a quick little program that manages queues for you.

It’s handy for those times where I think of something to do while working on a project, but I am already working on something. With this I can just append it to the end of my queue for that project and forget about it until later.

The code can be gotten from bitbucket, if you are interested.

You can use it like so:

Push items to the top of a queue:

$ q todo push 'do that one thing'
do that one thing
$ q todo push 'do that other thing'
do that other thing

See what’s at the top of a queue:

$ q todo
do that other thing

Pop items from the top of a queue

$ q todo pop
do that one thing

Append items to the end of a queue:

$ q todo append 'do some more things'
do that one thing

The help q prints out if you call it with no parameters:

$ ./q.py 
usage: ./q.py queuename [command [params]]
  commands:
    push       Add one or more lines to the queue
    all        Show all the items in the queue
    append     Add one or more lines to the end of the queue
    pop        Remove the top item from the specified queue and push it onto the .done queue for that file
    next       (default) Return the top item in the queue

Other commands I plan on adding include “rot” to swap the current top item with the next item (or with a numerical parameter to move it even further down).

I’ve been experimenting around with Mercurial, and since that was also written in Python, I was wondering what it would take to rewrite this as a hg plugin. It could be handy to use something like this to manage a todo file. It could add some output to show what todo items were marked as done for each commit and perhaps also do a pre-commit hook where it pulls any new lines starting with “TODO:” and adds them to the todo file.

Untiny that url!

April 11th, 2009

There has been some talk about and arguments against and responses to issues about using rev=”cononical” for referencing shorter URLs instead of the automated use of TinyURL when posting to sites like Twitter.

I must say that I agree with Ben Ramsey (see “arguments agains” above) in suggesting we use rel=”alternate shorter” instead.

I also like the idea that Chris Shiflett had of using a HTTP header and a HEAD request to make it so you neither have to retrieve the entire requested page nor parse any HTML. I’d stick with Ben’s suggestion, however, and make the header something like “X-Alternate-Shorter:”, rather than “X-Rev-Canonical”. What’s the harm in calling it something that actually makes sense?

The idea of using HTTP HEAD requests to solve the problem inspired me to come up with a more immediate solution to one of the problems introduced by using url shortening services: uncertainty about where a URL leads.

This problem can be solved on the client side, which requires no work on the part of Twitter (meaning this is more likely to be put into use sooner).

Since most URL shortening services use an HTTP redirect to do their job, all it takes is a HEAD request to the tiny URL in question, and then a look at whatever “Location:” header is returned to see what the real URL is. In fact, you don’t even really need to do a HEAD request in most cases, since most URL shortening services don’t return any body, since they are just redirecting you anyway.

Read on for more information and implementations of an untinyurl function in various languages.

Read the rest of this entry »

The Tiniest GIF Ever

March 15th, 2009

Yesterday I was base64-encoding an image so I could send it to CouchDB to test some code I’m working on for a client. It reminded me of something I did a while back to set cookies on a remote server.

Basically, a small PHP script was put on the remote server which took a couple of GET parameters and set some cookies based on their values. The script then output a 1×1 transparent GIF. A PHP script on the local server generated an IMG tag which linked to this image and set the parameters based on the COOKIES on the local server.

This process also had to happen in the reverse direction, so I had to send the script to developers on the other side. I wanted to keep it as simple as possible, so I put the actual image contents in the PHP file as a base64 encoded string. I used the GIMP to generate the smallest transparent GIF I could manage so there wouldn’t be too huge of a nasty string in the file. I came up with something like the following:

< ?php
setcookie('foo', $_GET['foo']);
header('Content-Type: image/gif');
echo base64_decode('R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==');
?>

Remembering this got me to wondering, how small could you make a GIF? The file generated by the GIMP was only 43 bytes, but it seemed to be that you should be able to make a file which is representing a single pixel a bit smaller than that.

So, with equal parts of determination and derangement, I set about finding out.

Though of somewhat dubious usefulness, I managed to generate a perfectly valid GIF of only 26 bytes in length, which has the potential to display completely differently in various different software.

Read on to see how I found my way to this point.

Read the rest of this entry »

First steps to an Erlang OpenID consumer

January 21st, 2009

I’m working on a little project in Erlang and I wanted to use only OpenID for my authentication. It turns out there is currently no Erlang OpenID consumer library (or if there is, I couldn’t find it).

So I’ve started writing my own. So far I’ve got the first necessary step complete: HTML-based discovery.

I’m starting with version 1.1, simply because it is shorter and requires less (I don’t want to implement the XRI or Yadis protocols just yet).

It turns out that mochiweb comes with an HTML parser, so I used that, since I’m using mochiweb for my application. The parsed HTML comes back as a series of nested tuples of the format {<<”tag”>>, Attributes, Children}, where “tag” is the tagname (the root will be <<”html”>>, for example), Attributes is a proplist of that tag’s attributes, and Children is a list of more tuples of the same format and/or binaries with the contents of text nodes. Everything is represented as binaries, so I use those directly rather than converting between strings and binaries.

Here’s the code which finds the link tags with rel=”openid.server” and rel=”openid.delegate” (if it is there):

get_openid_server(Identifier) ->
    NormalizedIdentifier = normalize_identifier(Identifier),
    case http:request(NormalizedIdentifier) of
        {ok, {_Status, _Headers, Body}} ->
            HtmlTokens = mochiweb_html:parse(Body),
            find_openid_tags(HtmlTokens);
        _ ->
            {error, http_error}
    end.
 
normalize_identifier(Ident = "http://" ++ _Rest) ->
    Ident;
normalize_identifier(Ident) ->
    "http://" ++ Ident.
 
find_openid_tags(HtmlTokens) ->
    case find_tag(<<"head">>, [HtmlTokens]) of
        {<<"head">>, _Attrs, Children, _Rest} ->
            case find_tag_with_attr(<<"link">>, {<<"rel">>, <<"openid.server">>}, Children) of
                not_found ->
                    {error, openid_server_not_found};
                ServerAttrs ->
                    Server = proplists:get_value(<<"href">>, ServerAttrs),
                    case find_tag_with_attr(<<"link">>, {<<"rel">>, <<"openid.delegate">>}, Children) of
                        not_found ->
                            [{server, Server}];
                        DelegateAttrs ->
                            Delegate = proplists:get_value(<<"href">>, DelegateAttrs),
                            [{server, Server}, {delegate, Delegate}]
                    end
            end;
        not_found ->
            {error, no_head_tag}
    end.
 
find_tag(_TagName, []) ->
    not_found;
find_tag(TagName, [{TagName, Attributes, Children} | Rest]) ->
    {TagName, Attributes, Children, Rest};
find_tag(TagName, [{_OtherTag, _Attributes, Children} | Rest]) ->
    find_tag(TagName, Children ++ Rest);
find_tag(TagName, [_Other | Rest]) ->
    find_tag(TagName, Rest).
 
find_tag_with_attr(_TagName, {_AttrKey, _AttrVal}, []) ->
    not_found;
find_tag_with_attr(TagName, Attr = {AttrKey, AttrVal}, Tags) ->
    case find_tag(TagName, Tags) of
        not_found ->
            not_found;
        {TagName, Attributes, Children, Rest} ->
            case proplists:get_value(AttrKey, Attributes) of
                AttrVal ->
                    Attributes;
                _ -> 
                    find_tag_with_attr(TagName, Attr, Children ++ Rest) 
            end
    end.

(the <PIPE>s above should be “|”s and the <SEMI>s should be “;”s. Not sure why the syntax highlighter is doing that to them…

Assuming the above code is put into a module called “openid”, you get the following:

1> openid:get_openid_server("blog.paulbonser.com")
[{server,<<"http://www.livejournal.com/openid/server.bml">>},
 {delegate,<<"http://misterpib.livejournal.com/">>}]
2>

As I said, this is the first step. Hopefully I’ll have some time very soon to get on with the next couple of steps, and then I’ll be done.

EmotionML

November 25th, 2008
<emotionml xmlns="http://www.w3.org/2008/11/emotionml">
    <emotion>
        <intensity value="0.4"/>
        <category set="everydayEmotions" name="surprise"/>
        <link uri="http://www.w3.org/2005/Incubator/emotion/" role="triggeredBy"/>
        <link uri="http://blog.paulbonser.com/2008/11/25/emotionml/" role="expressedBy"/>
     </emotion>
    <emotion>
        <intensity value="0.7"/>
        <category set="everydayEmotions" name="amusement"/>
        <link uri="http://www.w3.org/2005/Incubator/emotion/" role="triggeredBy"/>
        <link uri="http://blog.paulbonser.com/2008/11/25/emotionml/" role="expressedBy"/>
     </emotion>
</emotionml>

Don’t complain if it doesn’t conform, because it’s not a fixed standard yet. ;)

A prefix notation programming language

November 16th, 2008

Prefix notation?

Have you ever dreamed of a language which uses strictly prefix (a.k.a. polish, Ɓukasiewicz) notation?

No? Well, I can’t say I’m surprised. Lisp is often called a prefix notation language, but I’ll let you in on a secret, it’s not purely prefix notation. It uses another notation you’ve probably never heard of: outfix notation.

Outfix notation?

I’d say I made outfix notation up, but I found a reference to it on abstractmath.org, so I at least have something to back this claim up with. Basically, the parentheses are a function which says, “put these items into a list.”

Of course, Lisp uses lists for everything, so you can hardly call it a prefix notation language any more.

Real prefix notation

Now, how about making a real prefix notation language? A real prefix notation language needs no parentheses because it knows how many arguments each function takes, so it can simply pull in the next two expressions following the function name.

A real prefix notation language is a piece of cake to implement, as long as every function has a fixed arity and that arity is known at compile time. Of course, then how do we represent things such as lists with varying amounts of items. How do we pass a variable number of arguments to a function?

The same way Lisp does, we use a list.

Read the rest of this entry »

What I'm Listening to

Loading...