Commits

David Chambers committed e77ee29

add hints for Pygments

Comments (0)

Files changed (53)

15=applescript-syntax-highlighting.text

 To have SyntaxHighlighter parse a block of AppleScript, wrap the code in `pre`
 tags like so:
 
+    :::html
     <pre class="brush: applescript; class-name: applescript;"></pre>
 
 `brush: applescript;` tells SyntaxHighlighter to use the AppleScript brush for

17=php-print_filesize-function.text

 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 
+    :::php
+    <?php
+    
     /**
      * echoes nicely formatted filesize
      * @param string $filename
             echo "{$before}{$approx}{$size} {$unit}{$after}";
         }
     }
+    
+    ?>
 
 Example usage:
 
+    :::html+php
     <a href="favicon.ico">favicon.ico</a><?php print_filesize('favicon.ico'); ?>
 
 This gives: [favicon.ico][1] <span class="filesize">(≈1.1 kB)</span>.

18=prototype-loader-for-syntaxhighlighter.text

 
 2.  Replace:
     
+        :::html
         <script src="/path/to/scripts/shCore.js"></script>
         <script src="/path/to/scripts/shBrushAS3.js"></script>
         <script src="/path/to/scripts/shBrushBash.js"></script>
     
     with:
     
+        :::html
         <script>
             function Brush(name, filename, aliases)
             {
 **Style sheets.** By default, `settings.stylesheets` is an array containing
 just the default style sheet. This can easily be modified:
 
+    :::javascript
     stylesheets: ['shThemeCoda', 'shThemeAppleScript'],
 
 **Brushes.** By default, `settings.brushes` is an empty array. All the bundled
 brushes are handled automatically, but additional brushes can be included by
 adding them to this array:
 
+    :::javascript
     brushes: [
         new Brush('AppleScript', 'shBrushAppleScript', ['applescript'])
     ],
 **Defaults.** SyntaxHighlighter defaults can be set by modifying
 `settings.defaults`:
 
+    :::javascript
     defaults: {
         'auto-links': false,
         'html-script': true

20=photoshop-save-for-web-javascript.text

 Web & Devices...** which means that the file size of the resulting PNG will be
 smaller than would be the case using `PNGSaveOptions()`.
 
+    :::javascript
     function saveForWebPNG(outputFolderStr, filename)
     {
         var opts, file;

23=tiny-calendar-icons-sprite.text

 One uses a sprite by applying a background image to an element using CSS. One
 could start with an empty span element:
 
+    :::html
     <span class="day-1"></span>
 
 The following CSS sets the width and height of the element and sets the sprite
 as its background image:
 
+    :::css
     span.day-1
     {
         display: block;
 
 To have the "1" icon displayed, the element's background position is specified:
 
+    :::css
     span.day-1
     {
         display: block;
 
 Here's the final CSS:
 
+    :::css
     span.day
     {
         display: block;
 Note that I introduced the class name **day** to streamline the CSS. This must
 appear in the HTML, as in this example:
 
+    :::html
     <span class="day day-31"></span>
 
 

24=captions-over-images.text

 an image, just as a definition _describes_ a term. Meaningful markup for an
 image and its caption should look something like the following:
 
+    :::html
     <dl>
         <dt><img src="images/paris.jpg" alt="View from Notre Dame de Paris" /></dt>
         <dd>View from Notre Dame de Paris</dd>
 each image–caption pair reside in its own element. The final markup, however,
 is still quite clean:
 
+    :::html
     <dl class="captioned-image">
         <dt><img src="images/paris.jpg" alt="View from Notre Dame de Paris" /></dt>
         <dd><span>View from Notre Dame de Paris</span></dd>
 Check out the [captions over images demo][3] to see the approach in action. The
 CSS responsible for the appearance of the captions is as follows:
 
+    :::css
     dl.captioned-image         { position: relative; margin: 1em 0; }
     dl.captioned-image dt img  { display: block; }
     dl.captioned-image dd      { position: absolute; left: 0; bottom: 1.25em;

25=embed-youtube-clips-using-valid-xhtml-markup.text

 nothing to it. Simply replace both instances of `video_id` in the following
 code with -- you guessed it -- the video's ID.
 
+    :::html
     <object class="youtube"
             type="application/x-shockwave-flash"
             data="http://www.youtube.com/v/video_id&hl=en&fs=1&rel=0">
 YouTube object using CSS. There's no need to include the `width` and `height`
 attributes in the markup.
 
+    :::css
     object.youtube
     {
         width: 100%;

26=prototype-image-slider.text

 I noticed that the script was failing miserably in Safari, which didn't like
 the following line:
 
+    :::javascript
     li: new Element('li', { class: 'prev' }),
 
 Wrapping the word "class" in quotes as per this [recommendation by Tobie
 To create a new `Slider` simply call the constructor. The constructor requires
 one argument, either a DOM node or a string that references a node's ID.
 
+    :::javascript
     new Slider('slider');
 
 There's nothing to prevent multiple image sliders from appearing on a page. The
 following code turns each div with class of 'slider' into a `Slider` object.
 
+    :::javascript
     $$('div.slider').each(function (e) {
         new Slider(e);
     })
 Of course, it's a good idea to wait until the page is ready to be manipulated
 before... er... manipulating the page.
 
+    :::javascript
     document.observe('dom:loaded', function () {
         $$('div.slider').each(function (e) {
             new Slider(e);
 specifying the number of the slide to be displayed first. The default values
 are 1.0 and 0 (slides are numbered from zero).
 
+    :::javascript
     new Slider('slider', 0.5);     // faster transitions
     new Slider('slider', 1.0, 3);  // fourth slide displayed first
     new Slider('slider', 1.0, -1); // last slide displayed first

27=sticky-footers.text

 
 I'll explain how it's done. The markup must look something like the following:
 
+    :::html
     <body>
         <div id="wrap">
             <div id="main">
 The required CSS is also straightforward. First, set the heights of the html
 and body elements to the height of the viewport:
 
+    :::css
     html    { height: 100%; }
     body    { height: 100%; }
 
 This makes it possible to set the _minimum_ height of the wrapper div to the
 height of the viewport:
 
+    :::css
     #wrap   { min-height: 100%; }
 
 Next, pull up the footer so that it's visible without scrolling on pages
 without a lot of content:
 
+    :::css
     #footer { margin-top: -5em; height: 5em; }
 
 Finally, apply bottom padding to the main content div to ensure that nothing
 is covered by the footer:
 
+    :::css
     #main   { padding-bottom: 5em; }
 
 Putting it all together gives the following:
 
+    :::css
     html    { height: 100%; }
     body    { height: 100%; }
     #wrap   { min-height: 100%; }

28=memorable-passwords-for-programmers.text

 punctuation without resorting to the use of random strings of characters.
 Here's a "JavaScript" password, for example:
 
+    :::javascript
     var favourites = { book: 'Collapse', game: 'Agricola', site: 'ted.com' };
 
 Carefully written passwords wrapping personal information in programming syntax

30=css-fixed-position-headers.text

 
 The CSS for the header initially looked like this:
 
+    :::css
     #header
     {
         position: fixed;
 
 Here's the CSS:
 
+    :::css
     h1, h2, h3, h4, h5, h6, p
     {
         padding-top: 160px;
 
 Again, the CSS:
 
+    :::css
     div.id
     {
         position: relative;
 This approach introduces meaningless markup. Where previously we may have had
 something like this:
 
+    :::html
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc faucibus volutpat risus nec mollis. Integer dapibus dictum ultrices. Aenean vel lectus odio. Nam a mi ligula. Nam in dolor quis metus pretium imperdiet sit amet sed elit.</p>
     <h3 id="example">Example</h3>
     <p>Suspendisse potenti. Proin convallis lacinia nibh, nec auctor ligula mattis consectetur. Mauris vel elit sit amet nibh volutpat varius id vel sem. Pellentesque id purus ligula. Vivamus vel nulla vel justo tempor ultricies.</p>
 
 We now have the following:
 
+    :::html
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc faucibus volutpat risus nec mollis. Integer dapibus dictum ultrices. Aenean vel lectus odio. Nam a mi ligula. Nam in dolor quis metus pretium imperdiet sit amet sed elit.</p>
     <div id="example" class="id"></div>
     <h3>Example</h3>
 The previous approach got the job done, but introduced meaningless elements.
 This task is best performed with JavaScript.
 
+    :::javascript
     // accommodate fixed-position header
     document.observe('dom:loaded', function () {
         $$('h2[id]', 'h3[id]', 'h4[id]', 'h5[id]', 'h6[id]').each(function (e) {
 CSS can be used to position these empty divs in such a way that headings are
 visible when jumped to:
 
+    :::css
     h2.unidentified div, h3.unidentified div
     {
         float: left;

31=using-html5-time-element-in-wordpress-themes.text

 through its **datetime** attribute, provides a machine-readable version of
 dates and times.
 
+    :::html
     <time datetime="2009-11-01T16:41:53+13:00">1 November 2009</time>
 
 I wrote a function to generate the machine-readable dates and times for blog
 comments.
 
+    :::php
+    <?php
+    
     /**
      * echoes comment's date and time in format 2009-11-01T03:41:53+13:00
      */
     
         echo $output;
     }
+    
+    ?>
 
 While looping through comments in your WordPress theme, call the above function
 to print a valid datetime string.
 
+    :::html+php
     <time datetime="<?php comment_datetime(); ?>">

32=prototype-and-scriptaculous-combined-and-compressed.text

 I suggest including the Prototype and script.aculo.us version numbers in the
 `src`:
 
+    :::html
     <script src="/scripts/prototype+scriptaculous.min.js?p=1.6.1&amp;s=1.8.3"></script>
 
 This prevents caching issues that might otherwise arise upon updating to a

33=autopopulating-input-fields-with-prototype.text

 
 ### Markup {@id=markup}
 
+    :::html
     <input type="search" id="s" name="s" placeholder="search..." />
 
 ### Styling {@id=styling}
 
+    :::css
     input.placeholder { color: #a9a9a9 !important; }
 
 I decided to use `#a9a9a9` as Safari uses this colour for placeholder text.
 
 ### Placeholder class {@id=placeholder-class}
 
+    :::javascript
     var Placeholder = Class.create({
         initialize: function (element) {
             this.element = element;
 To create a new instance of the Placeholder class, simply pass the constructor
 a Prototype extended element:
 
+    :::javascript
     new Placeholder($('s'));
 
 Ensure that the DOM is ready by wrapping everything in Prototype's `dom:loaded`
 event listener. This also avoids polluting the global namespace.
 
+    :::javascript
     document.observe('dom:loaded', function () {
         var Placeholder = Class.create({
             ...
 snippet. I drew inspiration from a post on [iPhone-like password fields using
 jQuery][4].
 
+    :::javascript
     // provide input hints
     document.observe('dom:loaded', function () {
         var PLACEHOLDER_SUFFIX = '_placeholder'; // used for password inputs

35=duplicating-arrays-in-javascript.text

 significant portion of JavaScript coders do not think of variables as pointers
 to memory addresses. This leads to confusion in cases such as this:
 
+    :::javascript
     var fruits = ['orange', 'lime'];
     var colours = fruits; // naïve attempt to duplicate array
     colours.push('yellow');
 One might be surprised to learn that `fruits` now contains not just "orange"
 and "lime" but also "yellow". Oops! Here's how it went wrong:
 
+    :::javascript
     var fruits = ['orange', 'lime'];
     // fruits points to array containing "orange" and "lime"
     
 
 How, then, does one create a copy of the original array? _Slice!_
 
+    :::javascript
     var colours = fruits.slice();
 
 <aside id="footnote">* Languages such as C. Like

36=shockingly-simple-url-shortening.text

 URL shortener to run on that domain. I then struck upon a **simple, elegant
 solution** which took all of ten minutes to implement.
 
+    :::apache
     RewriteEngine On
     RewriteRule ^(.*)$ http://davidchambersdesign.com/$1 [R=301,L]
 

38=get-attributes-of-django-model-or-instance.text

 
 What is the best way to get the attributes of a Django model or instance?
 
+    :::python
     from django.db import models
     
     class Musician(models.Model):
 
 One option is to use `__dict__.keys()`:
 
+    :::pycon
     >>> m = Musician(first_name='Norah', last_name='Jones', instrument='piano')
     >>> print m.__dict__.keys()
     ['last_name', 'instrument', 'first_name', 'id']
 
 Another options is to use `_meta.fields`:
 
+    :::pycon
     >>> print [f.name for f in m._meta.fields]
     ['id', 'first_name', 'last_name', 'instrument']
 
 This approach also works on models directly:
 
+    :::pycon
     >>> print [f.name for f in Musician._meta.fields]
     ['id', 'first_name', 'last_name', 'instrument']
 

39=gorgeous-css3-buttons-inspired-by-aqua.text

 
 #### Hover ####
 
-    border-color: #740;
-    background: #fb4;
-    background: -webkit-gradient(linear, left top, left bottom,
-        from(#fb4), to(#fb4),
-        color-stop(0.1, #fea), color-stop(0.2, #fb4),
-        color-stop(0.5, #fb4), color-stop(0.5, #f90));
-    background: -moz-linear-gradient(-90deg,
-        #fb4 5%, #fea 15%, #fb4 25%, #fb4 50%, #f90 50%, #fb4);
-    color: #740;
-    cursor: pointer;
+    :::css
+    .aqua:hover {
+        border-color: #740;
+        background: #fb4;
+        background: -webkit-gradient(linear, left top, left bottom,
+            from(#fb4), to(#fb4),
+            color-stop(0.1, #fea), color-stop(0.2, #fb4),
+            color-stop(0.5, #fb4), color-stop(0.5, #f90));
+        background: -moz-linear-gradient(-90deg,
+            #fb4 5%, #fea 15%, #fb4 25%, #fb4 50%, #f90 50%, #fb4);
+        color: #740;
+        cursor: pointer;
+    }
 
 ![Hover state][k]
 : Hover state (right) alongside default state
 
 #### Focus ####
 
-    -webkit-box-shadow: #740 0 1px 0.75em;
-    -moz-box-shadow: #740 0 1px 0.75em;
-    color: #740;
-    outline: none;
+    :::css
+    .aqua:focus {
+        -webkit-box-shadow: #740 0 1px 0.75em;
+        -moz-box-shadow: #740 0 1px 0.75em;
+        color: #740;
+        outline: none;
+    }
 
 ![Focus state][l]
 : Focus state (right) alongside default state
 
 #### Active ####
 
-    border-color: #630;
-    background: #f90;
-    background: -webkit-gradient(linear, left top, left bottom,
-        from(#f90), to(#f90),
-        color-stop(0.1, #fd8), color-stop(0.3, #fb4),
-        color-stop(0.5, #fb4), color-stop(0.5, #f90));
-    background: -moz-linear-gradient(-90deg,
-        #f90 5%, #fd8 15%, #fb4 35%, #fb4 50%, #f90 50%, #f90);
-    color: #630;
+    :::css
+    .aqua:active {
+        border-color: #630;
+        background: #f90;
+        background: -webkit-gradient(linear, left top, left bottom,
+            from(#f90), to(#f90),
+            color-stop(0.1, #fd8), color-stop(0.3, #fb4),
+            color-stop(0.5, #fb4), color-stop(0.5, #f90));
+        background: -moz-linear-gradient(-90deg,
+            #f90 5%, #fd8 15%, #fb4 35%, #fb4 50%, #f90 50%, #f90);
+        color: #630;
+    }
 
 ![Active state][n]
 : Active state (right) alongside default state

41=mootools-every-method.text

 evaluates as true for every item in a collection. Take <var>list</var>,
 for example, an Array containing several numbers:
 
+    :::javascript
     var list = [4, -1, 3, 2, 5];
 
 One might wish to determine whether all the numbers in <var>list</var> are
 
 In plain JavaScript, this can be achieved using a `for` loop...
 
+    :::javascript
     var allPositive = true;
     for (var i = 0; i < list.length; i++) {
         if (list[i] <= 0) {
 
 ... or a `while` loop (which is slightly more efficient).
 
+    :::javascript
     var allPositive = true, i = list.length;
     while (i--) {
         if (list[i] <= 0) {
 With MooTools, one might consider using the [Array object's each method][5]
 instead of a `for` or `while` loop.
 
+    :::javascript
     var allPositive = true;
     list.each(function (item) {
         if (item <= 0) {
 there's probably a better tool for the job. In this case the [Array object's
 every method][6] is the perfect tool for the job.
 
+    :::javascript
     var allPositive = list.every(function (item) {
         return item > 0;
     });

42=forcing-browsers-to-rerender-elements.text

 [Forcing a UI redraw from JavaScript][1] highlights the solution employed by
 Thomas Fuchs, creator of the popular JavaScript library [script.aculo.us][2]:
 
+    :::javascript
     Element.addMethods({
         redraw: function (element) {
             element = $(element);
 
 The post's first comment includes an alternative approach:
 
+    :::javascript
     element.className = element.className;
 
 I gather that there are situations in which this simple solution fails -- it's

43=css-image-switcher-done-the-right-way.text

 enables more than one description -- a title and a caption, for instance -- to
 be tied to an image:
 
+    :::html
     <dl>
         <dt><img src="images/ds81.jpg" alt="Vancouver architecture" /></dt>
         <dd>This is not like that</dd>

45=using-google-for-site-search.text

 with its search functionality. Last night I decided to switch to a very simple
 solution:
 
+    :::html
     <form action="http://www.google.com/search" method="get">
         <div>
             <label for="q">Search davidchambersdesign.com</label>

48=linkify-tweets-with-regex.text

 
 #### JavaScript implementation ####
 
+    :::javascript
     tweet.replace(/(^|\s)(@\w+)/gm, '$1<a href="http://twitter.com/$2">$2</a>');
 
 It would of course be nicer to write:
 
+    :::javascript
     tweet.replace(/(?<=(?:^|\s))(@\w+)/gm, '<a href="http://twitter.com/$1">$1</a>');
 
 Unfortunately, JavaScript does not support lookbehinds in regular expressions,
 Python _does_ support lookbehinds, but only _fixed-width_ lookbehinds, so it
 won't allow `(?<=^|\s)`. No matter.
 
+    :::python
     import re
     re.sub(r'(?m)(^|\s)(@\w+)',
             lambda m: m.group(1) + '<a href="http://twitter.com/' + m.group(2) + '">' + m.group(2) + '</a>',

49=serializing-django-model-instances.text

 
 One might expect the following code to serialize a Django model instance:
 
+    :::python
     import simplejson
     simplejson.dumps(instance)
 
 but I do have a solution: define a serialization method on the instance's
 model.
 
+    :::python
     def toJSON(self):
         import simplejson
         return simplejson.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
 
 Here's the verbose equivalent for those averse to one-liners:
 
+    :::python
     def toJSON(self):
         fields = []
         for field in self._meta.fields:

50=freeing-myself-of-wordpress.text

 incredibly simple. One provides Django with an ordered list of places to
 look for templates.
 
+    :::python
     TEMPLATE_DIRS = (
         '/webapps/dcd/blog/templates',
         '/webapps/dcd/blog/mango/templates',

51=optimization-via-stringification.text

 
 Instead of...
 
+    :::css
     a[href="/contact/"] {
         background: url(/images/sprite.png) no-repeat 0 -30px;
     }
 
 use something like...
 
+    :::css
     a[href="/contact/"] {
         background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAALJJREFUeNrs1eEJgzAQBWATHKkjZAZHiCtkhKxgRnAGR+gMWSVypflRQfOeSgvlDgTxjvuSC0RTSul+EUZhhRX+bziNj0ur8tPT7OV6qEGMFJhCaNZYBA3DAKNSiyzUIs3iPEO41EgtEhbdSQtnUAo+wlmUhiWccx+4vMs3NnqmeEmpc96/norXndbc7fC28Xa0kmNwewbdPYY3fgvMjhDFm6POOUM3kf6dFFZY4a/FKsAADsZ+Lb8VFH4AAAAASUVORK5CYII=) no-repeat;
     }
 
 I threw together a Python script which converts images to encoded strings.
 
+    :::python
     #stringify.py
     import base64
     import sys
 
 #### Usage
 
+    :::console
     $ python stringify.py /path/to/image.png

52=autopopulating-input-fields-with-mootools.text

 I realize that it's not very pretty. I'm rewriting this site's JavaScript
 in MooTools, and the new code is quite a bit more elegant.
 
+    :::javascript
     // provide input hints
     window.addEvent('domready', function () {
         $$('input[placeholder]').addEvents({

54=first-matching-item.text

 loop as soon as a match is found. The examples here are in Python, but the same
 patterns apply to other languages.
 
+    :::python
     def student_by_id(students, id):
         for student in students:
             if student.id == id:
 This appoach strikes me as inelegant when the function is called in one place
 only. Today a different approached occurred to me.
 
+    :::python
     student = None
     for student in students:
         if student.id == id:

55=settimeout-fix-for-webkit-transition.text

 
 The code behind this example is not complicated:
 
+    :::javascript
     element.style.webkitTransitionProperty = 'left';
     element.style.webkitTransitionDuration = '2s';
     element.addEventListener('click', function () {
 
 The code:
 
+    :::javascript
     element.style.left = '100px';
     element.style.webkitTransitionProperty = 'left';
     element.style.webkitTransitionDuration = '2s';
 
 The working code:
 
+    :::javascript
     element.style.left = '100px';
     setTimeout(function () {
         element.style.webkitTransitionProperty = 'left';

57=empty-collections-are-valid-cache-data.text

 When using Django's cache, ensure that empty collections (`[]`, `()`, `{}`) are
 treated as valid cache data.
 
+    :::python
     cached = cache.get(cache_key)
     if cached:
         return cached
 
 Avoid this by explicitly comparing the return value to `None`:
 
+    :::python
     cached = cache.get(cache_key)
     if cached is not None: # much better!
         return cached

59=remove-textarea-scrollbars-in-internet-explorer.text

 As it turns out, there's a dead simple way to prevent this, and once again its
 everybody's friend `overflow` to the rescue.
 
+    :::css
     textarea { overflow: auto; }
 
 The `overflow` property seems to be a magical remedy for a variety of different

5=escape-special-characters-for-sql-regexp.text

 my own function for the job, and thought I'd share it in case others encounter
 the same problem:
 
+    :::php
+    <?php
+    
     function mysql_regexp_escape_string($string)
     {
         $special_chars = array('*', '.', '?', '+', '[', ']', '(', ')', '{', '}', '^', '$', '|', '\\');
     
         return str_replace($special_chars, $replacements, $string);
     }
+    
+    ?>
 
 It is quite possible that a solution to this problem already exists. If this is
 the case, I am eager to know about it.

60=positioning-elements-using-mootools.text

 
 It turns out that I'd been calling the wrong MooTools method. I'd been doing...
 
+    :::javascript
     element.setStyle('left', offset);
 
 rather than...
 
+    :::javascript
     element.setPosition({ x: offset });
 
 Frustratingly, `setStyle('left', offset)` _appeared_ to work, but its behaviour

66=python-loops-can-have-else-clause.text

 something in one using the syntax of the other. The most common example is
 joining a list.
 
-    # Python
+Python:
     
+    :::python
     ' '.join(['foo', 'bar'])
 
-    // JavaScript
+JavaScript:
     
+    :::javascript
     ['foo', 'bar'].join(' ')
 
 Often -- as is the case above -- the syntactical differences are minor, but
 [MooTools][1], for example, adds the [`every` method][2] to the `Array` object.
 This makes it possible to write some rather terse conditional statements.
 
+    :::javascript
     var numbers = [87, 33, 21, 75];
     if (numbers.every(function (n) { return n % 3 == 0; })) {
         window.alert('The numbers are all divisible by 3.');
 
 Python lists have no comparable method, so how would one write this in Python?
 
+    :::python
     numbers = [87, 33, 21, 75]
     if [n for n in numbers if n % 3 == 0] == numbers:
         print 'The numbers are all divisible by 3.'
 Assume that we have a list of documents, and we want to know which of the
 documents contain all the terms in a list of search terms.
 
+    :::javascript
     // (MooTools) JavaScript
     
     var terms = ['python', 'list', 'methods'], matches = [];
 
 Here, we _could_ use the list comprehension approach as before.
 
+    :::python
     # Python
     
     terms = ['python', 'list', 'methods']
 It turns out that Python has just the thing for the job: **in Python, a loop
 statements may have an `else` clause!**
 
+    :::python
     terms = ['python', 'list', 'methods']
     matches = []
     for document in documents:

67=self-caching-functions-in-javascript-and-python.text

 
 ### JavaScript Fibonacci without caching
 
+    :::javascript
     function fibonacci(n) {
         if (n <= 1) return n;
         return fibonacci(n - 2) + fibonacci(n - 1);
 
 I created a simple timer:
 
+    :::javascript
     function timer(func) {
         var i = 10, start;
         while (i--) {
 `cache`, which can _only_ be accessed by our `fibonacci` function. This
 ensures that our cache cannot be overwritten, accidentally or otherwise.
 
+    :::javascript
     fibonacci = (function () {
 
         var cache = {};
 1, making the `if (n <= 1)` logic unnecessary. Since one of the cached values
 is now 0, however, the `if (cached)` statement is no longer appropriate.
 
+    :::javascript
     fibonacci = (function () {
 
         var cache = { 0:0, 1:1 };
 It's also possible to cache results without using closure. This is important
 since Python (which I'll get to shortly) does not have this capability.
 
+    :::javascript
     function fibonacci(n) {
 
         if (!fibonacci.cache) fibonacci.cache = {};
 To avoid the overhead of checking for the existence of the cache on each
 invocation, the cache could be initialized outside of the function definition.
 
+    :::javascript
     function fibonacci(n) {
         // function body
     }
 
 ### Python Fibonacci without caching
 
+    :::python
     def fibonacci(n):
         if n <= 1:
             return n
 
 Does the vanilla Python function outperform the vanilla JavaScript function?
 
+    :::pycon
     >>> import time
     >>> for i in range(10): t = time.time(); fibonacci(35); print time.time() - t;
 
 
 ### Python Fibonacci with caching via function property
 
+    :::python
     def fibonacci(n):
         if n in fibonacci.cache:
             return fibonacci.cache[n]
 
 For the sake of completion I'll include this unappealing approach.
 
+    :::python
     def fibonacci(n, _cache={}):
         if n <= 1:
             return n

68=efficient-rounding-in-javascript.text

 So you have some number, `x`, which you want to round to the nearest integer.
 Easy, right?
 
+    :::javascript
     x = Math.round(x);
 
 Sure, but is this the fastest option? I think not.
 
+    :::javascript
     x = x < 0 ? x - 0.5 >> 0 : x + 0.5 >> 0;
 
 What the heck's going on here? `>>` is JavaScript's right shift operator.

69=filtering-lists-in-python-ruby-and-javascript.text

 highlight situations in which one language reads better than the other, such
 as the following.
 
+Python:
+
+    :::python
     '\n'.join(obj.name
         for obj in (
             repository.retrieve(id)
             for id in ids)
         if obj)
 
+Ruby:
+
+    :::ruby
     ids.map do |id|
       repository.retrieve(id)
     end.compact.map do |obj|
 
 My first attempt used the `filter` array method.
 
+    :::javascript
     ids.filter(function (id) {
         var obj = repository.retrieve(id);
         return obj && obj.name;
 
 Note the empty array (`[]`) on line 5 – that's our "accumulator".
 
+    :::javascript
     ids.reduce(function (ids, id) {
         var obj = repository.retrieve(id);
         if (obj && obj.name) ids.push(obj.name);

70=converting-integers-to-ordinals.text

 
 ### Python
 
+    :::python
     def ordinal(n):
         if 10 < n < 14: return u'%sth' % n
         if n % 10 == 1: return u'%sst' % n
 
 ### JavaScript
 
+    :::javascript
     function ordinal(n) {
         if (10 < n && n < 14) return n + 'th';
         switch (n % 10) {

73=ridding-markup-of-textual-decoration.text

 I was horrified to discover that [Bitbucket][4] is guilty of this. I've since
 rectified the situation (although the change is yet to go live).
 
+    :::css
     .footer-nav li {
         display: inline;
         list-type: none;
 Another case in which there's a temptation to mark up content in a certain way
 in order to achieve a certain visual appearance is the comma-separated list.
 
+    :::html
     <p><strong>Tags:</strong> Apple, iOS, iPad</p>
 
 This approach is inflexible. Displaying the tags as Twitter-style hashtags,
 in non-arbitrary order (alphabetical), an ordered list is probably appropriate.
 "Tags" is a heading that relates to the list of tags.
 
+    :::html
     <h4>Tags</h4>
     <ol>
         <li>Apple</li>
 list, but it gives us the freedom to dramatically alter the list's appearance
 without touching the markup.
 
+    :::css
     h4, ol, li {
         display: inline;
     }

74=javascript-date-and-time-localization.text

 localization: the `time` element, whose `datetime` attribute provides the
 canonical representation of a point in time.
 
+    :::html
     <time datetime="1984-04-26">26 April 1984</time>
 
 Simply by using the `time` element correctly our scripts gain access to date,
 
 Assume that a page contains the following `time` element.
 
+    :::html
     <time datetime="2010-11-27T13:30-00:00">27 November 2010</time>
 
 We could localize this element (along with any other `time` elements on the
 page) with a simple call to `localize`.
 
+    :::javascript
     $('time').localize();
 
 This updates both the visible text and the value of the `datetime` attribute.
 
+    :::html
     <time datetime="2010-11-28T00:30+11:00">28 November 2010</time>
 
 Date and time formats are fully customizable via [directives][2], and there

75=bitwise-not-operator-proves-useful-in-javascript.text

 JavaScript is a wonderful language. Its syntax, though, leaves a lot to be
 desired at times. String pattern matching, for example, is rather ugly.
 
+    :::javascript
     // ugly option 1
     if (text.indexOf('✈') != -1)
 
 and self-documenting. The language does provide a way to make such expressions
 terser, but it's far from obvious.
 
+    :::javascript
     // bitwise NOT
     if (~text.indexOf('✈'))
 
 behaves. It's equivalent to the following function, at least for the values
 that can be returned by [`indexOf`][2].
 
+    :::javascript
     function bitwiseNot(n) {
         return -n - 1;
     }

78=simulating-nonlocal-in-python-2.x.text

 scoping. Python 3 is lexically-scoped, too, as the following code
 demonstrates.
 
+    :::python
     def cache(saved=None):
         def _(thing=None):
             nonlocal saved
 If (the rebound) `cache` is passed no arguments (or `None`), `saved` is
 returned. Otherwise, `thing` is assigned to `saved` and returned.
 
+    :::pycon
     >>> cache(2**3)
     8
     >>> cache()
 
 ### Bringing lexical scoping to Python 2.x
 
+    :::python
     def cache(saved=None):
         def _(thing=None):
             # nonlocal saved
 
 The `nonlocal` line is commented out as it's a syntax error in Python 2.x.
 
+    :::pycon
     >>> cache(2**3)
     8
     >>> cache()
 
 #### Dictionary
 
+    :::python
     def cache():
         ns = {'saved': None}
         def _(thing=None):
 
 #### Function object
 
+    :::python
     def cache():
         def ns(): pass
         ns.saved = None

79=faster-terminal-navigation-via-aliases.text

 Another cool thing to know about is `cd -`, which takes you to the directory
 you were in most recently.
 
+    :::console
     $ cd ~/Desktop
     $ site-packages
     $ pwd

7=wordpress-login-redirect.text

 _front-end_ functionality hidden from guests. In such instances, we can simply
 provide a standard login link:
 
+    :::html+php
     <a href="<?php bloginfo('url'); ?>/wp-login.php">log in</a>
 
 While this gets the job done, it takes users to the dashboard after they have
 round trip from **origin** to **wp-login.php** to **wp-admin/** to **/** and
 finally back to **origin** by including a value for `redirect_to` in the href:
 
+    :::html+php
     <a href="<?php bloginfo('url'); ?>/wp-login.php?redirect_to=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>">log in</a>
 
 The above returns users to their starting point after they've logged in.

80=customizing-your-bash-prompt-for-pleasure-and-profit.text

 Terminal loads your **~/.bash_profile** but not your **~/.bashrc**. As a
 result, your **~/.bash_profile** should contain the following snippet.
 
+    :::bash
     if [ -f ~/.bashrc ]; then
       source ~/.bashrc
     fi

82=repeating-strings-in-javascript.text

 
 ### Python {@id=python}
 
+    :::python
     '=' * 5
 
 ### Ruby {@id=ruby}
 
+    :::ruby
     '=' * 5
 
 ### PHP {@id=php}
 True to form, repeating strings in JavaScript is ugly and counterintuitive,
 but kinda cool.
 
+    :::javascript
     new Array(5 + 1).join('=')

83=changing-the-colour-of-list-bullets-using-css.text

 
 So, you're about to style an unordered list of some sort...
 
+    :::html
     <h1>TXJS 2011 Speakers</h1>
     <ul>
       <li>Brendan Eich</li>
 You've decided upon hanging square bullets in a light grey – nothing too
 distracting...
 
+    :::css
     ul {
       list-style: square outside;
       color: #ccc;
     }
-    
     li {
       color: #000;
     }
 
 ### Conventional hack {@id=conventional-hack}
 
+    :::html
     <h1>TXJS 2011 Speakers</h1>
     <ul>
       <li><span>Brendan Eich</span></li>
       <li><span>Paul Irish</span></li>
     </ul>
 
-    ul {
-      list-style: square outside;
-      color: #ccc;
-    }
-    
-    li>span {
-      color: #000;
-    }
+    <style>
+      ul {
+        list-style: square outside;
+        color: #ccc;
+      }
+      li > span {
+        color: #000;
+      }
+    </style>
 
 This gets the job done, but those `span`s are ugly – there are ways to achieve
 the desired visual effect without hacking the markup.
 
 ### Background image technique {@id=background-image-technique}
 
+    :::css
     ul {
       list-style: none;
     }
-    
     li {
       margin-left: -12px;
       background: url(bullet.png) no-repeat 0;
 
 ### Pseudo-element technique {@id=pseudo-element-technique}
 
+    :::css
     ul {
       list-style: none;
     }
-    
     li {
       position: relative;
     }
-    
     li:before {
       position: absolute;
       top: 8px;
 
 Prefer round bullets? No problem. :)
 
+    :::css
       ...
       -webkit-border-radius: 2px;
       -moz-border-radius: 2px;

86=end-of-string-anchor-in-javascript-regular-expressions.text

 It's possible, though, to have a lookahead act as an end of string anchor
 in multiline mode:
 
+    :::javascript
     > /bar(?![\s\S])/m.test('foo\nbar')
     true
     > /bar(?![\s\S])/m.test('foo\nbar\n')

88=escaping-html-in-javascript.text

 [HTML escaping][2], which provoked me to rewrite Bitbucket's escape
 function (invoked from within Underscore templates):
 
+    :::javascript
     function makeSafe(text) {
       return text.replace(/[&<>"'`]/g, function (chr) {
         return '&#' + chr.charCodeAt(0) + ';';
 To accommodate unquoted attribute values, the following function could be
 used instead:
 
+    :::javascript
     function makeSafe(text) {
       return text.replace(/\W/g, function (chr) {
         return '&#' + chr.charCodeAt(0) + ';';

89=decorators-in-javascript.text

 
 A decorator is a function which takes a function and returns a function:
 
+    :::coffeescript
     decorator = (fn) -> fn
 
 Obviously, this doesn't do anything useful. It's the fact that a decorator
 that makes the pattern interesting. Commonly a decorator will simply wrap a
 function invocation in a check of some sort:
 
+    :::javascript
     var loginRequired = function (fn) {
       return function () {
         if (!user.authenticated) {
 The above decorator could be used to "guard" actions that only authenticated
 users are permitted to perform:
 
+    :::javascript
     var changeUsername = loginRequired(function (username) {
       $.ajax({
         type: 'PUT',
 
 The CoffeeScript equivalent is quite a bit clearer:
 
+    :::coffeescript
     changeUsername = loginRequired (username) ->
       $.ajax
         type: 'PUT'

8=valid-xhtml-alternative-to-strike.text

 `<strike>` is not valid XHTML; I'd forgotten the correct XHTML markup for
 this purpose:
 
+    :::html
     my favourite colour is <del>red</del> <ins>white</ins>
 
 The above gives: my favourite colour is <del>red</del> <ins>white</ins>
 It's a good idea to explicitly define the appearance of deleted and inserted
 text in your style sheet:
 
+    :::css
     del { text-decoration: line-through; }
     ins { text-decoration: underline; }
 

90=getting-started-with-socket.io.text

 JavaScript code. For those unfamiliar with CoffeeScript's syntax, here's the
 fifteen second rundown:
 
+    :::coffeescript
     qux = foo 'bar', (baz) -> 'Hello, world!'
 
 The above is equivalent to:
 
+    :::javascript
     var qux = foo('bar', function (baz) {
       return 'Hello, world!';
     });
 
 This is Node 101 stuff:
 
+    :::coffeescript
     fs   = require 'fs'
     http = require 'http'
     
 
 ### Step 2: Add server-side event handlers
 
+    :::coffeescript
     io = require('socket.io').listen server
     
     io.sockets.on 'connection', (socket) ->
 
 ### Step 3: Create the HTML file
 
+    :::html
     <!doctype html>
     <html>
       <head>
 
 ### Step 4: Add client-side Socket.IO event handlers
 
+    :::coffeescript
     $status = $ '#status'
     socket = io.connect()
     
 
 ### Step 5: Add DOM event handlers which emit custom events
 
+    :::coffeescript
     $input = $ 'input'
     
     $('button').click ->

91=higher-level-style-sheets.text

 
 ### Original CSS
 
+    :::css
     ol.archives {
       margin: 0 0 0 -21px;
       list-style: none;
 that selectors needn't include their "context" (ancestors). It also means
 that a style sheet's structure resembles that of the corresponding markup.
 
+    :::sass
     ol.archives
       margin: 0 0 0 -21px
       list-style: none
 data URI – the Base64-encoded representation of calendar.png. If calendar.png
 is changed, `compass compile` is all that's required to update the data URI.
 
+    :::sass
     ol.archives
       ...
       time
 with sprites, but in this case all that's required is to generate background
 positions for an existing sprite. The first step is to add a loop:
 
+    :::sass
     @for $date from 1 through 31
       // do stuff
 
 The loop variable, `$date`, can be interpolated to generate the selectors:
 
+    :::sass
     @for $date from 1 through 31
       &[datetime*="#{$date}T"]
 
 Almost. This gives `datetime*="1T"`, `datetime*="2T"`, etc. rather than their
 zero-padded equivalents. Adding a leading zero when required is not difficult:
 
+    :::sass
     @for $date from 1 through 31
       @if $date < 10
         $date: "0#{$date}"
 Finally, variables can be used to calculate the `background-position` of each
 element:
 
+    :::sass
     $offset: -20px
     $x: 3
     $y: 1