Programming is a wonderful mix of art and science; source code is both a poem and a math problem. It should be as simple and elegant as it is functional and fast. This blog is about that (along with whatever else I feel like writing about).

Sunday, December 16, 2007

I Finally Discovered Flex

Just a little while ago I was considering the possibility of pre-built PHP Display Components, which would allow me to build applications faster and re-use a lot of the boilerplate code that I currently spend too much time on. And once those components are built, they could be improved individually, which would make all my applications better without having to do anything.

It seemed like a good idea, and while considering how I might go about doing it, I discovered Adobe Flex. I'd heard of it before, as "Flash for developers," but had never been that curious. Having investigated Flash before, I was not interested in having to purchase a visual development environment and then messing around with timing, tweening, layers, and all the other crap Flash puts you through.

But Flex isn't like that at all. In fact, it's essentially just a set of visual components you can use in building a visual interface, along with a slew of classes for connecting to web services and easily binding XML data to the visual components. Additionally, ActionScript appears to be what JavaScript wishes it were ... which is nice.

Best of all? They provide a free SDK with a command line compiler. So as long as you're willing to actually write the code (rather than drag-drop-connect, which seems to be the direction the IDE companies want programming to go), you don't have to pay a dime and can check Flex out. So I did.

I decided to write a quick program to calculate quarterback ratings. Since the ratings formulae are different in the NFL and in college, I figured I'd have it calculate both.

Here are links to the app and the source code.

The first thing I did here was set up the visual interface, which is at the bottom. I used Flex's Label, TextInput, and Button components to build a simple form. I used absolute positioning because it's supposed to be better for performance (and because all the examples on Adobe's site use it, which means I haven't learned much about their automatic layouts yet -- I certainly would like to).

These components should be pretty familiar to anyone who's used HTML and Swing ... the tags seem to be a mix between the two, which is pretty interesting.

After writing the interface (and compiling and testing it to make sure it looked the way I wanted it to), it's time to add the functionality itself. The calculations will be done by ActionScript, in the <mx:Script> tag. It's a lot like JavaScript, except that you can define strong types and public/protected/private status, both of which are nice additions. The functions in here are simply designed to pull the data from the input fields, convert to Numbers, apply the formula, and set the label.

The one slightly non-basic feature I used in this program is NumberFormatter. Flex claims you can instantiate any component either with tags or in the script code, but the only way I got this working was to make an <mx:NumberFormatter> tag and reference it from the script. It's actually pretty interesting, and once I get used to having to do that, I may grow to like it.

I then went ahead and compiled it, and it worked quite nicely. Flex looks like a promising way to build web applications -- it's even possible that I could grow to prefer it to PHP + AJAX for my own applications.

Saturday, December 08, 2007

PHP Display Components

Just about every GUI language/framework has standard classes for displaying common datatypes. There are datagrids, sortable datagrids, paginated lists, searchable lists, input forms, display forms, etc. You instantiate them, set up some information about them, and connect them to your data source. Then you call some sort of display() method on the object, and it displays everything on the screen.

The reason I mention this is because PHP has nothing like this (at least not that I know about). In PHP, the View part of MVC is merely an HTML-based layout file with some markup in it to display your data. But isn't is possibly to create a set of components that generate the HTML on their own?

Obviously, we could all just continue to code the HTML in our Smarty templates, recreating the same functionality over and over again in "low level" HTML. On the other hand, we could create components at a higher level of abstraction, and when we figure out a better/cooler way to do that searchable+paginated list (maybe adding some Javascript), we do it once -- in the component -- and it works everywhere we're using it. That's much better than having to change HTML code everywhere we're displaying a list of data (um, a lot).

So what are the goals of these display components?
  • Define a set of reusable components that handle the display of data on a web page and generate the HTML
  • Concentrate the HTML/JS of your application in component code, out of sight
  • Ability to easily create new components, or edit existing ones as needs arise
  • Skinnable -- either set CSS values in the code, or assign a CSS file to the object (also allow for a default CSS file to be set sitewide)
  • Allow you to stay at a higher level of abstraction, so you can get more done with less code
These seem like reasonable goals. They're not trying to shoot the moon ... and they don't seem to demand that you develop a certain type of application if you use these components. However, the problem of defining what components are necessary then quickly arises.
  • Lists of data
    • Paginated
    • Searchable
    • Sortable
  • Header
  • Footer
  • Sidebar
  • Input form
  • Display form
  • Calendar
  • Date selector
    • Single date
    • Date range
  • Time selector
    • Single time
    • Time range
  • Popup dialogs
    • Modal
    • Non-modal
  • AJAX
    • Periodical updating
    • Response to user action
    • Connect a URL-defined data source to a component
That's a start, anyhow. More components are probably necessary.

There should probably be a general Page class, or something, that you would attach the other components to. The point of that would be to set pagewide CSS and only being required to call the display() method once per page.

In the interest of separating this from the concept of "scaffolds," I think the way it should work is that each component has a standard/default HTML template that it draws from, and the file it uses is an object variable. If you want, you should be able to create a brand new HTML template and make your component use it instead -- it would be nice to have that kind of flexibility.

Right now ... I don't know if this is feasible. I don't even know if it's a good idea. I'm sure people have tried to do this before, and I've never heard of the results. At the moment, my plan is to think about it for a while longer, and if I continue to think it's a good idea, it may be worth spending a bunch of time on to see what I can come up with. Could be interesting. (Let me know your thoughts, if you have any.)

The First Week -- Mostly Waiting

I just finished my first week on the job. I don't know how typical an experience it was, but I'll run down a quick overview of how it went for me.

It was "Team Week," which means that everyone who works in offices around the country all get together in Chicago for a week of project planning (during the day) and partying (at night). As a general rule I would have jumped on the partying train after work, but I'm adapting to a new lifestyle -- one that involves waking up early and commuting to work -- and have been pretty tired. I don't want to throw a hangover on top of that process. It's already hard enough to prevent myself from drinking coffee.

I really like the team I'm working with, so it's a bit of a shame that they've now all gone back to their respective homes and we'll have to work remotely. But they've been successfully doing it for a while, so I'll just have to slide right in and contribute.

And on that note, I was completely unable to "slide right in." I expected it to take a day, maybe a day and a half, before everything was set up and I would be working. Alas, no. There were numerous problems with waiting for IT, and one entire day was lost because the one guy who knew what we needed to take a step forward missed a day (spent it with his son in the ER -- apparently everything's okay now). I spent most of the week reading source code, but with no access to the repository or a development server, nor any direction on what to do. Finally, on Thursday, I was assigned projects, and on Friday, I was told what they actually want. But I'm still waiting on CVS access.

In my first week on the job, the vast majority of my time was spent on non-work tasks. I don't think that's very unusual, but it feels weird to have to "wait" like that after you've started the job. From the reactions of the rest of the team, they seemed to expect that it would take 2-3 days. By the end of the week they were getting as frustrated as I was that I still couldn't work.

Hopefully everything gets set up quickly, and next week goes a bit better.

Friday, November 16, 2007

Becoming a Consultant

Last week I decided to look for work. From what I can tell, the best way to do that is to throw your resume up on dice.com and wait for the calls to roll in (well, the best way is probably to know someone who'll get you a job more easily, but I don't). I didn't have to wait long until I had a couple of promising contacts with what I assumed were both recruiting firms. I set up face to face interviews with both of them.

As it turned out, the first firm was in fact a recruiting firm who had a permanent position in mind for me. Everything seemed to go well, and when I left the meeting I felt good (which was significantly different from how I felt when I went in ... I was quite nervous). They were going to send my information along to their client, and I'd have an interview on Monday. While waiting for my next interview a couple hours later, I decided to have lunch at Potbelly Sandwich Works, who make delicious sandwiches for a low low price. (I guess it's not as low as Jimmy John's ... but Potbelly actually cooks their sandwiches.) I got my usual, the "Italian on Wheat." I love restaurants where you can order something that sounds almost non-sensical, and they know exactly what you mean. While eating my sandwich, I took the opportunity to get nervous again. After all, the second interview was in the Sears Tower, which is designed to be intimidating ... and is successful. It has as much security as an airport, and is much, much taller.

I stood outside the massive tower, unable to see the top, for about an hour and a half. This did not help the state of my nerves. Finally, I decided to call my contact at the recruiting firm to get this show on the road. He came downstairs and we held our meeting in the Starbucks in the lobby. I declined the offer for coffee, since I don't drink the stuff, but he insisted "Come on, make me feel good," and I was obligated to order a small bottle of orange juice. It was delicious. You've got to love expense accounts.

Early into our meeting, I learned that this company was not really a recruiting firm, but was instead a consulting firm. It was SPR, and he spent a considerable amount of time convincing me about the greatness of the company. And you know those cases where someone tries really hard to make you think they're great, but the whole time you're sitting there thinking "That doesn't sound so great," and waiting for them to let you leave? Well ... this wasn't one of those times. He didn't have to try very hard at all, because he had a lot of "we're great and it's pretty self-evident" material. He went on to describe the client I'd be working for, and it sounded like a great situation and a great person to work for.

I left that meeting excited about working with SPR, and again nervous since I had to pass a technical screening followed by a face to face interview with the client if the technical screening went well. I had to wait a few days (it was a weekend) for the phone screening, and as it turned out I didn't need to be so nervous (as had been the case every time). I had the interview the next day, and so the next morning I hopped on the bus and rode downtown. I didn't know exactly where to get off, so I sat there the whole time with my iPhone out, matching the streets on Google Maps with the stops on the way. That worked fine, because I managed to get off on the correct street.

This interview was mostly over lunch, and was with the guy I'd be working for as well as another developer I'd be working with. It turned out that they were both vegetarians, and I ordered a meat ravioli (in other words, something that you know exactly what it is when you hear the words, which I don't like as much). At first I thought "What if they think I'm one of those heartless meat-eaters?" Then I immediately thought "If the fact that I'm not a vegetarian is any kind of an issue, would I really want this job?" Neither of them had a second thought about it. That was excellent. So was the rest of the lunch interview. After lunch, the boss went back to work and the developer gave me a tour of the office, and after a little while I went home feeling pretty good about my chances.

When I talked to my dad, he tried to manage my expectations and keep my feet on the ground (though they already were). "Don't get too excited, you don't have the job yet." Yeah. I know. Don't remind me. After that phone call, I was on the edge of my seat, staring anxiously at the phone. It took about two hours, but it rang and the voice on the other end said "I have good news and good news." Well, needless to say, that was good news! He told me the deal, and when I hung up the phone I was a consultant.

The whole way through the process I was nervous, and I shouldn't have been. The key is just to be yourself, and everything will go well. Now I have to wait two weeks before I can start (professional courtesy to the current employer), and then I get to get down to the part I'm good at, which is actually doing the work. It's all very exciting. And since I'll be paid by the hour, the number of 12 hour days will probably decrease just a bit (down from "every day except Sundays").

After I start, I'll know how I like it. I'll post my thoughts here, naturally. Until then, have fun.

Thursday, November 15, 2007

Apache Rewrite Rules

Everybody likes websites that have good, clean URLs. On a minor little project I'm working on on the site, I wanted to give that a try. So instead of seeing a URL like /index.php?username=user1&view=feeds, you'd see /user1/feeds. It's kind of cool ... and remarkably easy!

One assumption this particular projects makes is that index.php is the only page that'll be viewed. It checks the query string parameters and changes its behavior depending on that. I don't personally like this method, but it makes it easier to handle the rewriting rules.

Here's the .htaccess file you're going to want to put into your webroot directory:

RewriteEngine on
RewriteRule ^([a-zA-Z0-9]+)/?$ index.php?username=$1
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z]+)/?$ index.php?username=$1&view=$2
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z]+)/([a-zA-Z]+)/?$ index.php?username=$1&view=$2&action=$3
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z]+)/([a-zA-Z]+)/([0-9]+)/?$ index.php?username=$1&view=$2&action=$3&id=$4


So that seems simple enough. The first option on each line is the regular expression that you want to match. Each match within a set of parentheses corresponds to the $1, $2, etc, flags in the second option. The ^ at the beginning and the $ at the end are regex symbols signifying the beginning and end of the string, respectively. the /? right before the $ on each line makes it so the rule will match the URL whether there's a trailing slash or not. (For example, /user1 and /user1/ will work in exactly the same way.)

Thanks ... and enjoy!

Sunday, October 14, 2007

PHP Profiler

At ZedZone, we found we're having a few problems with performance on a few of our pages. So I needed to find a way to determine what parts of our pages needed optimization so we could speed everything up without wasting our time optimizing functions and queries that don't need it.

There are a few profiling packages available for PHP, but they require installing modules or PEAR packages, and it seemed to me that that's not necessary to profile your performance. So instead, I decided to write my own class.

What I wanted from my profiling class was the ability to measure the entire execution time of the script, as well as the execution time between any given points in the script. I wanted there to be any arbitrary number of measurable points in the script; it should be up to me to decide what parts of the script I want to measure, as well as how many such parts.


class Profiler {
var $startTime;
var $endTime;
var $marks;
var $report;

function profiler() {
//initialize the object
$this->marks = array();
}

function getMicroTime() {
$t = microtime();
$time = explode(' ', $t);

return doubleval($time[0]) + $time[1];
}

function start() {
//start the profiling
$this->startTime = $this->getMicroTime();

$this->mark('Start');
}

function mark($title) {
//mark the current spot
$this->marks[] = array(
'title' => $title,
'time' => $this->getMicroTime()
);
}

function finish() {
//shut it down
$this->endTime = $this->getMicroTime();

$this->mark('Finish');
}

function generateReport() {
$report = array();

$lastTime = $this->startTime;
$totalTime = $this->endTime - $this->startTime;
foreach($this->marks as $mark) {
$mark['diff'] = $mark['time'] - $lastTime;
$mark['percentage'] = ($mark['diff'] / $totalTime) * 100;

$lastTime = $mark['time'];

$report[] = $mark;
}

$report = sortArray($report, 'percentage');
$report = array_reverse($report);

$this->report = $report;
}
}

So the first thing to notice about the script is that when you initialize it, it only sets up the array for the profiling marks. In general use of the script, you call the start() method right after initializing the Profiler object, and the finish() method after all the code on the page.

Then after every function call, query, or section of code that you want to measure, call the mark() method, passing a string that identifies what's being measured between this mark and the previous mark. At the end of the script, call generateReport(), and you can either var_dump/print_r the report instance variable, or you can create another method called printReport() that builds a table to display the results of the profiling.

Note that the sortArray() function is not included in this script. In my code, it points to a quicksort that sorts an associative array by the values in the given key (as opposed to the sort functions that simply sort an array of strings or numbers, rather than associative arrays). I might post that later, but at this point the Profiler class only does this to sort the report by the sections of code that affect performance the most.

This class has worked pretty well for me so far, and hopefully it can be helpful to you too. If I find I need to add to it, I'll post further. Happy coding!

Monday, January 15, 2007

Getting iTunes to Recognize Your TV Shows

I have quite a few movies on my computer, as I've mentioned in previous articles. I've encoded most of them in H.264, which I find gives the best quality. Since I never felt like looking up my Quicktime 7 key (which I legally purchased when it came out, hoping it would allow me to encode DVDs more easily), I always played all my videos using VLC (because Quicktime doesn't let you do full screen). The process was annoying: I had to find the movie in the Finder, then drag it down to the VLC icon in the dock, then go to full screen. And VLC doesn't have an onscreen controller during full screen playback (at least not on Mac, I don't know about the status of other operating systems).

Needless to say, I started to find this pretty cumbersome. When iTunes first got the ability to play video, I jumped at the chance to have a program manage my video playing needs. I was grossly disappointed by how slow it was, and after a few hours of trying to set it up, went back to my Finder-VLC approach. Well, it's been a few iTunes updates since then, so I decided to give it another go.

The first thing you need to make sure you do is to set iTunes so it doesn't automatically move your files into the iTunes directory. This won't work at all when your main drive is full and most of your movies are on an external hard drive. Plus, it takes a really long time to transfer those files.

Adding the movies is very simple. Switch to the Movies tab on iTunes, then select all your movies, and drag them on over to iTunes. It'll chug for a little while, then give you a list of all your movies. You can set it to automatically play them full screen, which I like, and they give you a nice onscreen controller during full screen playback, which I like more.

But in addition to my movies, I also have quite a few television shows on this thing. And while iTunes does support TV shows, they seem to prefer that you buy them from the iTS rather than play your own. But I don't feel like repurchasing all these shows from Apple, so I need to get iTunes to recognize that they are, in fact, TV shows instead of Movies.

For an individual episode, this isn't too bad. You go to Get Info, then Video (a tab on top). Here you can set it to TV Show, and also enter the name of the show and the season number. Cool.

But that's really cumbersome if you have a lot of TV shows. You know, like a season. Or ten. Or, in my case, many many more. There MUST be a better way!

Doug's Applescripts give us Set Video Kind of Selected, which allows you to do this very thing to an arbitrary number of files. Awesome. Just download it, toss the Applescript file into /Users//Library/iTunes/Scripts, restart iTunes, and you're ready to get started.

Select your files:


When you drag them to iTunes, remember to select them all again and choose the script from the Applescript menu:


This will bring up a little dialog box where you can change the Video Kind to TV Show, the Show Name to, for example, "The Simpsons" and the Season Number to, say, 6.

It chugs for a few seconds, and then it says it's done. Popping over to the TV Shows tab in iTunes shows us that it did in fact work nicely, turning 5 or so minutes of tedious data entry into just a handful of seconds of just telling your computer what you want.



And the TV Show interface is kind of slick. Maybe it's possible for it to be a bit nicer or more usable, but come on ... it's easily a dozen times better than Finder+VLC. And iTunes certainly isn't as slow as it used to be.

And now I'm off to watch a bit of television. In iTunes. Tally ho!

Sunday, January 14, 2007

Is the NFL Fixed?

I feel like I'm the only person in America who hates the New England Patriots. That's like hating apple pie and Neil Armstrong! How could anyone hate the Patriots? They're an American flag with a football, and they're so good as to be unbeatable. But does anyone remember a time before their dynasty started, and exactly when it happened?

In the year 2000, the Patriots were 5-11. (2000 Standings.) They weren't a good team. At the beginning of the 2001 season, nobody expected them to do anything, and for good reason. They started off 0-2, as expected. Then the unthinkable happened. The World Trade Center towers got knocked down, and everyone needed to pull together and be patriotic. And ... the Patriots started winning. A lot. Tom Brady, a nobody, a quarterback from the Big Ten (which is not very well known for producing great quarterbacks these days), who didn't play at all in 2000 (not technically true; he played in 2 games, and was 1-3 for 6 yards and 0 touchdowns), suddenly became the best quarterback in the league. People are now trying to go so far as to say he's the best quarterback of all time. (This is complete crap, by the way. Johnny Unitas, Joe Montana, Dan Marino, Brett Favre ... at least you can say Brady's name in the same sentence, but he's not as good as any of them.)

In 2001, the Patriots won the Super Bowl, after an amazing turnaround from the previous season. They started playing well after a big tragedy. And the "dynasty" has been going strong ever since. After the 2001 season, I had begun to suspect that something fishy may be going on in the NFL. How did the Patriots get so good all of a sudden? Why did a team called the "Patriots" suddenly become the best team -- by a long shot -- right when everyone in the country was supposed to start being really patriotic? It seemed like too much of a coincidence, but I had to sit and wait until something happened again before I could point any fingers.

Then, a year and a half ago, Hurricane Katrina devastated New Orleans. Despite all the pain, death, and damage, what was the main focus by the people charged with rebuilding the city? The Superdome. They'd been planning to demolish the Superdome anyway, since it's so old and crappy. The Saints wanted to build a new stadium, and since they might not have gotten one in New Orleans, they were considering leaving for a city with a better fanbase. It didn't matter where. New Orleans fans had always been bad to their team.


Why did everyone care so much about rebuilding the Superdome and keeping the Saints in New Orleans? Surely the money could have been better spent elsewhere in the city ... unless the Saints had a good season for the first time in their history and actually got fans into the stadium, made some money, and united the population of New Orleans.

Last season, the Superdome wasn't ready. The Saints didn't play any home games all season. They were miserable, going 3-13. This team had no future, no quarterback, no coach, no talent. Then they drafted Reggie Bush -- despite all the hype, there was no way he could be ready for the NFL already. And they picked up Drew Brees from the San Diego Chargers. It was the first time in NFL history that a team acquired a quarterback who had a passer rating of 90 or better for the previous two seasons. I was surprised by this until I realized that if you have a quarterback doing that well, you're not going to give him up. Well, the Chargers did (and it wasn't a bad move by any means, thanks to Phil Rivers), and the Saints really lucked out.

This year they made the playoffs, got a first round bye, and even won a game, sending them to the NFC Championship game against the Chicago Bears. It was the second playoff game the Saints had ever won. It will be their first trip to the NFC Championship. And it is the most remarkable one-season-to-the-next turnaround in NFL history. No other team had a worse record in the year preceding a trip to the Championship game.

We'll see how the Saints do in the rest of the playoffs. Will they manage to defeat the Chicago Bears, at Soldier Field? It's possible; the Bears haven't looked good in the second half of the season, despite their early dominance. And depending on the outcome of tonight's game between the Patriots and the Chargers, as well as next week's AFC matchup between the winner of that game and the Colts, it's just possible that the Saints will be matched up in the Super Bowl against -- get this -- the New England Patriots. The two teams who actually benefited from tragedy will be facing each other. Will the torch be passed from New England to New Orleans? From the Patriots to the Saints? From Belicheck to Payton? Only time will tell.

Another possibility is that the Chargers will beat the Patriots, and then the Colts (which is likely, considering LT's awesomeness and Indy's lack of a defense), and go on to face the Saints in the Superbowl. And we'll get to see if San Diego made a mistake by getting rid of Brees, or if they made the right move in going with Rivers. (By the way, in case anyone was paying attention, Drew Brees is another Big Ten quarterback.)

Frankly, I'm rooting for the Chargers over the Patriots. No surprise, I despise the Patriots. But that's a passing thing. Five years from now, my hatred will have subsided. But for the sake of the sport, I hope that on Superbowl Sunday we don't see a scoreboard with the Saints and Patriots both on it. That would just be too much. For all us football fans out there, who have spent so many years of our lives following our teams and our favorite players ... is it really so meaningless week in and week out that the only thing that you need to do to have a Superbowl caliber team is to suffer some horrible tragedy?

Saturday, January 13, 2007

TVMini HD

A while back I bought the Miglia TVMini HD, which allows you to view HDTV streams on your computer. It's essentially an HDTV tuner. There are many other such products, many of which have more impressive features than the TVMini; but this one gets to brag about its size (for what that's worth).

I have a cheap 37" HDTV (doesn't have an ATSC tuner, supports 1080i/720p only), but I don't have cable TV. I use the television as a computer monitor for my G5 tower. It works pretty well in that function -- all I use it for is watching movies and television shows that I have saved to the computer. But now it's time for playoff football, so I need to be able to watch television. So I had to get the TVMini working again.

My G5 doesn't have wireless (I bought an AirPort card, but there must be something wrong with either the card or the computer, as it won't work ... I bought them both refurbished, so it doesn't bother me much), so I hadn't had it connected to the internet. But apparently the EyeTV software that comes with the TVMini requires an internet connection. I bought a 25' ethernet cable and ran it from my Mac Mini to the G5 and turned on internet connection sharing. Instantly, the G5 was online, and the EyeTV software came alive.

It scanned the airwaves for what channels were available, then downloaded the program information and displayed it. The interface is pretty, but not quite *that* intuitive. You have to right click the channel name on the left of the screen to get the options you want, and there are 2 options that always stand out in my mind. "Go To Now" and "Tune To" ... it turns out that "Go To Now" does not mean "go to this channel now," but rather "change the program display such that what's currently on television is displayed." I don't know what would be a better name, but I found that confusing. "Tune To" did what I wanted: go to the channel and view it. It seems to me that if you double click the channel name, it should tune to it.

I must say, ATSC over-the-air broadcasts look really, really good. Of course, not all stations are broadcasting in HD, so I'm getting some SD content too (broadcast over HD frequencies), but those programs that actually are HD are stunning. I'm watching the Eagles-Saints game right now, and the picture quality is fantastic.

But, there's a problem with the move to digital television, and that seems to be the very nature of "digital" itself. Unlike your father's TV sets, if the signal isn't quite good enough, you never get static and the picture quality is never compromised. It just stops and waits for the signal strength to get back up to a sufficient level again.

According to a cursory study of the signal strength graph, the TVMini cuts out if the signal strength drops below 50%. Unfortunately, the antenna they give you really bites, and I have yet to see a signal higher than 66%. Worse, every 5-10 seconds it drops down to 30-40% for a few seconds, meaning that the television viewing experience is pretty jarring.

The EyeTV software includes some really cool features, like scheduling/recording shows, pause/resume live television, encode for iPod, etc. (I tried encoding down to H.264 several months ago, and it's _slooow_ ... much slower than the x264 codec used by Handbrake.) But I can't use any of these features because the feed I'm getting through this antenna is too miserable.

I don't want to sign up for cable (because I hate Comcast), so I may have to buy a higher quality ATSC antenna. And I'll have to get a good one that does both VHF and UHF, because I'm in Chicago and CBS, for some reason, is the only UHF station and is also broadcasting at extremely low power. There are technical reasons for this, but I don't understand the political reasons for them being put into place.

It's too bad, too. The TVMini HD is a pretty cool little product, hampered by its generic remote control which relies on the functionality of mostly unlabelled buttons and a bargain basement antenna that destroys the quality of your signal. I can't recommend this product by itself unless you have cable (but you can't use it with a cable box, you need to plug it directly into the cable and hope you're getting an unencrypted digital Clear QAM signal) or are planning to buy a high quality ATSC antenna along with it.

But I did get to watch football on my HDTV today, even if the CBS nonsense prevented me from watching the early game (it was AFC so it was on CBS) and the bad antenna made the late game (NFC, so it's on Fox) nearly unwatchable. It's still football, and it's still the playoffs. And it was a really good game, to top it all off!

Until next time, take it easy.

Tuesday, June 06, 2006

Installing TurboGears on Ubuntu

I recently came across a new web framework called TurboGears that I think seems pretty interesting.

The basic concept is to integrate several different elements of a framework into one simple, easy install. It uses Python's SQLObject to interact with the database (SQLite, MySQL, PostgreSQL, and Firebird are supported), Kid for templating, the MochiKit Javascript library, and CherryPy for the actual server functionality. They attempt to blend front-end and back-end development in a way that seems like it would allow a developer to be much more productive. Anyhow, it looked good to me and I decided to install it.

The installation is supposed to be easy, and for the most part it is. However, at least if you're using Ubuntu Linux (I'm running the newly released Dapper Drake), there are a few things you need to make sure you have installed.

First, you need python2.4, and python2.4-dev, and libc6-dev. These can all be gotten from the apt repositories.

sudo apt-get install python2.4-dev libc6-dev

should do it for you.

Then you simply follow the instructions here, which I will summarize:

1. Download the ez_setup.py script.
2. Run sudo python ez_setup.py -f http://www.turbogears.org/download/index.html --script-dir /usr/local/bin TurboGears


After that, it should just blow through the installation and you'll be ready to rock. Now I'm off to see what I can do with it!

Friday, May 19, 2006

My Own JSON/PHP Web Services: SSWebService

Web Services. It's a new buzzword. Everyone needs them, because they'll make everything better, right?

Well, nuts to that.

What web services really amount to is nothing more than remote procedure calls that you can make from a web browser. That's cool enough. You make a request, and get a response. Instead of sending HTML that you render, the web service just returns the data. Most web services today use XML to package that data, though a few places -- like Yahoo -- are starting to use JSON instead.

JSON has a few major advantages over XML. First, it is smaller: less bandwidth is wasted by 1.0 crapola. Second, it is very easy to parse it in Javascript. In fact, JSON stands for "Javascript Object Notation," and is native to Javascript. Parsing a JSON-encoded object takes very little time. I've written Javascript applications that need to parse an XML file, and let me tell you, parsing XML in Javascript is not trivial and is a major performance bottleneck.

For an upcoming project, I wanted to develop a web service. There will be PHP interacting with the database, and I want to make simple calls from the browser. The frontend will be a Javascript application, and it is not page-based at all. So I needed a way to pass data back and forth between the browser and the server simply and quickly.

I investigated using SOAP, but was underwhelmed. I decided to design my own web service in PHP, which would use JSON for all its data passing.

The first thing I needed was to be able to register functions with the service, such that only functions that are actively made public are available. I quickly put together a PHP class with a "methods" instance variable and a "register" instance method.

Each function will take a single parameter, but this parameter is expected to be an arbitrary JSON object, which can hold any amount of data. So rather than calling a function like sum(1,2), you would call the function sum($par), where $par = {one:1, two:2}. Then you parse that parameter object in the sum() function and handle it appropriately. It's an extra step and a bit more to remember, but I feel that it adds plenty of flexibility. For example, I wrote a sum function using this brand of parameter passing, and it was utterly trivial to make it work for an arbitrary number of values.

function sum($par) {
    $sum = 0;
    foreach ($par as $key=>$val) {
        $sum += $val;
    }
    return array("sum"=>$sum);
}


Oh yes. I forgot to mention how the return values work. Rather than simply returning a single value, I will always be returning an associative array/object (the PHP associative array type is most closely related to the Javascript object type). This way I know what the return value is (it's called the "sum"), and for more complicated functions I can return as much data as I want.

In order to serve a request, which should be a POST with two parameters ("method" and "param"), I need to decode the param parameter from JSON into a PHP-native object, check that the method is registered, and then call the method with the parameter. I then take the function's return value, JSON-encode it, and return it to the browser.

Here is the code for the web service (sswebservice.php):
<?php

require_once("JSON.php");

class SSWebService {
    var $methods;
    var $json;
   
    function initialize() {
        $this->json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
    }
   
    /*
    add a function to the server, so it can be accessed
    */
    function register($name) {
        $this->methods[$name] = true;
    }
   
    /*
    set a registered function to be inaccessible
    */
    function deregister($name) {
        $this->methods[$name] = false;
    }
   
    /*
    execute the given method, passing its single parameter
    JSON-encodes the return value, which should be an object or associative array
    */
    function call($name, $param) {
        if ($this->methods[$name] == true) {
            $evalstring = $name."(\$param);";
            eval("\$rval=".$evalstring.";");
            return $this->json->encode($rval);
        }
    }
   
    /*
    decode the JSON param into a native object, and call the given method
    return the JSON-encoded object to the browser via echo
    */
    function serve($method, $param) {
        $obj = $this->json->decode(stripslashes($param));
       
        if ($this->methods[$method] == true) {
            $res = $this->call($method, $obj);
        } else {
            $res = $this->json->encode("Not a registered function.");
        }
       
        echo $res;
    }
}

?>


And here is a demonstration web service that uses it (jsontest.php):
<?php

require_once('sswebservice.php');

$server = new SSWebService;

$server->initialize();

function helloWorld($par) {
    return array("string"=>"Hello, world!");
}

function hello($par) {
    return array("string"=>"Hello, ".$par["name"]."!");
}

function sum($par) {
    $sum = 0;
    foreach($par as $key=>$val) {
        $sum += $val;
    }
    return array("sum"=>$sum);
}

$server->register("sum");
$server->register("helloWorld");
$server->register("hello");

$method = $_POST["method"];
$param = $_POST["param"];

$server->serve($method, $param);

?>


As you can see, this web service has three available functions: sum, hello, and helloWorld. Now I just need a way to call them from the browser.

I tend to use the Prototype/Scriptaculous libraries for my web development, so I first whipped something up using Prototype's Ajax.Request object, but that turns out to be quite a bit of code every time I want to make a call to my web service. So I created a very simple class with nothing in it but a class method (ssclient.js):

function SSClient() {

}

SSClient.call = function(url, method, obj, callback) {
    var param = "method=" + method + "&param=" + obj.toJSONString();
    new Ajax.Request(url, {
        parameters: param,
        onSuccess: function(req) {
            var rval = req.responseText.parseJSON();
            callback(rval);
        },
        onFailure: function(req) {
            alert("Call failed.");
        }
    });
}


So when I want to make a call to my web service, I simply need to supply the URL, the method I want to call, the Javascript object I want to send, and a callback function to execute when it returns. The callback function should expect to receive a JS-native object, since I parse the JSON-encoded object before calling the callback function.

Here is an example of the code to call the web service:

function button1() {
    SSClient.call("jsontest.php", "sum", {
        one: 1,
        two: 6,
        three: 9
    }, sum_callback);
}

function sum_callback(r) {
    alert(r.sum);
}


As you can see, the SSClient.call() function is very easy to use, and I can create an anonymous object to pass along. In this case, the callback function simply pops up the return value. Note that it is accessed by r.sum, which is because of how I set up my return values in jsontest.php. Neat.

This requires Prototype, json.js from http://www.json.org/json.js, and JSON.php from http://mike.teczno.com/JSON/JSON.phps.

And now I'm off to build an application with my new web service!

Tuesday, May 02, 2006

Intel's Cheap Laptop Proposition

By now we've all heard quite a bit about MIT's One Laptop Per Child initiative, and its sub-$100 laptop. In order to reach such a low cost, the machine uses a slow and inexpensive AMD Geode processor, and runs Linux. Naturally, this has led Microsoft and Intel executives to call it "a gadget" and to insist that it is inadequate for children in developing nations.

Now Intel has backed up their statements with a plan to produce their own version of a cheap laptop computer for students in developing nations, called Edu-Wise. They claim that it will cost $400 or less, and will run some version of Microsoft Windows on an Intel processor faster than the AMD in MIT's inexpensive offering.

Another key differentiator between the two machines is that the MIT laptop uses 802.11 b/g wireless mesh networking to provide connectivity between machines, whereas the Intel laptop will include a WiMAX chip, allowing it to connect from much farther away from any access points and removing the requirement that it be used in a classroom setting.

While I understand Intel's claim that "that Wi-Max deployments will leapfrog stages of development in the nonindustrialized world," I find it somewhat dubious that the nonindustrialized world will gain access to WiMAX deployments any time soon. After all, there have only been minimal deployments of the technology even in industrialized areas, and widespread adoption does not appear to be imminent. The inclusion of WiMAX in an ultra-cheap device before it is even an option on high end equipment is an indication that this is little more than a stunt to keep developing nations from signing on with MIT's proposal, which happens to actually exist.

Another question is the actual cost. MIT promised a sub-$100 notebook, and have reported that it currently costs them $135 to build one. They haven't made their goal yet, but they're pretty close. On the other hand, Intel is starting from the $400 price point (which, by the way, is already what cheap laptops cost on the US market today), and their recent record with hitting price targets is not good. For example, the recent UMPC was projected to cost around $500, but is actually available for sale in the $1100 range. Engadget expects that Intel's new machines will cost close to $750, rather than $400. So the questions Intel has to answer are:
  1. How is this machine an improvement over those that already exist at the same price point?
  2. Is the announced price point remotely possible?
  3. Is $400 affordable for students in developing nations?
  4. Do students in developing nations really need more processing power than the AMD Geode can offer?
  5. Do students in developing nations really need the expensive Microsoft Windows installed on their computers, or would they be better served by a Linux-based solution which would drive costs down?
At this time, none of these questions have been answered. The closest Microsoft or Intel will come to addressing these issues is to publish statements such as
"We don't think you cross the digital divide with old technology," he said. "It doesn't need exotic technology and it runs real applications."
made by Paul Otellini, which implies that they want to somehow use new (expensive) technology to address the demands of this new (poor) market.

This venture is doomed to fail. It is nothing but another scare tactic from Intel, designed to cripple its competitors without having to produce a competing product. They did the same thing with the Itanium, and it worked. Now they are doing it with Edu-Wise. A real product may or may come of this. If it does, it probably won't meet the announced price point. And even if it somehow does, it will still be too costly for the market they are trying to address. The real test of whether this is a successful move by Intel will be whether or not developing nations delay their purchases of the OLPC in favor of waiting for Intel's notebook. If that happens, Intel and Microsoft have already won (and they know this better than anyone).

Monday, May 01, 2006

Democracy - Television for the Internet Age

Last week I came across a rather new video player with an interesting twist: it is meant to be a platform for distributing internet-based television. Democracy's goal is to be a democratization of the media, allowing anyone with a video camera and an internet connection to put together their own channel, producing art, entertainment, or news.

Rather than simply playing videos downloaded elsewhere (this is, in fact, not possible in the current player, though I have been told that it is planned for the next release in mid-May), in Democracy you subscribe to channels and videos are downloaded automatically as they are made available. It is the work of a moment to begin watching in a window or in full screen mode. And as an added bonus, all downloaded videos play one after the other so your television experience is not interrupted by having to start the next video.

In an effort to curb hard drive use, Democracy has implemented an expiration system based on Tivo's, in that downloaded videos expire in 6 days (by default, though that number can be changed), unless they are explicitly saved for longer. And the website reminds you that you can always download expired videos again if you want to see them.

I have only used the program to a somewhat limited extent thus far, and have not fully explored the channel options. However, the content I have found is mostly good, and in one case is better than the options on television (Channel Frederator). I am certainly looking forward to the creation of new and interesting video content, and the distribution opportunities being made available by standards such as RSS and innovative new players such as Democracy.

While I don't think it has the potential to replace the networks, the ability for anyone to produce their own news should force the news networks to remain diligent and the ability for anyone to produce and publish their own shows should force the studios to remain creative. This democratization of the media, by putting the tools into the hands of the individual, can only be a good thing.

Democracy is open source, released under the GPL, and is available for Windows, Mac OS X, and Linux.

Google Complains About IE7's Default Settings

Just saw this article about Google officially complaining that Microsoft will set IE7 to use MSN search by default. The claim is that it is unfair to limit choice and drive users to MSN rather than Google.

This is a specious argument coming from Google, considering the fact that Google search is the default in Firefox, Opera, and Safari. The only difference would be that Microsoft owns both the browser and the search engine ... but if MS owns both then they should be allowed to link them as they see fit, yes? It certainly wouldn't make any sense to require Google search to be the default on IE7, when MSN search is the only option Microsoft has if they want to default to a non-competitor.
"The market favors open choice for search, and companies should compete for users based on the quality of their search services," Marissa Mayer, the vice president for search products at Google, told the Times. "We don't think it's right for Microsoft to just set the default to MSN. We believe users should choose."
Yes, users should be able to choose. But you still need a default, and for once Google isn't going to be that default. Perhaps that's what's gotten under their skin.

For the record, Microsoft did what they could not to come off well either:
Microsoft told the Times that giving users of the new version of IE an open-ended choice could add complexity and confusion to the browser set-up process, while offering a few options would be arbitrarily limiting.
Aside from once again demonstrating their lack of respect for their own users, how arbitrarily limiting can offering a few choices possibly be? The options would probably be:
  1. MSN Search
  2. Google Search
  3. Yahoo Search
  4. Add another search engine...
Perhaps all Google was trying to do was to raise awareness of the issue, and to force Microsoft to offer options. However, they should avoid whining like this, lest they lose their darling status. Google should get back to their roots: winning by being better, rather than by having better lawyers and journalist shills.

Friday, February 17, 2006

Netflix Online Video Distribution

Netflix has a problem, in that it's getting harder and harder for them
to make a profit. They break even on a renter if he/she gets 5 DVDs
per month. So, they need to find some way to augment their service
somehow.

One possible way they could do this is to start getting into the
online distribution game. They have all these DVDs, and they're a
known commodity for the studios. They would need to license the movies
for online distribution, but the fact that they also distribute DVDs
should help in those negotiations. Then, once they can offer the
movies online, they have a few options as to how to get them to their
customers.

One possibility is to have each movie streamable from the Netflix
website as long as the customer has the DVD checked out. So when they
ship you a movie, they also make available a stream so you can watch
it online. The problem with this is that they then incur the cost of
shipping and of online distribution, making it somewhat non-viable.

A second possibility is to offer an added level of service that
includes streaming movies, allowing people to watch a movie instantly,
without having to wait for the disc to come in the mail. This would
free Netflix from having to ship the movie, saving them some money.

A third possibility is to offer the movies for download, for a fixed
cost per movie. This way, Netflix would be able to recoup the cost of
the transfer in the purchase fee. However, they would have to
implement some kind of DRM scheme.

They would want to build the DRM system so that it's as fair as
Apple's FairPlay. Since the best codec for distributing video online
at the moment is H.264, and they would want their files playable on
the iPod anyway, they should try to make a deal with Apple. Apple lets
the iPod play Netflix's DRM'd video files and possibly shares
bandwidth, licensing and advertising costs, while Netflix only
supplies video in this format, helping to ensure iPod dominance. It
would be a win for both companies, while allowing them both to do what
fits within their business model.

For the client side, Netflix would need an application to play the
streamed/downloaded video. There are a few possibilities here.
1) They could roll their own client which plays H.264 files and
decodes the Netflix DRM. They would probably need to make it talk to
the iPod somehow, but this would presumably be part of the deal with
Apple. Making it cross platform is important.
2) They could do some kind of bundling deal with Apple for Quicktime.
This would give them the benefit of getting advertisement through
Quicktime even for non-subscribers, but would be difficult to do and
would get into the thorny full screen issue (do you get Quicktime Pro
when you subscribe to Netflix?).
3) They could update an open source client, such as VLC. VLC already
has support for H.264, and for streaming video over the network, as
well as being very cross platform. There are two issues here, which
are related. The client needs to be able to decode the DRM, and VLC is
an open source program. The way I see it, DRM doesn't really work when
the code is open. Even if the technical aspect were completely figured
out and the DRM was uncrackable (dubious, considering that all DRM has
been cracked), the studios would never agree to it. Say what you will
about open source (I know I like it), it doesn't instill confidence in
the major content owners.

A solution could be developing a program that opens the
downloaded/streamed file, decodes the DRM, and passes the video along
to VLC, or any other video player. This greatly simplifies the
software from Netflix's perspective and gets them away from having to
open source the decoder. However, there could be a problem with the
player receiving the unencrypted file, with no way to prevent the user
from saving the stream to the hard drive. (Of course there will be
people who figure out how to do it, but the point of DRM is to make it
at least somewhat difficult, so the process doesn't enter the
mainstream.) Because of this issue, developing their own player seems
to be the best option.

Netflix needs to do something to help the bottom line, other than
attempting to screw their customers. Withholding discs from their
happiest customers is not a good way to keep those customers happy.
This would be a good way to make more money by offering more services,
rather than fewer. And partnering with Apple would been a boon for
both companies; in fact, it's difficult to tell who would benefit
more.

Obviously, I have no inside information about this. I say it because
it's what I would do if I were in a position of authority at either
Netflix or Apple. And as a user of both, I'd certainly like to see it
happen.

Friday, February 10, 2006

Apple Making Intel Uncomfortable?

Just saw a story over on Ars about Apple's new ads making Intel uncomfortable. Basically, the premise is that some analysts are worried that Apple's ad (which insults Intel's other partners like Dell & HP by calling them "dull little boxes") will alienate Intel from their other, larger customers.

They cite Intel's "public love-fest" with its newest customer, the 1000 employees dedicated to The Switch, and the fact that Apple got the first Core Duo chips as other reasons Intel may be in trouble with its other customers.

But I'd like to point out another problem with their claim. Intel's in the driver's seat in these relationships. Dell only uses Intel chips. And they can't even threaten to go to AMD, because Intel can pull their sweet prices out from under them, or even stop selling them chips entirely, leaving Dell to find some way to get 10 million processors per quarter from AMD. I'd be willing to venture that AMD isn't capable of supplying that many processors. And the same goes for HP, Lenovo, and everyone else. If you want to offer AMD chips, then you can, but you have to stick with Intel for the same reason Apple chose Intel: manufacturing capability. Intel is the only place to go if you want a guaranteed supply.

So I'd say that Intel has nothing to worry about. In fact, they're probably excited that Apple is lighting a fire under the other computer makers. The CPU-comparison is now gone, so the difference maker is not processing power any more. That puts an onus on the designers of the whole system to put together a better offering ... and whether it's Apple's Front Row or Dell/HP/etc VIIV, Intel stands to benefit. A lot.

And I think everybody knows it. That's why none of the computer makers are saying they're insulted. Dell's spokesperson had this to say:

"As far as their marketing goes, that's marketing," said Dell spokesman Jess Blackburn. "We continue to have a very solid relationship with Intel and nothing has changed in that respect. We probably are their largest customer; we shipped 10 million systems in the fourth quarter. I don't think any supplier is going to ignore a customer that is building that many systems and using that many of their parts in them."

My guess is that Intel is quietly encouraging Apple to be as insulting as they want. If Dell and HP lose customers to Apple, it's probably better for Intel. They'd prefer their chips to be part of the high end, high margin space that Apple aims for, because it means more money for them. But this entire issue is just meaningless controversy invented by analysts. I guess they have to justify their paychecks somehow.

Wednesday, December 14, 2005

HandBrake Wrapper Script

I've been encoding my DVD's lately using HandBrake for Linux. As far as I can tell, there isn't a GUI for the Linux version, though there is a very nice one for OS X. However, you don't need the GUI at all.

Once you have compiled HandBrake from source, you have everything you need. Except that the default options in the CLI program (HBTest) aren't exactly the greatest in the world. So every time you want to encode a movie, you have to type a long string of command line options which aren't strictly necessary, since they're the same every time. (I'm assuming you encode all your movies the same way, because that's what I do ... and who wants to worry about encoding each movie differently?)

I encode the video using the x264 codec at 700 kbps, and the audio using the faac codec at 96 kbps. I find that this gives a high enough quality rip that the artifacts aren't typically very apparent. In most cases, my encoded version is indistinguishable from the MPEG-2 version on the DVD, except for the small size.

Normally, I would have to type:
/home/sean/Desktop/HandBrake-0.7.0/HBTest -e x264 -E faac -2 -b 700 -B 96 -w 512 -i /dev/dvd -o This\ is\ the\ movie\ title.mp4

That's a lot of typing, especially considering the fact that all of it is the same every time except for the -o argument.

To save myself some time (it's a valuable couple of seconds!), I wrote a wrapper script in Python to use my defaults instead of HandBrake's.

Here it is.

Now all I have to type is:
./hbencode.py 'This is the movie title.mp4'

Which of course is a lot faster.

I also decided that I might at some point forget to type a title for the movie, but I'd still want the movie to be ripped and encoded, and I could name it later. So my solution was that if nothing is passed in at the command line, it would get the current timestamp and use that as the filename. That should be unique enough that I'd be able to repeatedly encode things without setting a title and be able to go back and set their names later. It has the added bonus of keeping the files in chronological order, according to when they're ripped.

The next step is to take more command line options than just the movie title, so that the defaults can be changed if necessary. The first addition would be the ability to set the title to rip, in case you're ripping a TV show, or a movie where the main feature is (for whatever dastardly reason) not the first title.

This is a very simple script, but it makes my video encoding life a little simpler, and a little more pleasant. Hopefully it does the same for you.

Tuesday, December 06, 2005

Web Based Remote Control

I spend a lot of time at my computer, but I spend even more time near my computer but not quite at the keyboard. It's a Mac Mini, and most of the time it's playing music in iTunes or a movie in VLC. I wanted a way to control those applications remotely, so I could pause without going all the way over to the computer. Since I have a Nokia 770, I thought the easiest way to do this would be to write a web page that can control these applications, and connect to it from the 770.

The first thing I needed was a way to control the applications. This was quite simple, of course, using Applescript. I made a small script for each action I wanted to perform. For example:

tell application "iTunes"
   playpause
end tell

All the scripts I wrote were similar in complexity, but more complicated scripts can of course be written.

The next step was to run these scripts from a web page. PHP handles this quite nicely, using the system() command. However, it won't work right out of the box, because OS X runs the web browser as a different user than the person running iTunes (for obvious security reasons). So I had to add a line to the /etc/sudoers file:

www ALL = NOPASSWD; /usr/bin/osascript

This gives the user running Apache the right to run osascript (which executes Applescript files) without typing in a password. This is probably not the best thing to do, security-wise, so it's pretty important to make sure that your machine is only accessible to computers on your local network.

Next, the PHP. It's quite simple. I only need one page, which takes a script and executes it as if it were on the command line. Here it is (execute.php):

<?php

$script = $_REQUEST['script'];

system($script);

?>

I'm planning on sending requests to this PHP file via XMLHttpRequest, of course. I'm using my standard xmlhttp() function which you can get from a previous blog. The only other Javascript function I actually need is the execute() function, which sends a request to execute.php. Here it is:

function execute(script) {
   var req = xmlhttp();
   var param = 'script='+script;
 
   //this should be made async
   req.open('POST', 'execute.php', true);
   req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   req.send(param);
}


This is a pretty simple function, sending a single parameter asyncronously. Since it's only sending the request, and doesn't really need to return anything, I don't even bother checking the return. We just shoot off the request and wait for more input. You'll know if it worked it the music starts playing.

It was important to me that I didn't limit this program to any set of functionality that would be difficult to augment later. So I created an XML file that holds records for each program that can be controlled and the scripts to run in order to control it. Originally, I wanted the interface to be built dynamically via Javascript, so I crafted the XML file such that it had no attributes, only elements, because my JS XML parser doesn't read attributes (I should work on that). Unfortunately, it seems that the browser on the 770 doesn't support dynamically created DOM elements, so this approach didn't work. Plenty of wasted work there (and a lot more Javascript than I've included here).

This was when it dawned on me that I don't actually need to build the interface every time the page loads. It only needs to be done when the XML file is changed. So I wrote a Python program to take the XML file, parse it, and output the same HTML as would have been produced by the Javascript. I recreated the XML file to use attributes instead of just elements, because I find that to be simpler to read, and it's much easier to handle that in Python's xml.sax library. Here's the Python (buildinterface.py):

import os, sys
from xml.sax import saxutils, handler, make_parser

#set up the environment variables
config_file = "server2.xml"
html_file = "index.html"
output_file = file(html_file, 'w')

#globals programs dictionary
programs = []

class Program:
   def __init__(self, name):
       self.name = name
       self.commands = []
     
       programs.append(self)
     
   def addCommand(self, cmd):
       self.commands.append(cmd)
     
class Command:
   def __init__(self, name, script):
       self.name = name
       self.script = script
     
class ConfParser(handler.ContentHandler):
   def __init__(self):
       handler.ContentHandler.__init__(self)
     
   def startElement(self, name, attrs):
       global temp_prog
       if name == "program":
           temp_prog = Program(attrs['name'])
       elif name == "command":
           temp_prog.addCommand(Command(attrs['name'], attrs['script']))
         
def write_html(out = sys.stdout):
   out.write("<html><head><title>Remote Control</title>")
   out.write("<link rel='stylesheet' type='text/css' href='remote.css' />")
   out.write("<script type='text/javascript' src='remote.js'></script>")
   out.write("</head><body>")
   for prog in programs:
       out.write("<fieldset><legend>" + prog.name + "</legend>")
       out.write("<div id='" + prog.name + "_div'>")
     
       for cmd in prog.commands:
           out.write("<span class='link' onclick='execute(\"" + cmd.script + "\");'>" + cmd.name + "</span>")
           out.write("<br />")
         
       out.write("</div></fieldset>")
   out.write("</body></html>")

parser = make_parser()
parser.setContentHandler(ConfParser())
parser.parse(config_file)

write_html(output_file)

output_file.close()


As you can see, it outputs directly to index.html, which is convenient. Every time you run buildinterface.py, you have a fully updated interface waiting for you to load up in your browser. And in case you were wondering what those span tags are all about, they are to mimic links without the bother of actually putting a link on there. Here's the CSS for that:


.link {
   text-decoration: underline;
   font-size: 10pt;
   color: black;
   cursor: pointer;
}


Each link has its onclick event set to call execute() with the script to run. It's a fairly simple scheme, and when I loaded it in my browser to test it out, it worked swimmingly. I could control iTunes, VLC, Quicktime, and the system volume. I pulled out my laptop and connected, and found that it worked from remote systems. Now it was time to try it out on the 770. I fired up the browser and opened my page. This time the interface loaded, which was of course promising. However, none of the links worked. So the remote control program works, and is extensible, but I haven't been able to get it working on my Nokia. It seems that the browser doesn't want to send the XMLHttpRequests, which is weird, because it's Opera, and I tested this in Opera on both OS X and Linux, and it works there. I'll be trying to get it to work on the 770, but until then, here's the working code.

Things that could be added:
1. Get it to work on the Nokia 770.
2. Write plugins for other programs, to build out the capabilities of the remote.
3. Have the PHP return something, so it's possible to tell if the command has been executed or not. This will allow for more interesting possibilities on the front end.
4. Anything else ... ?

You can download the code here. Let me know how it goes, or if there are any problems you find with it. And let's here about those plugins!

Monday, August 22, 2005

Associative Array Doubly Linked List

This isn't going to be a demonstration of an application of any kind, but rather I'm going to show a data structure I developed the other day to help out with my web applications. I implemented it in Javascript, but it should be trivial to port it to other languages. (If the language doesn't support associative arrays on its own, then you'll have to implement that first.)

The idea behind an Associative Array Doubly Linked List (AADLList) starts with an associative array and adds a doubly linked list to it. In an associative array, you have a bunch of key/value pairs, where the value is accessed by its key (normal arrays can be viewed as an associative array where the keys are integers starting with 0). In a linked list, you have to define an object that has not only its data, but also a pointer to the next object in the list. A linked list will also have a pointer to the front of the list. A doubly linked list takes this a step further, by giving each object a pointer to the object before it AND after it, and the list must have pointers to the first and last items in the list.

I wanted to make this data structure independent of the application you're going to use it in, so instead of defining information fields in the objects as well as the pointers, the nodes in this list will have another variable inside that you can fill with whatever object you want.

First, we have to define the list objects, AADLListNode and AADLList:

function AADLListNode() {
    this.node = null;
    this.next = null;
    this.prev = null;
}

function AADLList() {
    this.list = new Array();
    this.first = null;
    this.last = null;


Note that I omitted a trailing bracket at the end of the AADLList definition. That is because the rest of the code goes inside the AADLList class definition.

As you can see, the ListNode class has a node object and its two pointers. The List object has a list (which is an array) and its two pointers. At first, the first and last pointers are null, which means the array is empty.

The first thing we need to do is add nodes to the list. When we're adding the first item in the list, we have to take more things into consideration. When the first node is inserted, the list's first and last pointers have to change from null to the new first node. So we write our first function:

/*
    add a node that is the first and therefore only node in the list
    */
    this.addFirst = function(key, val) {
        var node = new AADLListNode();
        node.node = val;
        node.next = null;
        node.prev = null;
        
        this.list[key] = node;
        
        this.last = node;
        this.first = node;
    }


After our first node has been added, we can start adding more nodes. Since it's a doubly linked list, we have the desirable ability to add nodes to either the front or the back of the list. (Actually, we will be able to insert a node anywhere in the list.) So we write two functions, to add a node to the front or back of the list.

/*
    add the given key/val pair as the first element in the list
    */
    this.addToFront = function(key, val) {
        var temp = this.first;
        
        var node = new AADLListNode();
        node.node = val;
        node.next = this.first;
        node.prev = null;
        
        if (this.isEmpty()) {
            this.addFirst(key, val);
        }
        
        this.list[key] = node;
        
        if (this.first) {
            this.first.prev = node;
        }
        this.first = node;
    }
    
    /*
    add the given key/val pair as the last element in the list
    */
    this.addToBack = function(key, val) {
        var node = new AADLListNode();
        node.node = val;
        node.next = null;
        node.prev = this.last;
        
        if (this.isEmpty()) {
            this.addFirst(key, val);
        }
        
        this.list[key] = node;
        
        if (this.last) {
            this.last.next = node;
        }
        this.last = node;
    }


The code in these functions is pretty simple. We just need to set the prev or next pointers of the newly created node, and update the first or last pointers of the list. As you can see, these functions use the isEmpty() function to determine whether they should call addFirst() or not. We have to create isEmpty() for ourselves, like so:

/*
    returns true if the list is empty
    */
    this.isEmpty = function() {
        if (!this.first && !this.last) {
            return true;
        } else {
            return false;
        }
    }


Simple enough. If the first and last pointers are both null, then the list is empty. It should, in theory, be possible to also just access the this.list.length value and check that it is zero, but unfortunately, when you remove an entry in a Javascript array, it does not disappear. The key continues to exist, but points to null. So the this.list.length field will be incorrect if a node is ever removed from the list.

I often don't care whether my nodes are inserted at the front or the back, so I threw a convenience function in:

/*
    simple convenience function
    just calls addToBack
    */
    this.add = function(key, val) {
        this.addToBack(key, val);
    }


Now we can add as many nodes as we want, either at the front or the back of the list. But how do we access the nodes once they're there? One way is to simply go through the object's members and use them, but this is generally not an awesome way to go (if you really wanted to do it, you'd have to do something like this: myList.list[myKey].node.myField ... etc. Clearly not what you want to be doing every time you want to retrieve something from the list). So we can write a function that will retrieve a given node for us based on its key.

/*
    try to get the node for a given key
    return the node if it exists, null if not
    */
    this.getNode = function(key) {
        for (var id in this.list) {
            if (id == key) {
                return this.list[id];
            }
        }
        
        return null;
    }


But that isn't always what we want, because it will return an AADLListNode object, which you probably won't want to use in your application. So we write another, similar function, to just return the object inside the node (without the pointers).

/*
    try to get the node value for a given key
    return the value of the node or null, if there is no node
    */
    this.getNodeValue = function(key) {
        var node = this.getNode(key);
        if (node) {
            return node.node;
        } else {
            return null;
        }
    }


Note that if we were simply doing a linked list (or even a doubly linked list), this operation would have an O(n) efficiency (worst case), because we would have to traverse the list and check each node to see if it was the one we're looking for. But since it's also an associative array, we can access it in O(1) time, greatly speeding up our data access. This is good.

I'm sure you've noticed that what this is missing is a way to remove a node from the list. So we're going to add that function now. We need to make sure we check that the node actually exists, then change the next object's prev pointer to point to the removed object's prev, and vice versa. (Don't know how to explain that very well, except to use the term "switcharoo," which I think should cover it pretty well.)

/*
    remove a node from the list
    return true on success, false on failure (if the given key isn't in the list)
    */
    this.removeNode = function(key) {
        var node = this.getNode(key);
        
        //if the node doesn't exist, you can't remove it
        if (!node) {
            return false;
        }
        
        var tempNext = node.next;
        var tempPrev = node.prev;
        
        //if the node doesn't have next/prev, you can't change them
        if (tempNext)
            tempNext.prev = tempPrev;
        if (tempPrev)
            tempPrev.next = tempNext;
        
        //if it's the first node, set the next node to be the first
        if (key == this.first.node.id) {
            if (tempNext) {
                this.first = tempNext;
            } else if (tempPrev) {
                this.first = tempPrev;
            } else {
                this.first = null;
            }
        }
        
        //if it's the last node, set the prev node to be the last
        if (node == this.last) {
            if (tempPrev) {
                this.last = tempPrev;
            } else if (tempNext) {
                this.last = tempNext;
            } else {
                this.last = null;
            }
        }
        
        //null out the entry in the array
        this.list[key] = null;
        
        return true;
    }


As you can see, this is by far the most complicated function in the class (and it's not even very complicated!).

And don't forget that trailing bracket!

}


Now we have a working AADLList, which gives us all the advantages of a doubly linked list and an associative array in one easy to use package. You have O(1) access to any node in the list, but you can also traverse from the back or the front and add nodes in whatever order you want (although that isn't implemented in this version).

So what would you want to add to the AADLList to make it a little better?
  • How about an insert() function of some kind, so you can decide where in the list you want a node to be added?
  • Build on your insert() function and make the AADLList a sorted list.
  • Give it some queue-like or stack-like functionality, with push() and pop() operations. (Who wouldn't want the ultimate data structure?)

Feel free to use it, add to it, whatever. Let me know if you have any issues with it, or problems using it or implementing new features for it.