416th Wordpress Twitter Plugin

Today my Recently on Twitter wordpress plugin became the 416th plugin to join the wordpress Twitter plugin directory. I’ve been told that the 415th previous attempts didn’t load asynchronously or otherwise caused the page to stall during render. Hopefully, this one does a slightly better job, though I haven’t actually investigated the competition. This plugin took about 30 minutes to develop, mostly because I have created around 10 different iterations of the same concept for previous clients and employers.

Let me know if you find it useful. You can find details on usage and installation here. Some of the features include:

  • Loads Twitter data asynchronously after the DOM ready event
  • Automatically links Urls
  • Automatically links Twitter Usernames
  • Automatically links hash tags
  • Always fresh data, even with WP-cache & Super Cache
  • Works with both Widget enabled and regular wordpress themes

You can see it in action at the bottom of the ride side of this blog. Enjoy!

jQuery Array Chunk plugin

Since I am working almost exclusively in jQuery, I am much more inclined to convert common utilities I have written to jQuery plugins, my latest is the JavaScript array chunk method.

You can see the complete code and a usage example below, or download the plugin via the jQuery plugin library.

Usage is as follows:

 
        (function($) {
 
        	$.chunk = function( array, chunkSize ) {
        	   var base = [], i, size = chunkSize || 5;
        	   for(i=0; i<array.length; i+=chunkSize ) { base.push( array.slice( i, i+chunkSize ) ); }	
        	   return base;
        	}
 
        })(jQuery);
 
        var myArray=["apple", "onion", "orange", "potato", "pear", "grape", "tomato"], myChunkedArray=[];
        myChunkedArray = $.chunk( myArray, 3);
        console.log( myChunkedArray )
 
        /*
            Output:
 
            myChunkedArray = [
                ["apple", "onion", "orange"],
                ["potato", "pear", "grape"],
                ["tomato"]
            ]
        */

jQuery Time Format Plugin

When it comes to real-time, there is nothing that says it like a cool time date display. That’s why I am releasing my jQuery.timeFormat() plugin. It’s extremely simple, it takes a timestamp from the server in seconds and calculates the difference. The return response is of the format:

  • Now
  • 2 mins ago
  • 5 hours ago
  • 1 day ago
  • January 15

This is the same logic I use in my last.fm wordpress plugin. The code is below or available via the jQuery site.

/*
    name : timeFormat
    file : jquery.timeFormat.js
    author : gregory tomlinson
    Dual licensed under the MIT and GPL licenses.
    ///////////////////////////
    ///////////////////////////        
    dependencies : jQuery 1.4.2
    ///////////////////////////
    ///////////////////////////
 
*/
 
(function($) {
 
    /*
        Format the time by:
            1. taking existing timestamp from server
            2. calculate current time
            3. find difference
            4. Display:
                    Now
                    2 mins ago
                    3 hours ago
                    1 day ago
                    January 15
    */
 
    $.timeFormat = function( timestamp ) {
        var time = handleDate( timestamp );
        return time;
    } 
    function handleDate( timestamp ) {
        var n=new Date(), t, ago = " ";
        if( timestamp ) {
          t =   Math.round( (n.getTime()/1000 - timestamp)/60 );
          ago += handleSinceDateEndings( t, timestamp );
        } else {
            ago += "";
        }
        return ago;
    }    
    function handleSinceDateEndings( t, original_timestamp ) {
        var ago = " ", date;
        if( t <= 1 ) {
            ago += "Now";
        } else if( t<60) {
            ago += t + " mins ago";
        } else if( t>= 60 && t<= 120) {
            ago += Math.floor( t / 60 ) + " hour ago"
        } else if( t<1440 ) {
            //console.log(t)
            ago += Math.floor( t / 60 )  + " hours ago";
        } else if( t< 2880) {
            ago +=  "1 day ago";
        } else if( t > 2880  && t < 4320 ) {
            ago +=  "2 days ago";
        } else {
            date = new Date( parseInt( original_timestamp )*1000 ) 
            ago += months[ date.getMonth() ] + " " + date.getDate();
        }
        return ago;
    }
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
})(jQuery);

Tweet your Favorite Tracks, automagically

Earlier this week, I wrote a tiny little app, which tweets my favorite music. You can read more about the concept here. This is a technical post to explain how you can leverage this app for your own enjoyment.

First, you will need to download the code. Then you will need to obtain the following items:

Once you have obtained these items, you will need a computer that is always plugged into the internet or a web server where you can run cron jobs. I am running the script on this server.

Open the track_lover.php file, which you should have gotten from here, and update the following lines, replacing ‘xxx’ with real values:

    // TWITTER
    define("TWITTER_USERNAME", "xxx");
    define("TWITTER_PASSWORD", "xxx");
 
    // last.fm
    define("LASTFM_USER", "xxx");    
    define("LASTFM_API", "xxx");    
 
    // bit.ly via j.mp
    define("BITLY_USER", "xxx");
    define("BITLY_API", "xxx");

Once you save the file, you will be all set to turn on The cron job entry may look as follows

# run every two minutes
*/2 * * * * /usr/local/bin/php /path/to/the/script/trackLover/track_lover.php > /dev/null 2>&1

That’s it, you should be up and running tweeting your favorite tracks. Enjoy!

Intersection of Geek and Music

I absolutely love the intersection of geek and music.

Recently, I wrote a tiny little app that does for me something that is irritating to do manually, sharing my favorite music at this moment. Essentially, it tweets to the world the track I have listened to a track at least 3 times in the last hour.

I am leveraging several APIs to create this app. The always wonderful last.fm API, as well as the bit.ly (awesome) API and the Twitter API. The real trick is taking advantage of the upcoming version 3 API from bit.ly. In the latest bit.ly API, bit.ly returns a boolean whether the recently shortened track is a new ‘hash’ or not. Meaning, if it has not been shortened by me before, it returns true. Instead of needing to attach a database to this app, I am just checking this boolean. Normally, I would consider this abusive, however, with all the preconditions of my script, I rarely even ask bit.ly if this shorten is ‘new’.

If it wasn’t for the descriptive potential of bit.ly, I would need to establish a flat file, or database to handle this logic check. Eventually, if they alter the API, this will become a nessecity, but for the time being I am leveraging this functionality.

Shortly, I will attempt to release a new wordpress plugin or cron that leverages all three APIs, but for the time being the code is a bit messy. If you are interested, please reach out in the comments below with an email address and I am happy to share the code. Otherwise, enjoy my twitter stream and all the music I am addicted too.

All the Cool Kids use bitly.tv

It was a huge week at bit.ly. At the beginning of the week Google and Facebook launched URL shorteners at the same time we were launching bit.ly pro. As if that wasn’t exciting enough, I also launched my first product experience for bit.ly known as bitly.tv.

The response to bitly.tv has been very exciting and positive. It launched as part of labs.bit.ly, where I hope to be involved in many future experiments with bit.ly data. The bitly.tv User Interface is very fun and extremely different from anything I have built in the last few years, I had the opportunity to really flex my AJAX application skills.

The app uses quite a few of my favorite libraries and JavaScript projects, including jQuery, SWF Address, SWF Object and a few plugins I wrote specifically for bitly.tv. I also got my first taste of writing Python for a production level project as well as using the Tornado framework. In addition, I got the opportunity to finally use the new Google Closure Compiler. All in all, I think all of these technologies are excellent and make writing apps fun.

I also learned some extremely valuable lessons about the jQuery animation code and DOM interface. During the prototyping phase of bitly.tv, I noticed that jQuery was consuming a considerable about of memory because my architecture was not caching references to DOM elements. Essentially, I was crawling the DOM looking for the correct rows and columns to transition on every mouse over and mouse out. This was very slow in FireFox, but not very noticeable from a user experience point of view in Chrome and Safari. To help alleviate this issue, I began storing the references to each row and column in an array then did a simple jQuery.inArray(); check to skip the DOM API completely. This reduced the number of internal jQuery calls from around 32,000 to around 4,000.

In addition to the above, I also helped speed up the jQuery animation code by skipping the standard jQuery().animate(); and going directly to jQuery.fx();, which also had a considerable impact on the number of internal calls jQuery needed to make. I don’t recommend doing this, however, as it could cause compatibly issues with future releases of jQuery.

Take a few minutes and check out bitly.tv. We are already planning bitly.tv 2.0, and I would love to include your feedback.

Newish Music, Portugal The Man

My friend Dan has been raving about this band, Portugal, The Man for a while now. He said their latest CD, The Satanic Satanist, could be his album of the year. So, as usual I didnt bother listening to it, because he spends a great deal of time trying to convince me of things. I finally put it on my iPod, and I have to say its very good. I sort of hate it when he is right, but I do love good music.

bit.ly Bookmarklet API Hack

I recently started using bit.ly for storing my bookmarks instead of delicious. While bit.ly isn’t entirely ready to be a bookmarking service for everyone, it does have some cool features, such as a public history, and saves me a hop for sites that I want to bookmark plus need a short URL in order to tweet.

In order to facilitate my new, higher volume, usage of bit.ly, I wrote a little bookmarklet hack that throws the current page into bit.ly and alerts back the shortened URL in case I need it.

I put together this form that will let anyone take advantage of the hack. You’ll just need to input your user name and bit.ly API key. Then you never have to worry about logging in again. Enjoy.

My Next Big Thing

Just a quick note to say I started last week at bit.ly as the Lead Front-end Engineer. It’s my second attempt at a startup and so far it’s amazing. I’m very excited about learning Python and having a chance to own the products I work on. Unfortunately, new jobs usually mean significantly fewer blog updates for the first few months, but I hope to put together more tutorials like my extremely popular ffmpeg install post by the first of the year.

Adding Docs for iPython on Mac OSX Leopard

I have been playing with iPython as part of my exploration into Python. A friend tipped me off that iPython is a little more sophisticated than the standard Python interactive prompt.

One of the features of iPython is an interactive help guide for the language. It’s pretty sweet, however, on the standard Python Mac build, it doesn’t include all the documentation. This means some of the help guide is also missing parts. In order to add the HTML docs for Python 2.5, I ended up needing to compile the docs. This required me to install a few items, which are listed below.

Essentially, the docs need to be compiled as HTML from LaTeX. I had to install LaTeX for Mac, LaTeX2HTML and Darwin Ports (aka Mac Ports). This wasn’t too difficult, but I had a few missteps along the way. The directions are mostly for my own benefit, but if you find them useful or need a correction please let me know.

Goal: Create a link to the Python Docs for use with iPython.

  • Install Darwin Ports
  • Install LaTeX for Mac
  • Intall LaTeX2HTML
  • Download Python 2.5
  • Copy compiled HTML docs to Standard Location
  • Create env variable PYTHONDOCS for iPython help reference

Notes: I am running Mac OSX 10.5.4 with Python 2.5.1 and iPython 0.10. The $ is simply my prompt in Terminal.

Installing Darwin ports is very fast and easy, just visit http://darwinports.com/ and grab the latest version. Once you get it downloaded, it’s only 1.4 megs, just click and install. It’s a very quick step.

For LaTeX, you have two choices that are outlined in this guide. I chose the simple method, which results in downloading a fairly large file (1.2 gigs) but I didn’t want to spend my day debugging LaTeX install issues, after all this is to help me learning Python!

After downloading LaTeX, it’s a basic package installer. This is the version I used.

The next requirement is the LaTeX2HTML program. It converts the doc files to HTML that will be used by iPython. You can read more about it here. I found the installation instructions were not exactly what I needed. I had to add the /opt/local/bin to my Bash path in order to install LaTeX2HTML. I did this permanently by altering .bash_profile, but for the purpose of this instructions, I have done this temporarily.

# adding to Path
$ PATH = $PATH:/opt/local/bin
$ cd  /opt/local/bin
$ sudo mkdir -p portslocation/dports/latex2html/
$ cd portslocation/dports/latex2html/
# install latex2html
$ sudo port install latex2html

This process takes a little while, so grab a cup of coffee while it’s installing. After it finishes, you’re all set to compile the doc files for Python. First, you need to download the entire Python package. Take a look at the releases here. Here is the specific process I followed.

$ cd ~; mkdir tmp; cd tmp
$ curl -O http://www.python.org/ftp/python/2.5/Python-2.5.tgz
$ tar -zxf Python-2.5.tgz
$ cd Python-2.5/Doc
$ make

This will compile the docs. Specifically, we are interested in the HTML version it creates via LaTeX2HTML. Once it’s complete, you need to place the HTML files somewhere more permanent.

$ sudo cp -r html/ /usr/share/doc/python-2.5-html

Now it’s time to set PYTHONDOCS to the location we just moved the HTML files too. You can do this a few ways, the best method is adding it to the .bash_profile.

$ vi ~/.bash_profile
## Add the following
# export PYTHONDOCS=/usr/share/doc/python-2.5-html
# Save the file and exit
$ source ~/.bash_profile

You’re now ready to start using the doc files with iPython. For convenience, I have attached the compiled files here. Have fun!