Your browser is very old. You might enjoy surfing the web more if you used something newer like:

Google Chrome

Even Firefox would be OK.

If you're being forced at gunpoint to use Internet Explorer, you should at least upgrade it. Version 8 is tolerable and 9 will be OK when it comes out.

Posts from February 2009

The shapening

Everyone has a collection of defining moments in from their past and they can trot out at least a couple of them without evening having to stop and think.

Find the person in closest proximity to you and ask them.

Then go ahead and think of two of your own right now.  You’ve lived a hollow and meaningless life if you didn’t immediately have two in mind at the end of that last sentence.  OK, maybe that’s a little harsh.  But you could probably have gotten out a bit more growing up.

I have lots of what I like to call secondary defining moments (like the first breast I ever got to touch that was not in the context of nursing and belonged to a real girl.  More on this later).

But the really insane moments divide your life into two sections.  Everything that happened before and everything that happened after.  I’ve already talked about my first time online which pretty much cemented my life as a computer geek.  Now it’s time to talk about one of the big ones.

I spent two weeks in the summer of 1993 at the Fir Acres Workshop in Writing and Thinking.  There were about 20 of us.  We lived in the dorms, we wrote every day, took writing classes.   I wore skirts, painted my toenails black, climbed soda machines, read poems out loud in the Lewis & Clark Chapel and went delightfully insane in a way that I’ve never quite been able to replicate (though not for lack of trying).

There was particular moment, the first day of the workshop, when I realized that things were going to be different.  I was in my morning writing class in an upstairs conference room of the Bodine building.  We were all sitting around a long rectangular table in a windowless room with zebra curtains along one wall.  We had just spent 15 minutes free writing and we going around the table reading aloud.  I even remember the starting topic which was to talk about what we had brought with us to the workshop.  I remember writing something about bringing a lot of socks.  “One can never have too many socks.”

I finished reading my piece and the next kid down the table started to read and I don’t remember the specifics of what he wrote but it was vulgar, full of profanity, and utterly hilarious.  I was shocked.  This kid was swearing in front of a TEACHER and he wasn’t getting in trouble.  Not only was he not getting in trouble but that fact that he’d written something fairly obscene was a complete non-event.  I had been writing a lot for several years at the point but it was all pretty benign and safe.  I hadn’t known that people my age could write like that.  It was like being given permission to be dangerous.

Every day consisted of writing.  Sometimes it was writing in class, which I found frustrating at best.  I was in Anne’s class and, while I feel sorry for her now, she drove us crazy.  She was in love with The Jump Off Creek by Molly Gloss and most of her exercises revolved around it.  My impression was that the other two classes were much more free-form, that the students were given more freedom to drive.  The consensus in our class was that we had “moved beyond” what Anne was trying to do and that she was “holding us back”.  You have to love the hubris of teenagers.  I really regret now what a hard time we gave her but I feel fortunate that I actually ran into her again a number of years later and was able to apologize.

I’ve gone through so many drafts of this piece, trying to portray things the way I felt them then and I don’t think I’ll ever get it quite right.  Here are two memories of the hundreds I have from those two weeks.

#1

It’s summer, 1993 in downtown Portland.  I am 14 years old and I haven’t slept in three days.  I am sitting on the hard floor of the Oregon History Museum, my jeans stiff with my legs folded underneath me.  I’m holding a notebook with a green cover that I have drawn peace signs all over.  At the time, I am completely unashamed of this fact.  I’m wearing a cheap, sterling silver, marijuana leaf ring that I purchased from a portable head shop at Saturday Market.  The ring is chaffing my fingers as I scribble frantically.  There is a column of pictures in front of me.  Pioneers, wagons, and a haggard gypsy women who’s black & white stare is drilling through me as I write about it.  I do this for 30 minutes or so and then move on another picture but I can’t recapture the intensity of that first moment with the gypsy.

Vince and I decide to duck into the museum theater to see the presentation about witches while the rest of the group moves to another room.  We take seats in the middle of the entirely empty theater.  To this day, I have no memory of the movie because we both fall asleep in the warm dark of the theater.  The three sleepless nights that have been chasing me finally catch up.

At some point, one of us wakes up and shakes the other.  We leave the theater and try to rejoin the group which has, predictably, left the museum.  There is a bus near a fountain at Saturday Market waiting to take us all back to campus.  Vince and I just have to figure out how the fuck we are going to find that bus.

Some amount of wandering around outside the museum finds a light rail stop.  Which way to we have to go?  Is it uphill?  I remember the river.  I know we have to get back to the river and that big bridge with all of the market booths underneath.  We scrounge up the train fare and hop on, heading through downtown toward the fountain and that bus.

We arrive and the bus is loaded and idling.  Teachers are presumably there scolding us but I only remember the lightness of my feet as we run, cackling, up the bus steps and collapse into open seats.  Lightness in my feet and relief in my chest that we haven’t been left behind.

That I am not alone.

#2

The three and I are sitting in one of the lounges of Alder Hall reading poems and scratching each others heads.  I don’t remember a thing we read, just the feel of many long fingernails digging wonderfully into my scalp.  The smoking of cloves is decided upon and so we walk down the long stairs past Tamarack lounge on the right and Juniper Hall on the right.  There are at least two cloves between the four of us, being passed back and forth.  My lips are slightly numb and my head is swimming as we pass the cafeteria, cross the grassy area in front of the biology building, and down the Albany Quadrangle stairs toward the Fir Acres theater.

The theater has a rising spiral staircase at one corner that leads up to a door that is never unlocked.  We climb the stairs and sit, smoking in the dark, with our legs dangling through the green wrought iron of the banister.  There is some sort of leap in my brain now and I lose all track of time.  I don’t remember if it is warm or cold but there is conversation and smoking and stars and my lips are still numb.  We are on lower campus before I am completely aware again.  We stuff our pockets with roses and take communion with them in one of the stone gazebos.  Taking it in turns to kneel to accept the bitter petals into our mouths.  I am wearing red cotton shorts and a t-shirt and no shoes and the cobblestones of the gazebo are painful beneath my knees.  My whole world is tilting when it’s my turn to kneel.

I have a film canister full of mud from earlier the day.  We had visited an abandoned farm with a pond and the sexiness of the mud was discussed at great length.  I open the canister and we paint stripes across our cheeks and our noses and our foreheads.  I spend the next day trying to avoid washing my face.  We’re near the fountains now.  Near the lion head that sticks out of the side of the middle terrace and spits icy water into the reflecting pond.  A shared look is passed between us and we are suddenly stripped down to our underwear and running through the fountains.  Washing our hair in the icy steps below the lion.  Painting his granite face with water.

Reading back through my writings in the days after, I find constant references to the daub of mud and the crunch of petals.

#3
(This one is straight out of my notebooks)

I was talking Siri the other day. I had played Toccatta & Fugue and she told me she had transmogrified. She had been in a room with a playing organ but no one was playing it. She had on a white dress with no shoulders and she was sitting in a velvet chair with cloth covered armrests and there were lots of wooden chairs and tables set up but she was alone. Then a man with a swirling black cape came in and he stared at her and she stared back and she kind of wished he would ask her to dance but she didn’t mind that he didn’t. Then the music stopped and the man in black walked out and she returned.

It was just a quick flash. Bright light. She sat stilly, in front of me at about 10:00pm. She had on overalls and she had a huge bunch of raw flowers in her lap. Lots of green and purple.

I had started that summer with two years of high school left.  After my return from Fir Acres, I was determined that the next year would be my last.  I took night classes at the local community college.  I arranged to do independent study for the senior history class.  I worked my ass off and my reward was graduating a year early and getting the fuck out.

I went to Lewis & Clark in the fall of 1994 and graduated in 1998.  While I was there, I met the woman who would become my wife.  Another defining moment.

It’s been 16 years since I went to Fir Acres and I still think about it all the time.  It’s not an exaggeration to say that those two weeks in 1993 changed me completely.  I stopped being afraid after that.  I had found proof that there were people in the world who understood me and that gave me hope that I could find people like that again.

The course of my life was set.

Me, Summer, 1993

Writing a simple Twitter-bot in PHP

OK kiddos, buckle up because today we’re going to write a simple PHP Twitter-bot that:

  • Gets a list of a user’s direct messages.
  • For each direct message, replies with the current date and time.

You’re going to need a few things to get started:

  1. You’ll need two Twitter accounts. One that you can send messages from and another to make API calls.
  2. A web server with PHP 5+ and cURL. I’ve done this on both CentOS 5 and XAMPP on Windows.

The Twitter REST API is very well written and simple to use. Since it’s a RESTful API, all we’re doing is using cURL to call various URLs. Retrieving data is a GET request while sending/deleting data is a POST request.

Step 1: Get a list of direct messages

$username = "Your Twitter Username";
$password = "Your Twitter Password";
$url = "http://twitter.com/direct_messages.json";

$httpReq = curl_init();
curl_setopt($httpReq, CURLOPT_URL, $url);
curl_setopt($httpReq, CURLOPT_RETURNTRANSFER, true);
curl_setopt($httpReq, CURLOPT_USERPWD, $username . ':' . $password);

$jsonret = curl_exec($httpReq);
curl_close($httpReq);

$data = json_decode($jsonret);

We’re doing a GET of http://twitter.com/direct_messages and sending our Twitter username & password via HTTP Basic Authentication (the only authentication Twitter fully supports so far).

Here’s the fun part. See that .json at the end of the URL?

That’s telling Twitter that we want the direct message results back in JSON format. We could just as easily get back results in XML (.xml) or RSS (.rss)

I like to get JSON-encoded responses because then I can turn them into PHP objects with json_decode.

In this case $data is an Array of PHP stdClass objects.

Array
(
    [0] => stdClass Object
        (
            [sender] => stdClass Object
                (
                    [description] =>
                    [screen_name] => antelopelovefan
                    [url] => http://antelopelovefan.com
                    [name] => Mark Biek
                    [protected] =>
                    [profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/74213403/m34_tiny_normal.png
                    [location] =>
                    [id] => 3556041
                    [followers_count] => 17
                )

            [created_at] => Mon Feb 16 21:41:34 +0000 2009
            [recipient_id] => 99999999
            [sender_id] => 3556041
            [recipient] => stdClass Object
                (
                    [description] =>
                    [screen_name] => faketwitterbot
                    [url] =>
                    [name] => Fake Twitter Bot
                    [protected] =>
                    [profile_image_url] => http://static.twitter.com/images/default_profile_normal.png
                    [location] =>
                    [id] => 99999999
                    [followers_count] => 1
                )

            [sender_screen_name] => antelopelovefan
            [text] => This is another test message
            [id] => 60474989
            [recipient_screen_name] => faketwitterbot
        )

)

With the above, it’s trivial to iterate over the list of messages.

foreach($data as $message) {
  echo 'Message from ' . $message->sender->screen_name . '';
}

Now that we can get our hands on the direct messages, it’s time to send a response.

Again, this is really easy. It’s just a matter of using the correct URL and POSTing the correct values to it. This code is just like the code to retrieve the list of messages

$username = "Your Twitter Username";
$password = "Your Twitter Password";
$url = "http://twitter.com/direct_messages/new.json";
$postData = array('user'=>'antelopelovefan', 'text'=>'The current date/time is ' . date('c'));

$httpReq = curl_init();
curl_setopt($httpReq, CURLOPT_URL, $url);
curl_setopt($httpReq, CURLOPT_RETURNTRANSFER, true);
curl_setopt($httpReq, CURLOPT_USERPWD, $username . ':' . $password);
curl_setopt($httpReq, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($httpReq, CURLOPT_POST, true);
curl_setopt($httpReq, CURLOPT_POSTFIELDS, $postData);

$jsonret = curl_exec($httpReq);
curl_close($httpReq);

$data = json_decode($jsonret);

The only difference here is that, since we’re sending data to the API, we need to use POST instead of GET.

We also pass a couple of parameters with the request. The first is the Twitter username of the person we’re sending the message to and the second is the message itself (remember, 140 characters max!). The return value is an encoded copy of the message you just sent.

We probably don’t want to respond to the same messages over and over so let’s delete each message when we’re done.

foreach($data as $message) {
  $username = "Your Twitter Username";
  $password = "Your Twitter Password";
  $url = 'http://twitter.com/direct_messages/destroy/' . $message->id . '.json';

  $httpReq = curl_init();
  curl_setopt($httpReq, CURLOPT_URL, $url);
  curl_setopt($httpReq, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($httpReq, CURLOPT_USERPWD, $username . ':' . $password);
  curl_setopt($httpReq, CURLOPT_HTTPHEADER, array('Expect:'));
  curl_setopt($httpReq, CURLOPT_POST, true);

  $jsonret = curl_exec($httpReq);
  curl_close($httpReq);

  $data = json_decode($jsonret);
}

In this case, the return is a list of the remaining messages.

There are lots of Twitter libraries in different languages. However, as part of this exercise, I’ve written a couple of simple PHP classes.

  • TRequest.php is a base class for doing Twitter requests. The idea was to build specific types of requests on top of this class.
  • TDirectMessages.php is a simple class for handling direct messages and extends TRequest.

And here’s the code for implementing a simple Twitter-bot like the one I described above.

Event handling with PrototypeJS

I’ve talked about the basics of PrototypeJS a bit before so I hope you’re convinced about the awesomeness of Prototype.

Now I want to talk a little more about how Prototype can make event handling easier.

You’re probably used to handling Javascript events by defining a function and then specifying the different event calls inline. This can get hard to keep track of over time. You have to remember to add the function call in every time you add a form element. It can also cause trouble if you have to change the call for the event because you have to go and change it everywhere.

<head>
  
</head>
<body>





</body>

Now here’s the Prototype way

<head>
  
</head>
<body>





</body>

The functionality here is exactly the same as the first example but we’ve taken the important step of removing the Javascript code from the HTML. This makes it easier to change the functionality of click event as well as making it easier to handle changes to the HTML.

Here’s a practical example. Let’s say we’d like an easy way to have some links popup in new windows while other links open in the same window.

In this example, we’re going to set it up so that every link with a class of offsite will popup in a new window.

<head>
    
</head>
<body>
    Onsite Link
    Offsite Link 1
    Offsite Link 2
    Offsite Link 3
</body>

We use the $$ to get all a tags with a class of offsite. Then we define a click event handler for each link which pops up a new window.

There’s one new thing here to be aware of:

  Event.stop(event);

This stops the default action of the event. In this case, without it, clicking on the link would popup in a new window and in the current window.