Commits

Stephen Skory  committed 5b1e027

Initial commit. It is functional, but has room to improve.

  • Participants

Comments (0)

Files changed (3)

+mydb - A Python cgi script to view yt datasets on Amazon SimpleDB.
+
+This is simple and quickly written script which will allow you to view all your
+datasets that you've ever touched with yt, from anywhere. Given your AWS
+credentials, it will log you in and display the particulars of the datasets.
+You can perform searches with various filters to narrow down what is displayed.
+
+What's included:
+  * mydb.py - The script itself. Right now, you should need to change the
+    'hostname' and 'url' variables at the top, as well as the location of
+    the 'sorttable.js' script (it's almost at the bottom, do a text search!).
+
+  * sorttable.js - A bit of javascript that enables the table to sort within
+    the browser. http://www.kryogenix.org/code/browser/sorttable/
+
+  * README - This file!
+
+
+
+This code is open source, don't sue me if it breaks up your marriage, and so
+on.
+
+Stephen Skory
+s@skory.us
+
+#!/usr/bin/env python
+# Stephen Skory
+# s@skory.us
+# Display the yt dataset database on Amazon SimpleDB.
+
+import boto
+import cgi, time, Cookie, datetime, random, os
+#import cgitb; cgitb.enable() # for debugging
+
+hostname = ".stephenskory.com"
+url = "http://stephenskory.com/cgi-bin/mydb.py"
+
+ProblemTypes = {
+1 : "Shock Tube (unigrid and AMR)",
+2 : "Wave Pool",
+3 : "Shock Pool (unigrid 2D, AMR 2D and unigrid 3D)",
+4 : "Double Mach Reflection",
+5 : "Shock in a Box",
+6 : "Implosion",
+7 : "SedovBlast",
+8 : "KH Instability",
+9 : "2D/3D Noh Problem",
+10 : "Rotating Cylinder",
+11 : "Radiating Shock",
+12 : "Free Expansion",
+20 : "Zeldovich Pancake",
+21 : "Pressureless Collapse",
+22 : "Adiabatic Expansion",
+23 : "Test Gravity",
+24 : "Spherical Infall",
+25 : "Test Gravity: Sphere",
+26 : "Gravity Equilibrium Test",
+27 : "Collapse Test",
+28 : "TestGravityMotion",
+29 : "TestOrbit",
+30 : "Cosmology Simulation",
+31 : "Isolated Galaxy Evolution",
+35 : "Shearing Box Simulation",
+40 : "Supernova Restart Simulation",
+50 : "Photon Test",
+60 : "Turbulence Simulation",
+61 : "Protostellar Collapse",
+62 : "Cooling Test",
+101 : "3D Collapse Test (hydro_rk)",
+102 : "1D Spherical Collapse Test (hydro_rk)",
+106 : "Hydro and MHD Turbulence Simulation (hydro_rk)",
+107 : "Put Sink from restart",
+200 : "1D MHD Test",
+201 : "2D MHD Test",
+202 : "3D MHD Collapse Test",
+203 : "MHD Turbulent Collapse Test",
+207 : "Galaxy disk",
+208 : "AGN disk",
+300 : "Poisson solver test",
+400 : "Radiation-Hydrodynamics test 1 - constant fields",
+401 : "Radiation-Hydrodynamics test 2 - stream test",
+402 : "Radiation-Hydrodynamics test 3 - pulse test",
+403 : "Radiation-Hydrodynamics test 4 - grey Marshak test",
+404 : "Radiation-Hydrodynamics test 5 - radiating shock test",
+405 : "Radiation-Hydrodynamics test 5 - radiating shock test",
+410 : "Radiation-Hydrodynamics test 10 - Static HI ionization",
+411 : "Radiation-Hydrodynamics test 11 - Static HI ionization",
+412 : "Radiation-Hydrodynamics test 12 - HI ionization of a clump",
+413 : "Radiation-Hydrodynamics test 13 - HI ionization of a steep region",
+414 : "Radiation-Hydrodynamics test 14 - Cosmological HI ionization",
+415 : "Radiation-Hydrodynamics test 15 - Cosmological HI ionization",
+450 : "Free-streaming radiation tests",
+451 : "Free-streaming radiation tests",
+452 : "Free-streaming radiation tests"
+}
+
+defaults = {
+'order_by' : 'last_seen_time',
+'order' : 'DESC',
+'limit' : 25,
+'BoxSizeMin' : 0.,
+'BoxSizeMax' : 0.,
+'ProblemType' : 0,
+'TotalNumberOfGridCellsMin' : 0,
+'TotalNumberOfGridCellsMax' : 0,
+
+'cr_dayMin' : 1,
+'cr_moMin' : 1,
+'cr_yrMin' : 1971,
+'cr_dayMax' : 31,
+'cr_moMax' : 12,
+'cr_yrMax' : 2020,
+
+'ls_dayMin' : 1,
+'ls_moMin' : 1,
+'ls_yrMin' : 1971,
+'ls_dayMax' : 31,
+'ls_moMax' : 12,
+'ls_yrMax' : 2020,
+
+'machine' : None,
+
+'zMin' : -1.,
+'zMax' : 200.,
+
+'sim_uuid' : None,
+
+'topgrid0Min' : 0,
+'topgrid0Max' : 2048
+}
+
+class mydb(object):
+    def __init__(self):
+        # Set some initial values
+        self.error = False
+        self.bad_login = False
+        self.cookie_set = False
+        self.keys = None
+        self.defaults = defaults.copy()
+        self.form = cgi.FieldStorage()
+        # Check to see if they're logging out.
+        if self.form.getvalue('clear_cookie') == 'True':
+            self.clear_cookie()
+            return
+        # Do some stuff.
+        self.check_form()
+        self.get_query_inputs()
+        self.check_cookie()
+        self.headers('My yt Datasets')
+        self.print_login_error()
+        if not self.cookie_set:
+            self.login_box()
+        self.main_html()
+        self.footers()
+
+    def check_form(self):
+        # We'll see if the user input one or more of the form fields, and
+        # if so, try to set the cookie if they entered enough fields.
+        if self.form.getvalue('s3id') is not None and \
+                self.form.getvalue('s3secret') is not None:
+            # Yay, they did both, now let's see if it's correct.
+            self.s3id = self.form.getvalue('s3id')
+            self.s3secret = self.form.getvalue('s3secret')
+            valid = self.try_sdb()
+            if valid:
+                # Let's set the cookie values.
+                cookie = Cookie.SimpleCookie()
+                cookie["cookie_s3id"] = self.form.getvalue('s3id')
+                cookie["cookie_s3id"]["domain"] = hostname
+                cookie["cookie_s3id"]["path"] = "/"
+                
+                cookie["cookie_s3secret"] = self.form.getvalue('s3secret')
+                cookie["cookie_s3secret"]["domain"] = hostname
+                cookie["cookie_s3secret"]["path"] = "/"
+                
+                if self.form.getvalue('s3cookie') == 'yes':
+                    # Set to expire a long time in the future,
+                    # effectively permanently. No expires means the cookie
+                    # is deleted when the browser shuts down.
+                    expiration = datetime.datetime.now() + \
+                        datetime.timedelta(days=30000)
+                    cookie["cookie_s3id"]["expires"] = \
+                        expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
+                    cookie["cookie_s3secret"]["expires"] = \
+                        expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
+    
+                #print "Content-type: text/plain"
+                print cookie.output()
+                #print "Content-type: text/html\n"
+                self.cookie_set = True
+            else:
+                # Not valid.
+                self.bad_login = True
+                self.error = True
+                self.cookie_set = False
+        # They entered fewer than required, so tell them they messed up.
+        elif self.form.getvalue('s3id') is not None or \
+                self.form.getvalue('s3secret') is not None or \
+                self.form.getvalue('s3cookie') is not None:
+            self.error = True
+
+    def get_query_inputs(self):
+        # We make sure types are correct when these are used, not here.
+        for key in self.defaults:
+            if self.form.getvalue(key) is not None:
+                self.defaults[key] = self.form.getvalue(key)
+                if key == 'limit':
+                    self.defaults[key] = min(2500, int(self.form.getvalue(key)))
+
+    def check_cookie(self):
+        if self.cookie_set: return
+        # Check to see if the cookie is saved.
+        try:
+            cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
+            self.s3id = cookie["cookie_s3id"].value
+            self.s3secret = cookie["cookie_s3secret"].value
+            if self.s3id == 's3id' or self.s3secret == 's3secret':
+                # Cookie is no good.
+                self.cookie_set = False
+                return
+            else:
+                self.cookie_set = True
+        except (Cookie.CookieError, KeyError):
+            self.cookie_set = False
+            return
+        # Now check to see if the cookie is valid.
+        valid = self.try_sdb()
+        if not valid:
+            self.cookie_set = False
+            self.bad_login = True
+
+    def print_login_error(self):
+        if self.bad_login:
+            print "<b>Login credentials not accepted!</b><br />"
+        if self.error or self.bad_login:
+            print "<b>Please (re-)enter both your Amazon Access Key and Secret Key!</b><br />"
+
+    def try_sdb(self):
+        # Test to see if the s3 credentials work.
+        self.sdb = boto.connect_sdb(self.s3id, self.s3secret)
+        try:
+            self.domains = self.sdb.get_all_domains()
+            return True
+        except:
+            return False
+
+    def main_html(self):
+        # The main place for html, This calls all the work assuming
+        # that the login is valid.
+        if not self.cookie_set: return
+        print "<a href='%s?clear_cookie=True'>Log out</a><br /><br />\n" % url
+        print "<h1>My yt Datasets</h1>"
+        try:
+            self.datasets = self.sdb.get_domain('datasets')
+        except:
+            print "Oops! There does not seem to be any datasets stored on SimpleDB. "
+            print "You might want to see how to set that up by looking at the docs."
+            return
+        # Yes, backtick quotes.
+        query = self.make_query()
+        
+        self.query_and_print(query)
+        self.print_input_boxes()
+        print """
+<h3>Your SimpleDB SQL Query:</h3>
+%s
+""" % query
+        
+
+
+    def query_and_print(self, query):
+        rs = self.datasets.select(query)
+        i = 0
+        count = 0
+        more = False
+        for i, item in enumerate(rs):
+            if i == 0:
+                print "<table border='1' class='sortable'>\n"
+            # The first one will be parsed for table column headers, and it
+            # will set self.keys.
+            if i == 0: self.print_column_headers(item)
+            # Skip items that don't fit the filter.
+            if not self.item_filter(item):
+                continue
+            print "<tr>\n"
+            for key in self.keys:
+                this = item[key]
+                # Change unix time to human readable format. GMT.
+                if key == 'last_seen_time' or key == 'creation_time':
+                    this = float(this)
+                    this = time.gmtime(this)
+                    this = time.asctime(this)
+                # Change the problem type to a description.
+                if key == 'ProblemType':
+                    try:
+                        this = ProblemTypes[int(this)]
+                    except:
+                        pass
+                # Don't need all the digits of time or redshift.
+                if key == 'redshift' or key == 'time':
+                    this = "<span class='detail' title='%s'>%.3f...</span>" \
+                        % (this, float(this))
+                # Make the sim_uuid into a clickable link.
+                if key == 'simulation_uuid':
+                    short_this = this[:3] + "..." + this[-3:]
+                    short_this = "<span class='detail' title='%s'>%s</span>" % \
+                        (this, short_this)
+                    this = self.make_link(short_this, print_out = False, sim_uuid = this)
+                # Shorten long text fields, but allow a mouse-over to show
+                # the full text.
+                if key == "pf_path":
+                    pieces = this.split("/")
+                    this = "<span class='detail' title='%s'>%s</span>" % \
+                        (this, ("/" + pieces[1] + "/.../" + pieces[-2] + "/" + pieces[-1]))
+                if key == "dset_uuid":
+                    this = "<span class='detail' title='%s'>%s</span>" % \
+                        (this, (this[:3] + "..." + this[-3:]))
+                if key == "output_type":
+                    this = "<span class='detail' title='%s'>%s</span>" % \
+                        (this, this[:6] + "...")
+                print "<td>%s</td>\n" % this
+            print "</tr>\n"
+            count += 1
+            if count == self.defaults['limit']:
+                more = True
+                break
+        if i > 0:
+            print "</table>\n"
+            #print "<table border='1'>"
+            #self.print_column_headers(item)
+            #print "</table>"
+        # This i/j business is to deal with cases when no records are returned.
+        if (i > 0):
+            j = i + 1
+        else:
+            j = 0
+        print "<h3>Search returned %d records, %d passed filters." % \
+            (j, count)
+        if more: print """
+<i>The are probably records not being shown that match the search filters.
+Increase the number of returned items or narrow your search filters to see them.</i></h3>\n
+"""
+        else: print "</h3>\n"
+        #print os.environ
+
+    def print_column_headers(self, item):
+        print "<tr>\n"
+        if self.keys is None:
+            self.keys = item.keys()
+            self.keys.sort()
+        for key in self.keys:
+            this = key
+            if this == 'last_seen_time' or this == 'creation_time':
+                this = this + ' (UTC)'
+            if this == 'BoxSize':
+                this = this + ' (Mpc/h)'
+            print "<th>%s</th>\n" % this
+        print "</tr>\n"
+
+    def item_filter(self, item):
+        # Filters the returned items on the criteria that SimpleDB doesn't
+        # handle very well, i.e. numerical comparisons.
+        if float(item['BoxSize']) < float(self.defaults['BoxSizeMin']):
+            return False
+        if float(item['BoxSize']) > float(self.defaults['BoxSizeMax']) and \
+            float(self.defaults['BoxSizeMax']) != 0.0:
+            return False
+
+        if int(item['TotalNumberOfGridCells']) < int(self.defaults['TotalNumberOfGridCellsMin']):
+            return False
+        if int(item['TotalNumberOfGridCells']) > int(self.defaults['TotalNumberOfGridCellsMax']) and \
+            int(self.defaults['TotalNumberOfGridCellsMax']) != 0:
+            return False
+        
+        cr_min = self.convert_date(self.defaults['cr_dayMin'],
+                 self.defaults['cr_moMin'], self.defaults['cr_yrMin'], 0)
+        if float(item['creation_time']) < cr_min:
+            return False
+        cr_max = self.convert_date(self.defaults['cr_dayMax'],
+                 self.defaults['cr_moMax'], self.defaults['cr_yrMax'], 0)
+        if float(item['creation_time']) > cr_max:
+            return False
+        
+        ls_min = self.convert_date(self.defaults['ls_dayMin'],
+                 self.defaults['ls_moMin'], self.defaults['ls_yrMin'], 0)
+        if float(item['last_seen_time']) < ls_min:
+            return False
+        ls_max = self.convert_date(self.defaults['ls_dayMax'],
+                 self.defaults['ls_moMax'], self.defaults['ls_yrMax'], 0)
+        if float(item['last_seen_time']) > ls_max:
+            return False
+
+        if float(item['redshift']) < float(self.defaults['zMin']):
+            return False
+        if float(item['redshift']) > float(self.defaults['zMax']):
+            return False
+        
+        if int(item['topgrid0']) < int(self.defaults['topgrid0Min']):
+            return False
+        if int(item['topgrid0']) > int(self.defaults['topgrid0Max']):
+            return False
+        
+        # All the way here? Yay!
+        return True
+
+    def make_query(self):
+        # Yes, backticks for field names and normal quotes for values.
+        line = "select * from `datasets` where `%s` is not null " % self.defaults['order_by']
+
+        if int(self.defaults['ProblemType']) is not 0:
+            line += "and `ProblemType` = '%d' " % int(self.defaults['ProblemType'])
+        
+        # Note the two %% which escapes to % in the string.
+        if self.defaults['machine'] is not defaults['machine']:
+            line += "and `machine` like '%%%s%%' " % self.defaults['machine']
+        
+        if self.defaults['sim_uuid'] is not defaults['sim_uuid']:
+            line += "and `simulation_uuid` like '%%%s%%' " % self.defaults['sim_uuid']
+
+        line += "order by `%s` %s limit %d" % (self.defaults['order_by'],
+            self.defaults['order'], int(self.defaults['limit']))
+        return line
+
+    def print_input_boxes(self):
+        # Prints out the form below the table.
+        print """
+<form method='get'>
+<input type='submit' value='Submit Parameter Search' />
+<input type='reset' value='Reset'>
+<a href="./mydb.py">Start Over</a><br><br>
+<input type='hidden' name='order_by' value='%s'>
+<input type='hidden' name='order' value='%s'>
+<table border='1'>
+<tr><th>Boxsize min/max<th>ProblemType<th>TotalNumberOfGridCells</tr>
+<tr>
+<td>
+""" % (self.defaults['order_by'], self.defaults['order'])
+        # BOXSIZE
+        print """
+(in Mpc/h)<br>
+min: <input type="text" name="BoxSizeMin" value="%d" size="4"/><br>
+max: <input type="text" name="BoxSizeMax" value="%d" size="4"/><br>
+(0 means no max)
+</td>
+""" % (float(self.defaults['BoxSizeMin']), float(self.defaults['BoxSizeMax']))
+
+        # PROBLEMTYPE
+        print """
+<td>
+<select name="ProblemType">
+"""
+        if int(self.defaults['ProblemType']) == 0:
+            print "<option value='0' selected>All</option>"
+        else:
+            print "<option value='0'>All</option>"
+        for key in sorted(ProblemTypes):
+            name = "(%d) " % (key)
+            name += ProblemTypes[key]
+            if key == int(self.defaults['ProblemType']):
+                print "<option value='%d' selected>%s</option>" % (key, name)
+            else:
+                print "<option value='%d'>%s</option>" % (key, name)
+        print """
+</select>
+</td>
+"""
+        # Number of Grid Cells.
+        print """
+<td>
+min: <input type="text" name="TotalNumberOfGridCellsMin" value="%d" size="12"/><br>
+max: <input type="text" name="TotalNumberOfGridCellsMax" value="%d" size="12"/> <br>(0 means no max)
+</td>
+""" % (int(self.defaults['TotalNumberOfGridCellsMin']), int(self.defaults['TotalNumberOfGridCellsMax']))
+        print """
+</tr>
+</table>
+<table border="1">
+<tr><th>creation_time<th>last_seen_time<th>machine</tr>
+"""
+        # Creation date ranges.
+        print """
+<tr><td>
+Begin: Day <input type="text" name="cr_dayMin" value="%d" size=2/>
+ Month <input type="text" name="cr_moMin" value="%d" size=2/>
+ Year <input type="text" name="cr_yrMin" value="%d" size=4/><br>
+End: Day <input type="text" name="cr_dayMax" value="%d" size=2/>
+ Month <input type="text" name="cr_moMax" value="%d" size=2/>
+ Year <input type="text" name="cr_yrMax" value="%d" size=4/>
+ </td>
+""" % (int(self.defaults['cr_dayMin']), int(self.defaults['cr_moMin']), int(self.defaults['cr_yrMin']),
+       int(self.defaults['cr_dayMax']), int(self.defaults['cr_moMax']), int(self.defaults['cr_yrMax']))
+        
+        # Last seen ranges
+        print """
+<td>
+Begin: Day <input type="text" name="ls_dayMin" value="%d" size=2/>
+ Month <input type="text" name="ls_moMin" value="%d" size=2/>
+ Year <input type="text" name="ls_yrMin" value="%d" size=4/><br>
+End: Day <input type="text" name="ls_dayMax" value="%d" size=2/>
+ Month <input type="text" name="ls_moMax" value="%d" size=2/>
+ Year <input type="text" name="ls_yrMax" value="%d" size=4/>
+ </td>
+""" % (int(self.defaults['ls_dayMin']), int(self.defaults['ls_moMin']), int(self.defaults['ls_yrMin']),
+       int(self.defaults['ls_dayMax']), int(self.defaults['ls_moMax']), int(self.defaults['ls_yrMax']))
+        
+        # Machine name
+        if self.defaults['machine'] is None:
+            mach = ""
+        else:
+            mach = self.defaults['machine']
+        print """
+<td>
+<input type="text" name="machine" value="%s" size=12/>
+</td>
+""" % mach
+        
+        print """
+</tr></table>
+<table border="1">
+<tr><th>Redshift<th>simulation_uuid<th>topgrid0<th>Max number of entries returned</tr>
+"""
+        # Redshift
+        print """
+<td>
+min: <input type="text" name="zMin" value="%d" size=4/><br>
+max: <input type="text" name="zMax" value="%d" size=4/><br>
+</td>
+""" % (float(self.defaults['zMin']), float(self.defaults['zMax']))
+        
+        # simulation uuid
+        if self.defaults['sim_uuid'] is None:
+            uuid = ""
+        else:
+            uuid = self.defaults['sim_uuid']
+        print """
+<td>
+<input type="text" name="sim_uuid" value="%s" size=50/>
+</td>
+""" % uuid
+        
+        # topgrid0
+        print """
+<td>
+min: <input type="text" name="topgrid0Min" value="%s" size=4/><br>
+max: <input type="text" name="topgrid0Max" value="%s" size=4/>
+</td>
+""" % (int(self.defaults['topgrid0Min']), int(self.defaults['topgrid0Max']))
+        
+        # Number of entries
+        print """
+<td>
+<input type="text" name="limit" value="%d" size=4/><br>(2500 max)
+</td>
+""" % int(self.defaults['limit'])
+        
+        # Closing up!
+        print """
+</tr>
+</table>
+</form>
+Search notes: <br>
+<ul>
+<li>For the <b>machine</b> and <b>simulation_uuid</b> fields, a
+blank field means search over all, substrings work and no wildcard
+characters are needed, and unfortunately capitalization is respected.
+</li>
+<li>Mouse-over entries with ellipses (...) to reveal the full entry
+</li>
+<li>Click on column headers to sort the table by that column.
+</li>
+</ul>
+"""
+        
+    
+    def make_link(self, name, print_out = True, order_by = None, order = None,
+            sim_uuid = None):
+        # This will make a link based on the current state of the query
+        # variables and any possible changes the user can ask for.
+        d = self.defaults.copy()
+        if order_by is not None:
+            d['order_by'] = order_by
+        if order is not None:
+            d['order'] = order
+        if sim_uuid is not None:
+            d['sim_uuid'] = sim_uuid
+        if print_out:
+            print self.make_get_link(d, name)
+        else:
+            return self.make_get_link(d, name)
+
+    def make_get_link(self, d, name):
+        link = "<a href='%s?" % url
+        for key in d:
+            if d[key] is not defaults[key]:
+                link += "%s=%s&" % (key, d[key])
+        link = link[:-1] # take of trailing ampersand
+        link += "'>%s</a>" % name
+        return link
+
+    def clear_cookie(self):
+        # We'll just re-set the cookies to default values, with no expiry,
+        # meaning it will be deleted when the browser quits.
+        cookie = Cookie.SimpleCookie()
+        cookie["cookie_s3id"] = 's3id'
+        cookie["cookie_s3id"]["domain"] = hostname
+        cookie["cookie_s3id"]["path"] = "/"
+        
+        cookie["cookie_s3secret"] = 's3secret'
+        cookie["cookie_s3secret"]["domain"] = hostname
+        cookie["cookie_s3secret"]["path"] = "/"
+        
+        print cookie.output()
+        # Now redirect back to the login page.
+        print "Status: 307 Temporary Redirect\r\nLocation: %s\r\n" % url
+
+    def login_box(self):
+        # Prints the html for the login boxes. The form submits to this
+        # self-same script.
+        print """
+<form method='post'>
+AWS Access Key: <input type='text' name='s3id' /><br />
+AWS Secret Key: <input type='password' name='s3secret' /><br />
+<input type='checkbox' name='s3cookie' value='yes' /> Persistent Cookie?<br />
+<input type='submit' value='Submit' />
+</form>
+"""
+
+    def headers(self, title):
+        # Print out the HTML header stuff.
+        print "Content-type: text/html\n"
+        print "<html><head>"
+        print "<title>%s</title>" % title
+        print """
+<STYLE TYPE="text/css">
+<!--
+TD{font-family: Courier New; font-size: 9pt;}
+TH{font-family: Courier New; font-size: 9pt;}
+--->
+</STYLE>
+<script src="/sorttable.js"></script>
+"""
+        print "</head>"
+        print "<body>"
+    
+    def footers(self):
+        # Close up the HTML.
+        print "</body>"
+        print "</html>"
+
+    def convert_date(self, day, mo, yr, day_buffer):
+        day = int(day)
+        mo = int(mo)
+        yr = int(yr)
+        return time.mktime((yr, mo, day + day_buffer, 0, 0, 0, 0, 0, 0))
+
+mydb()

File sorttable.js

+/*
+  SortTable
+  version 2
+  7th April 2007
+  Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
+  
+  Instructions:
+  Download this file
+  Add <script src="sorttable.js"></script> to your HTML
+  Add class="sortable" to any table you'd like to make sortable
+  Click on the headers to sort
+  
+  Thanks to many, many people for contributions and suggestions.
+  Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
+  This basically means: do what you want with it.
+*/
+
+ 
+var stIsIE = /*@cc_on!@*/false;
+
+sorttable = {
+  init: function() {
+    // quit if this function has already been called
+    if (arguments.callee.done) return;
+    // flag this function so we don't do the same thing twice
+    arguments.callee.done = true;
+    // kill the timer
+    if (_timer) clearInterval(_timer);
+    
+    if (!document.createElement || !document.getElementsByTagName) return;
+    
+    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
+    
+    forEach(document.getElementsByTagName('table'), function(table) {
+      if (table.className.search(/\bsortable\b/) != -1) {
+        sorttable.makeSortable(table);
+      }
+    });
+    
+  },
+  
+  makeSortable: function(table) {
+    if (table.getElementsByTagName('thead').length == 0) {
+      // table doesn't have a tHead. Since it should have, create one and
+      // put the first table row in it.
+      the = document.createElement('thead');
+      the.appendChild(table.rows[0]);
+      table.insertBefore(the,table.firstChild);
+    }
+    // Safari doesn't support table.tHead, sigh
+    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
+    
+    if (table.tHead.rows.length != 1) return; // can't cope with two header rows
+    
+    // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
+    // "total" rows, for example). This is B&R, since what you're supposed
+    // to do is put them in a tfoot. So, if there are sortbottom rows,
+    // for backwards compatibility, move them to tfoot (creating it if needed).
+    sortbottomrows = [];
+    for (var i=0; i<table.rows.length; i++) {
+      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
+        sortbottomrows[sortbottomrows.length] = table.rows[i];
+      }
+    }
+    if (sortbottomrows) {
+      if (table.tFoot == null) {
+        // table doesn't have a tfoot. Create one.
+        tfo = document.createElement('tfoot');
+        table.appendChild(tfo);
+      }
+      for (var i=0; i<sortbottomrows.length; i++) {
+        tfo.appendChild(sortbottomrows[i]);
+      }
+      delete sortbottomrows;
+    }
+    
+    // work through each column and calculate its type
+    headrow = table.tHead.rows[0].cells;
+    for (var i=0; i<headrow.length; i++) {
+      // manually override the type with a sorttable_type attribute
+      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
+        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
+        if (mtch) { override = mtch[1]; }
+	      if (mtch && typeof sorttable["sort_"+override] == 'function') {
+	        headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
+	      } else {
+	        headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
+	      }
+	      // make it clickable to sort
+	      headrow[i].sorttable_columnindex = i;
+	      headrow[i].sorttable_tbody = table.tBodies[0];
+	      dean_addEvent(headrow[i],"click", function(e) {
+
+          if (this.className.search(/\bsorttable_sorted\b/) != -1) {
+            // if we're already sorted by this column, just 
+            // reverse the table, which is quicker
+            sorttable.reverse(this.sorttable_tbody);
+            this.className = this.className.replace('sorttable_sorted',
+                                                    'sorttable_sorted_reverse');
+            this.removeChild(document.getElementById('sorttable_sortfwdind'));
+            sortrevind = document.createElement('span');
+            sortrevind.id = "sorttable_sortrevind";
+            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
+            this.appendChild(sortrevind);
+            return;
+          }
+          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
+            // if we're already sorted by this column in reverse, just 
+            // re-reverse the table, which is quicker
+            sorttable.reverse(this.sorttable_tbody);
+            this.className = this.className.replace('sorttable_sorted_reverse',
+                                                    'sorttable_sorted');
+            this.removeChild(document.getElementById('sorttable_sortrevind'));
+            sortfwdind = document.createElement('span');
+            sortfwdind.id = "sorttable_sortfwdind";
+            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
+            this.appendChild(sortfwdind);
+            return;
+          }
+          
+          // remove sorttable_sorted classes
+          theadrow = this.parentNode;
+          forEach(theadrow.childNodes, function(cell) {
+            if (cell.nodeType == 1) { // an element
+              cell.className = cell.className.replace('sorttable_sorted_reverse','');
+              cell.className = cell.className.replace('sorttable_sorted','');
+            }
+          });
+          sortfwdind = document.getElementById('sorttable_sortfwdind');
+          if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
+          sortrevind = document.getElementById('sorttable_sortrevind');
+          if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
+          
+          this.className += ' sorttable_sorted';
+          sortfwdind = document.createElement('span');
+          sortfwdind.id = "sorttable_sortfwdind";
+          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
+          this.appendChild(sortfwdind);
+
+	        // build an array to sort. This is a Schwartzian transform thing,
+	        // i.e., we "decorate" each row with the actual sort key,
+	        // sort based on the sort keys, and then put the rows back in order
+	        // which is a lot faster because you only do getInnerText once per row
+	        row_array = [];
+	        col = this.sorttable_columnindex;
+	        rows = this.sorttable_tbody.rows;
+	        for (var j=0; j<rows.length; j++) {
+	          row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
+	        }
+	        /* If you want a stable sort, uncomment the following line */
+	        //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
+	        /* and comment out this one */
+	        row_array.sort(this.sorttable_sortfunction);
+	        
+	        tb = this.sorttable_tbody;
+	        for (var j=0; j<row_array.length; j++) {
+	          tb.appendChild(row_array[j][1]);
+	        }
+	        
+	        delete row_array;
+	      });
+	    }
+    }
+  },
+  
+  guessType: function(table, column) {
+    // guess the type of a column based on its first non-blank row
+    sortfn = sorttable.sort_alpha;
+    for (var i=0; i<table.tBodies[0].rows.length; i++) {
+      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
+      if (text != '') {
+        if (text.match(/^-?[�$�]?[\d,.]+%?$/)) {
+          return sorttable.sort_numeric;
+        }
+        // check for a date: dd/mm/yyyy or dd/mm/yy 
+        // can have / or . or - as separator
+        // can be mm/dd as well
+        possdate = text.match(sorttable.DATE_RE)
+        if (possdate) {
+          // looks like a date
+          first = parseInt(possdate[1]);
+          second = parseInt(possdate[2]);
+          if (first > 12) {
+            // definitely dd/mm
+            return sorttable.sort_ddmm;
+          } else if (second > 12) {
+            return sorttable.sort_mmdd;
+          } else {
+            // looks like a date, but we can't tell which, so assume
+            // that it's dd/mm (English imperialism!) and keep looking
+            sortfn = sorttable.sort_ddmm;
+          }
+        }
+      }
+    }
+    return sortfn;
+  },
+  
+  getInnerText: function(node) {
+    // gets the text we want to use for sorting for a cell.
+    // strips leading and trailing whitespace.
+    // this is *not* a generic getInnerText function; it's special to sorttable.
+    // for example, you can override the cell text with a customkey attribute.
+    // it also gets .value for <input> fields.
+    
+    hasInputs = (typeof node.getElementsByTagName == 'function') &&
+                 node.getElementsByTagName('input').length;
+    
+    if (node.getAttribute("sorttable_customkey") != null) {
+      return node.getAttribute("sorttable_customkey");
+    }
+    else if (typeof node.textContent != 'undefined' && !hasInputs) {
+      return node.textContent.replace(/^\s+|\s+$/g, '');
+    }
+    else if (typeof node.innerText != 'undefined' && !hasInputs) {
+      return node.innerText.replace(/^\s+|\s+$/g, '');
+    }
+    else if (typeof node.text != 'undefined' && !hasInputs) {
+      return node.text.replace(/^\s+|\s+$/g, '');
+    }
+    else {
+      switch (node.nodeType) {
+        case 3:
+          if (node.nodeName.toLowerCase() == 'input') {
+            return node.value.replace(/^\s+|\s+$/g, '');
+          }
+        case 4:
+          return node.nodeValue.replace(/^\s+|\s+$/g, '');
+          break;
+        case 1:
+        case 11:
+          var innerText = '';
+          for (var i = 0; i < node.childNodes.length; i++) {
+            innerText += sorttable.getInnerText(node.childNodes[i]);
+          }
+          return innerText.replace(/^\s+|\s+$/g, '');
+          break;
+        default:
+          return '';
+      }
+    }
+  },
+  
+  reverse: function(tbody) {
+    // reverse the rows in a tbody
+    newrows = [];
+    for (var i=0; i<tbody.rows.length; i++) {
+      newrows[newrows.length] = tbody.rows[i];
+    }
+    for (var i=newrows.length-1; i>=0; i--) {
+       tbody.appendChild(newrows[i]);
+    }
+    delete newrows;
+  },
+  
+  /* sort functions
+     each sort function takes two parameters, a and b
+     you are comparing a[0] and b[0] */
+  sort_numeric: function(a,b) {
+    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
+    if (isNaN(aa)) aa = 0;
+    bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); 
+    if (isNaN(bb)) bb = 0;
+    return aa-bb;
+  },
+  sort_alpha: function(a,b) {
+    if (a[0]==b[0]) return 0;
+    if (a[0]<b[0]) return -1;
+    return 1;
+  },
+  sort_ddmm: function(a,b) {
+    mtch = a[0].match(sorttable.DATE_RE);
+    y = mtch[3]; m = mtch[2]; d = mtch[1];
+    if (m.length == 1) m = '0'+m;
+    if (d.length == 1) d = '0'+d;
+    dt1 = y+m+d;
+    mtch = b[0].match(sorttable.DATE_RE);
+    y = mtch[3]; m = mtch[2]; d = mtch[1];
+    if (m.length == 1) m = '0'+m;
+    if (d.length == 1) d = '0'+d;
+    dt2 = y+m+d;
+    if (dt1==dt2) return 0;
+    if (dt1<dt2) return -1;
+    return 1;
+  },
+  sort_mmdd: function(a,b) {
+    mtch = a[0].match(sorttable.DATE_RE);
+    y = mtch[3]; d = mtch[2]; m = mtch[1];
+    if (m.length == 1) m = '0'+m;
+    if (d.length == 1) d = '0'+d;
+    dt1 = y+m+d;
+    mtch = b[0].match(sorttable.DATE_RE);
+    y = mtch[3]; d = mtch[2]; m = mtch[1];
+    if (m.length == 1) m = '0'+m;
+    if (d.length == 1) d = '0'+d;
+    dt2 = y+m+d;
+    if (dt1==dt2) return 0;
+    if (dt1<dt2) return -1;
+    return 1;
+  },
+  
+  shaker_sort: function(list, comp_func) {
+    // A stable sort function to allow multi-level sorting of data
+    // see: http://en.wikipedia.org/wiki/Cocktail_sort
+    // thanks to Joseph Nahmias
+    var b = 0;
+    var t = list.length - 1;
+    var swap = true;
+
+    while(swap) {
+        swap = false;
+        for(var i = b; i < t; ++i) {
+            if ( comp_func(list[i], list[i+1]) > 0 ) {
+                var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
+                swap = true;
+            }
+        } // for
+        t--;
+
+        if (!swap) break;
+
+        for(var i = t; i > b; --i) {
+            if ( comp_func(list[i], list[i-1]) < 0 ) {
+                var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
+                swap = true;
+            }
+        } // for
+        b++;
+
+    } // while(swap)
+  }  
+}
+
+/* ******************************************************************
+   Supporting functions: bundled here to avoid depending on a library
+   ****************************************************************** */
+
+// Dean Edwards/Matthias Miller/John Resig
+
+/* for Mozilla/Opera9 */
+if (document.addEventListener) {
+    document.addEventListener("DOMContentLoaded", sorttable.init, false);
+}
+
+/* for Internet Explorer */
+/*@cc_on @*/
+/*@if (@_win32)
+    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
+    var script = document.getElementById("__ie_onload");
+    script.onreadystatechange = function() {
+        if (this.readyState == "complete") {
+            sorttable.init(); // call the onload handler
+        }
+    };
+/*@end @*/
+
+/* for Safari */
+if (/WebKit/i.test(navigator.userAgent)) { // sniff
+    var _timer = setInterval(function() {
+        if (/loaded|complete/.test(document.readyState)) {
+            sorttable.init(); // call the onload handler
+        }
+    }, 10);
+}
+
+/* for other browsers */
+window.onload = sorttable.init;
+
+// written by Dean Edwards, 2005
+// with input from Tino Zijdel, Matthias Miller, Diego Perini
+
+// http://dean.edwards.name/weblog/2005/10/add-event/
+
+function dean_addEvent(element, type, handler) {
+	if (element.addEventListener) {
+		element.addEventListener(type, handler, false);
+	} else {
+		// assign each event handler a unique ID
+		if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
+		// create a hash table of event types for the element
+		if (!element.events) element.events = {};
+		// create a hash table of event handlers for each element/event pair
+		var handlers = element.events[type];
+		if (!handlers) {
+			handlers = element.events[type] = {};
+			// store the existing event handler (if there is one)
+			if (element["on" + type]) {
+				handlers[0] = element["on" + type];
+			}
+		}
+		// store the event handler in the hash table
+		handlers[handler.$$guid] = handler;
+		// assign a global event handler to do all the work
+		element["on" + type] = handleEvent;
+	}
+};
+// a counter used to create unique IDs
+dean_addEvent.guid = 1;
+
+function removeEvent(element, type, handler) {
+	if (element.removeEventListener) {
+		element.removeEventListener(type, handler, false);
+	} else {
+		// delete the event handler from the hash table
+		if (element.events && element.events[type]) {
+			delete element.events[type][handler.$$guid];
+		}
+	}
+};
+
+function handleEvent(event) {
+	var returnValue = true;
+	// grab the event object (IE uses a global event object)
+	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
+	// get a reference to the hash table of event handlers
+	var handlers = this.events[event.type];
+	// execute each event handler
+	for (var i in handlers) {
+		this.$$handleEvent = handlers[i];
+		if (this.$$handleEvent(event) === false) {
+			returnValue = false;
+		}
+	}
+	return returnValue;
+};
+
+function fixEvent(event) {
+	// add W3C standard event methods
+	event.preventDefault = fixEvent.preventDefault;
+	event.stopPropagation = fixEvent.stopPropagation;
+	return event;
+};
+fixEvent.preventDefault = function() {
+	this.returnValue = false;
+};
+fixEvent.stopPropagation = function() {
+  this.cancelBubble = true;
+}
+
+// Dean's forEach: http://dean.edwards.name/base/forEach.js
+/*
+	forEach, version 1.0
+	Copyright 2006, Dean Edwards
+	License: http://www.opensource.org/licenses/mit-license.php
+*/
+
+// array-like enumeration
+if (!Array.forEach) { // mozilla already supports this
+	Array.forEach = function(array, block, context) {
+		for (var i = 0; i < array.length; i++) {
+			block.call(context, array[i], i, array);
+		}
+	};
+}
+
+// generic enumeration
+Function.prototype.forEach = function(object, block, context) {
+	for (var key in object) {
+		if (typeof this.prototype[key] == "undefined") {
+			block.call(context, object[key], key, object);
+		}
+	}
+};
+
+// character enumeration
+String.forEach = function(string, block, context) {
+	Array.forEach(string.split(""), function(chr, index) {
+		block.call(context, chr, index, string);
+	});
+};
+
+// globally resolve forEach enumeration
+var forEach = function(object, block, context) {
+	if (object) {
+		var resolve = Object; // default
+		if (object instanceof Function) {
+			// functions have a "length" property
+			resolve = Function;
+		} else if (object.forEach instanceof Function) {
+			// the object implements a custom forEach method so use that
+			object.forEach(block, context);
+			return;
+		} else if (typeof object == "string") {
+			// the object is a string
+			resolve = String;
+		} else if (typeof object.length == "number") {
+			// the object is array-like
+			resolve = Array;
+		}
+		resolve.forEach(object, block, context);
+	}
+};
+