Fixing A Jumping Audio Stream In ActionScript 3

We’re changing the format our streaming radio feeds at the moment and our test player kept jumping. We were a bit stumped as to what could be going on as the same code runs our current listen again functionality.

Delving into the ActionScript 3 code, we discovered that it appears to be down to how we implemented the NetStream object that handles the live stream. There is a variation between a live publishing stream and an archive subscribing stream and how they work with the buffer.

On a subscribing stream, the bufferTime attribute specifies how long to buffer incoming data before starting to display the stream. However, on a publishing stream, bufferTime specifies how long the outgoing buffer can grow before the application starts dropping frames.

We had our bufferTime set too low, the default is 0.1. We have now upped this and our problems have gone.

See the Adobe reference site for more information on the ActionScript 3 NetStream bufferTime attribute.

Creating A New Element With jQuery, With Or Without A Plugin

UPDATE: Whilst this remains an interesting example of creating a simple plugin, I no longer recommend this way of creating elements in jQuery. Instead just pass the html you want to use into jQuery directly as a string, e.g. var myH1Element = jQuery("<h1>My H1 Test</h1>");.

One function that seems to be missing in jQuery is to create new elements outside of the current DOM.

There is a good reason for this, normal vanilla JavaScript has the function createElement to do the job for you.

To create a new h1 element for example, we can do the following.

var myH1Element = document.createElement('h1');

We can easily combine this with jQuery to set the text inside for example…

jQuery(myH1Element).text("My H1 Text");

There is one downside, using the standard createElement we’re not able to chain functions with jQuery.

The way around this is to wrap the request in jQuery like this…

jQuery(document.createElement("h1"));

Now we can chain this together as before…

jQuery(document.createElement("h1")).text("My H1 Text");

If you don’t like the look of that, then we could always create a jQuery plugin, and add a createElement function to jQuery.

jQuery.extend({
createElement : function(elementName) {
return jQuery(document.createElement(elementName));
}
});

That must be one of the simpliest jQuery plugins ever!

Now we have extended jQuery with a createElement function we can chain calls to it like this.

jQuery.createElement("h1").text("My H1 Text").appendTo("body");

This will create a new h1 element, add the text “My H1 Text” inside the h1, then append the h1 inside the documents body tag.

Setting An AUTO_INCREMENT Seed In MySQL

I’ve used MySQL for many years and I’ve (nearly) always used AUTO_INCREMENT to get unique primary keys for my tables.

I came across a requirement earlier today that meant that I needed an id to start from 100000, instead of the the usual 1.

Normally I’d have just created a dummy record with an id of 100000 so the next insert would occur at 100001. This works as AUTO_INCREMENT automatically inserts the current highest value plus 1 for a column when you insert a row with NULL or 0 for the row’s value. This isn’t very elegant so I spent a few minutes with the MySQL manual and found that it is possible to seed the AUTO_INCREMENT to start at a specific value without having to use a dummy insert.

When creating a table you add a seed value at the end of the create statement something like this…

CREATE TABLE test(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50)
) AUTO_INCREMENT = 100000;

This means the first insert will have an id value of 100001 (the highest current value plus 1).

You can also alter an existing table to set the AUTO_INCREMENT seed…

ALTER TABLE test AUTO_INCREMENT=200000;

The next insert will have an id of 200001 now.

The Null-Coalescing Operator In C#

One bad habit that can occur when using a different programming language than the one you are used to, is writing code that looks very similar to the old language you are used to.

I found myself in this trap earlier, and only spotted it during a code review.

I had been using the ternary operator to compare and return results something like this in C#.

string currentStation = (selectedStation != null ? currentStation : "Q Radio");

It works, but C# provides something far nicer called the null-coalescing operator, ??, which lets you set a default value when you try to assign a nullable type to a non-nullable type.

The example above could be rewritten like this…

string currentStation = selectedStation ?? "Q Radio";

You can read more about the ?? operator for C# on the MSDN website.

Using A Canonical URL

Websites that can be accessed from multiple URL’s aren’t very search engine friendly.

Sometimes this structure may have evolved by accident as a site was developed at different times on varying technologies. You don’t want to turn off the old links as that would loose valuable search engine equity, but you don’t want them scattered on multiple URL’s either.

There is a solution, and that is to use a canonical URL.

The easiest is to add a simple link element to the page with it’s correct canonical URL. For example, if we have a page that can be reached at www.example.com/test.html, example.com/test.html or beta.example.com/test.html. we only want this to be index at www.example.com/test.html, so we can use add a link element as follows…

<link rel="canonical" href="http://www.example.com/test.html" />

Notice the use of rel="canonical", this is tells a search engine if it has accessed the page from another URL, it’s actually meant to be indexed from this URL.

Google, Yahoo and Microsoft have all agreed to support this canonical link element.

Another approach is to redirect the user to the page on the correct URL server side. Using Apache, this can be done using a RewriteRule and couple of RewriteCond‘s.

Using the same example, the rewrite rule would be something like this

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.example.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.example.com/$1 [L,R=301]

Here we make sure we’re not already accessing using the correct domain name. If we aren’t, the we redirect using the L flag to make sure this it’s the last rule run, and R=301 to issue a 301 Moved Permenantly redirect. Anyone visiting the page on an incorrect domain, will now be redirected to the right page.

Using jQuery And Mootools On The Same Page

While it’s never a good idea to bloat your webpage with too much unneeded content, there are times when you can’t avoid it. One example I came across recently was with my day job’s adoption of jQuery as our official JavaScript framework, I needed to add some jQuery goodness to some blog pages belonging to a certain category in Movable Type. Simple, right?

Well the site in question already used Mootools extensively, so the jQuery would have to run nicely next Mootools and not disrupt existing functionality.

The designers of jQuery have designed for this sort of situation, and have provided a function called noConflict that returns the use of $ to Mootools, or any other framework you may have installed as well.

Here’s some example code to show both jQuery and Mootools running in the same page…

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

In my Movable Type situation, I am able to use a custom MT tag to make sure jQuery only appears for certain categories. Let’s assume I have a category called jQuery where I need the jQuery library to be imported, the MTIfCategory tag is what I need to guard with…

<MTIfCategory label="jQuery">
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
</MTIfCategory>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

With this in place I can call jQuery functions using the jQuery variable, and MooTools using $ where necessary.

Using Config Files In Catalyst

I’ve been doing quite a bit of work with the Catalyst MVC framework lately.

Moving from development to live, the config system has really shown it’s usefulness. Instead of hardcoding values, we can simply move them out to the site’s config file and access these value programatically. It means we can run the same codebase on multiple machines and just tweak the config to pick up things like different database connection strings, cache settings etc.

I like to have my config file in Config::General format as it’s similar to Apache’s config files, but Catalyst can also handle config files in INI, JSON, Perl, XML or YAML, so you can use whatever you are most comfortable with.

Let’s have a look at a few examples. We’ll assume the Catalyst Application is called MyApp. This means we’ll have a perl module in our lib directory called MyApp.pm, and a config file called myapp.conf in the root directory.

MyApp.pm contains all the default values, but you can override these with myapp.conf. myapp.conf always takes priority.

Let’s create a simple string to say where our application is running. In MyApp.pm, in the __PACKAGE__->config we add an entry to the hash like this…


servername => 'dev',

Now when we run our application, we can access this value using the following code…


$c->config->{servername};

This will return “dev”. We can override this in the conf file, so in myapp.conf we can add…


servername production

Now when we run our application code, we’ll see “production” instead of “dev”.

A more practical use of the config file is to move out the database connection details. Let’s assume we have a simple MySQL based model in our lib/Model directory called Model::MyApp that handles our database work. We can override database connection details stored here in myapp.conf using something like this…

<"Model::MyApp">
connect_info dbi:mysql:myapp
connect_info www-rw
connect_info password
<connect_info>
AutoCommit 1
</connect_info>
</"Model::MyApp">

Now when we run the application, the connection details we entered in our conf file will be used instead. This is very useful as it means we don’t have to alter our codebase when we move the application to different servers that may have different databases. It’s also good for keeping dev, staging and live seperate as all that’s needed is a change to one config file.

For more information on how Catalyst can use a config file, have a look at
Catalyst::Plugin::ConfigLoader.

Sticky Buns Recipe

As it was Easter yesterday, and I don’t really like Hot Cross Buns, I decided to make variant of them, simple Sticky Buns. It’s more or less the Hot Cross Bun recipe, but without the fruit and peel.

You will need

  • 400g plain flour
  • 50g of strong white flour (though you can just use all plain if you want)
  • 50g caster sugar
  • 50g melted butter
  • 1 pack of dried yeast (the sort that doesn’t need activating in water first)
  • 1 tsp cinnamon powder
  • half tsp ground ginger
  • half tsp salt
  • 150ml warm water
  • 50ml warm milk
  • 1 beaten egg
  • Also, 1tbsp of caster sugar for glaze
  1. Sift together flours, cinnamon, ginger and salt.
  2. Mix in sugar and dried yeast
  3. Pour in water, milk, egg and butter and mix well
  4. Knead the dough on clean work surface for between 5 to 10 minutes until elastic
  5. Put in an oiled bowl, cover, and leave in a warm place to rise for about an hour
  6. Knock back the dough and seperate into 12 small balls. Place these on greased baking sheets
  7. Cover and let them rise again in a warm place for 30 minutes.
  8. Preheat over to gas mark 7, 220C, 425F
  9. Bake for 15 minutes
  10. When they come out, glaze with a mix or 1 part sugar to 1 part water melted in pan, then brushed over the surface.
  11. Enjoy!

These will only last about a day before going stale, but you probably won’t run into that problem as they are to delicious to leave that long.
Sticky Buns

Writing A jQuery Plugin To Stripe A Table

One of the most powerful features of jQuery is it’s plugin architecture. This allows developers to easily extend jQuery’s functionality.

I’ve decided to extend my table striping example code and turn it into a jQuery plugin. If I have a table with an id of test, I want to be able to call a stripe function on it’s selector, e.g. $('#test').stripe();

So how do we build this? Well firstly, as it’s a plugin we shouldn’t really be playing with the $ jQuery object incase our user has disabled it. There is a trick to get around this though…

(function($){
// code here can safely use $
})(jQuery);

What’s happening here? Well we’re using a closure to create an anonymous function into which we pass in the jQuery object. The parameter name we use in this function is $ so we can use this inside safely, even if the user has disabled this variable outside our plugin.
Now we have our $ variable we can get on with building the plugin.

$.fn.stripe = function(options) {
// define our function action here.
}

Here we’ve added a function to jQuery called stripe and told it to reference a fuction we’ve defined. Now we need to add the magic to this function to actually do the striping.

return this.each(function() {
$('/tbody:first>tr:even',this).addClass('even');
$('/tbody:first>tr:odd',this).addClass('odd');
});

As a jQuery selector can run over multiple items, we need to make sure we iterate over each of these. We use jQuery’s built in each function to do this. this refers to the current selector in this case.

Inside, we need to select the first tbody element of the selection, then for each child tr depending if it’s odd or even we set the class of that tr to be either even or odd. This should ensure that nested tables won’t be striped.

That’s great, but what would be even more useful would be the ability to define different class names dynamically so we’re not stuck with the two hardcoded ones.

This is easy to achieve by creating a set of defaults in a private object, passing overrides into our function, and using jQuery’s excellent extend function to merge the two.

var defaults = {
odd : 'dark',
even : 'lite'
};
var options = $.extend(defaults, options);

Now we can either just call .stripe directory, or pass in override options like this, .stripe({odd: 'testdark', even: 'testeven')

Putting this all together, we get the following code for our stripe plugin.

(function($){
$.fn.stripe = function(options) {
var defaults = {
odd : 'dark',
even : 'lite'
};
var options = $.extend(defaults, options);
return this.each(function() {
$('/tbody:first>tr:even',this).addClass(options.even);
$('/tbody:first>tr:odd',this).addClass(options.odd);
});
}
})(jQuery);

A configurable jQuery plugin, in just 13 lines of JavaScript. Marvellous!

Alternating Table Rows With JavaScript And jQuery

One of the most popular stories on this website is on Alternating Table Rows With Template Toolkit And CSS. The example I use is how to stripe alternate rows in an HTML table by applying a seperate class to each row.

As I’ve been learning jQuery lately, I thought I’d update this example to show how to do it using this excellent JavaScript framework.

Firstly, we need to setup our styles. We’ll have a lite and a dark class to use that will just set a different background colour.

<style type="text/css">
.lite {background-color: #ddffff;}
.dark {background-color: #aaffff;}
</style>

We’ll also need an example table.

<table class="stripe">
<tbody>
<tr>
<td>1</td><td>One</td>
</tr>
<tr>
<td>2</td><td>Two</td>
</tr>
<tr>
<td>3</td><td>Three</td>
</tr>
<tr>
<td>4</td><td>Four</td>
</tr>
<tr>
<td>5</td><td>Five</td>
</tr>
</tbody>
</table>

Notice how I have given the table a class of stripe. This is important, I’m going to use jQuery to only select table elements that have this class name, else every table on the page would be striped.

The jQuery to achieve the striping is actually very simple.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('table.stripe>tbody>tr:even').addClass("lite");
$('table.stripe>tbody>tr:odd').addClass("dark");
});
</script>

Firstly we added the jQuery library to the page. Next we setup our striping code to only run once the DOM is place. This is important as we’re going to be selecting and manipulating over the DOM next. The next two lines apply the lite class to even table rows and the dark class to odd table rows. Let’s look at this in a bit more detail.

The selector $('table.stripe>tbody>tr:even') is easier to explain backwards. We look for even matching tr elements, that have a parent of tbody, that has a parent of table with a class of stripe. The use of the > symbol instead of just a space is to make sure the elements are direct parent and child elements instead of just ancestor and descendant. Why is this important? Well if we used a space any nested tables that happened to have an striped ancestor would also be striped. This isn’t normally what we’d want to happen.