The Activities of Benjamin Davidson

My life’s philosophies, projects and people

Skip to: Content | Sidebar | Footer

Opera vs. Firefox

9 September, 2008 (00:42) | Philosophies | By: benjamin

The Opera 9 Logo

The Opera 9 Logo

In the great browser wars that have emerged in the post-IE6 era, I have been a supporter and user of Opera since the day it became ad-free, despite having Firefox to thank not only for finally shaking up Microsoft enough to finally implement such basic features as tabs, integrated search functionality, phishing detection, pop-up blocking and support for transparent PNG images into their browser, but for making Opera free in the first place.  Here I hope to explain why.

First, let me say that I am also a fan of Firefox.  Firefox is both user-friendly and developer-friendly.  I use the amazing Web Developer Toolbar on an almost daily basis, and know many who swear by many other plugins for everything from ad-blocking to Flickr to Amazon’s Elastic Compute Cloud (EC2). In fact, I am writing this very post in Firefox, since WordPress’ dynamic image-resizing handles do not work in Opera! And I don’t just like Firefox, I have several pieces of merchandise form the Mozilla store, including official Firefox and Thunderbird CDs.

However, I still prefer Opera. Most Firefox users will boast that Firefox is lean and standards compliant, but in fact Opera is both a smaller download and has the best web standards support. This alone impresses me, but it is not what drives me to it.

First and foremost, Opera includes a powerful mail client (with threads, indexed searched, support for RSS feeds, newsgroups, etc.), built into the browser (and is still smaller than Firefox, much less Firefox and Thunderbird combined!) Secondly, Opera has more intelligent shortcuts. If you like mouse gestures (which I don’t) they’re built in (but not enabled) by default. You can still use Ctrl+Tab and Ctrl+Shift+Tab to switch between browser windows if you want, but Opera has a faster, simpler, more intuitive solution: 1 and 2. For text searches, you can press Ctrl+F if you want, or you can just press the period key. It’s these kinds of outside-the-box shortcuts that make Opera grow on you very quickly once you’ve mastered it (something that any members of the equally entertaining vi/emacs debates will be able to appreciate). Opera also now includes its “speed dial” function, which Google recently borrowed for their Chrome browser, which makes your homepage a splash page with updated previews of your nine favourite sites, which are then mapped to shortcuts Ctrl+1 through Ctrl+9 respectively. Opera also provides image previews of windows, scales entire web sites with its zoom feature (as opposed to just enlarging fonts), and does many other things right out of the box that Firefox users would have to track down extensions for. It can synchronize your settings across systems, block ads, and download torrents. Also, Opera has an extensive library of widgets of its own.

Opera’s tabs are more powerful than other browsers. Tabs can be of different sizes, allowing multiple tabs displayed side by side within the same browser window. Tabs can be dragged and dropped between browser windows (without redownloading, restarting embedded videos, etc., like Firefox does), and can even be dragged onto blank desktop space to become their own windows. It’s address bar is easily customized with handy search shortcuts; for example, I have (a)mazon, (d)ictionary, (t)hesaurus, (w)ikipedia, so that I simply type “d flippant” and I’m automatically redirected to http://dictionary.reference.com/browse/flippant. Oh, and did I mention that Opera has used less memory, rendered pages faster, and processed JavaScript more quickly than Firefox for years? Only now with Firefox 3 are the browsers showing similar performance.

Below is a screenshot I took one day, with approximately 30 tabs open in Firefox spanned over a day, vs. about 150 tabs left open in Opera over the better part of a week. You’ll see that Firefox uses 160MB of memory to Opera’s 140MB, and that Firefox is mysteriously draining 15% of my (Core 2 Duo E6600) CPU. Both sites are open to plain text/image data, no more intensive to render than most Wikipedia articles.

Opera and Firefox resource consumption

Opera and Firefox resource consumption

Zenburn Syntax Highlighting

8 September, 2008 (23:43) | Philosophies | By: benjamin

Zenburn syntax highlighting in gvim

Zenburn syntax highlighting in gvim

For those that find staring at a light bulb all day especially straining on the eyes, I heartily recommend you consider doing what very few text editors dare to do: configure a light-text-on-dark-background environment. I made the switch several months ago, and can assure you it’s not only far easier to read, but not at all unfashionable, despite what you might think. In fact several of my friends have followed suit after looking over my shoulder at the colour scheme I arranged.

Unfortunately, arranging a colour scheme can be quite tiresome.  So many languages, each with strings and characters, numbers, keywords, operators, comments, and a host of other possible distinctions worth highlighting individually.  Fortunately, most IDEs provide an easy way to make global changes, and a GUI to speed you along.  Better yet, most of the work has already been done for you: the Zenburn colour scheme was created in 2002 by Jani Nurminen, and can easily be downloaded for vim, emacs, Visual Studio and my personal favourite, Notepad++.  as well as XTerm, the KDE konsole and others.

If you haven’t heard of Notepad++, why not try them both out now?  First install Notepad++, then go to %APPDATA%\Notepad++ and replace the stylers.xml file.  Launch Notepad++ and open up C, C++, C#, Java, Perl, Python, PHP, HTML, XML, Bash or many other kinds of files and see what you think.  If you don’t care for it, simply replace the old stylers.xml file and re-launch the program!

.NET 3.x and the Windows Presentation Foundation

4 September, 2008 (09:39) | Projects | By: benjamin

The structure of components in the .NET 3.0 Framework

The structure of components in the .NET 3.0 Framework

As part of BCIT’s .NET applications class (COMP 4870), I was instructed to produce a PowerPoint lesson and corresponding lab relating to any exciting .NET-related technology of my choosing. I chose the Windows Presentation Foundation, the layout and organization foundations part of the .NET Framework 3.0+ architecture. With specific focus on the language-agnostic eXtensible Application Markup Language (XAML) used to outline the structure of a traditional desktop application in a manner similar to web applications of the last few years, I began examining this and other components of the .NET architecture. I found a powerful suite of tools all buttressing one-another with features easing and extending the possibilities of designing desktop applications, eliminating the need to recreate interfaces in the transition from Photoshop/Illustrator to a “real” application interface, and allowing a hodgepodge of programming languages all to interact seamlessly with the general XAML designations of the application, even those languages not part of the .NET framework, thanks to various third party libraries.

The .NET 3.0 structure, illustrated using .NET UI components

The .NET 3.0 structure, illustrated using new .NET UI components, including gradients and transparencies.

I have come to believe that Microsoft has done something truly powerful with the Windows Presentation Foundation. Hardware accelerated vector graphics, complemented with an extensive library of multimedia codecs for even richer content, allowed me to produce my highly visual PowerPoint lessons doing all the art directly in the Microsoft Expression Blend development environment for (and by) the WPF. Silverlight’s support for large subsets of WPF makes the applications seamlessly web-portable with only a loss of hardware acceleration (for obvious security reasons). Event-driven storyboards of application states allow for unprecedented code organization and reusability.

In short, I have been very impressed with the WPF, and encourage anyone developing bleeding-edge applications for the Windows platform to take the time to learn its fundamentals immediately.

Network Diagrams and Proposals

4 September, 2008 (09:26) | Projects | By: benjamin

A network diagram examining the levels of isolation and redundancy in the Nisgaa government network.

A network diagram examining the levels of isolation and redundancy in the Nisga'a government network.

Being an ISP closely tied to the Nisga’a Lisims Government, enTel frequently examined opportunites to expand its infrastructure in the Nass Valley, and worked with local government denominations to expand services and support in municipal government offices. It was my responsibility to review reports from several enTel employees and compile a comprehensive network analysis and proposal to the government, complete with descriptions of server hardware, usage policies, physical location enhancements, and levels of redundancy infrastructure independence between government offices. Although details of the reports can not be revealed for security reasons, I did produce multiple reports, each several pages in length, detailing current conditions and ascribing remedies to common village IT problems.

Our concepts are perhaps best summarized in this simple network diagram I produced in Visio, summarizing our proposed solution.

Servers and Services at enTel

4 September, 2008 (09:11) | Projects | By: benjamin

A brief account of my life as the jack-of-all-trades at enTel Communications, the year before attending school at BCIT.

During my approximately nine-month stay at enTel Communications, a small Internet service provider based in the village of New Aiyansh, British Columbia and spanning across the four villages of the Nisga’a Nation, I did a great deal more than simple client web development: I produced a custom user control panel, with scripts that automatically regulated user account creation across the various servers and platforms of our internal network, and assigned a collection of email accounts, web spaces and corresponding MySQL databases to each user. Disk usage quotas were enforced across all components, spam filters were applied to email accounts, and one-click deployment options were available for WordPress, Joomla!, Mambo and PhpBB content management systems on users’ web spaces. In addition, the control panel provided illustrated graphics indicating current and maximum memory consumption under a given account, and a comprehensive collection of site visitation statistics. Perhaps most importantly: the servers ran CentOS Linux, Apache, PHP and MySQL, providing a completely expense-free LAMP application framework, along with sendmail, Dovecot, SpamAssassin and SquirrelMail for email, and quota, cron, expect and BASH utilities managing server operations like user account creation, email of warning messages when quotas were reached, and propagation of accounts between the various servers. With vsFTPd providing FTP access to web spaces, not a single dollar was spent on software licenses for the entire client-side service framework at enTel.

This all said, internally enTel used Windows Server technologies, managing users across multiple domains through Active Directory and managing company email through Microsoft Exchange and BlackBerry server technologies. Though these internal (and special corporate client) services did not interface with those services I organized for enTel’s Internet service clients, I also took part in the administration of these Microsoft systems, writing custom batch scripts and automating FTP backups and retrievals, eliminating the need for thousands of dollars worth of corporate archiving software not needed in our situation. Finally, I performed the many routine user maintenance tasks associated with network administration when our primary internal services technician was not available.

I also proved to be quite adept at folding invoices, when we were ahead of schedule on technical affairs!

Drupal Tempating and Modules

4 September, 2008 (08:42) | Projects | By: benjamin

A hypothetical layout for the City of Terraces website

A hypothetical layout for the City of Terrace's website

For a portion of a self-study project in the Information Systems option at BCIT, I decided to create my vision of a new website for the City of Terrace, noting it’s extremely poor current state at http://city.terrace.bc.ca. After creating what I believe is a fairly simple but attractive XHTML/CSS layout for the site, I then integrated its contents with the highly flexible and extensible Drupal content management system. Additional work included automatic PDF generation, integrated into a Drupal plugin using its system of hooks through PHP’s conveniently integrated reflexive programming paradigm.

See my reimagining of the City of Terrace website if you need any confidence that it is relatively painless to become familiar enough with Drupal to merge your layouts with its framework. In truth you need not learn the guts of Drupal at all; you’re merely scratching the service, echoing a body here, title there, and the occasional sidebar or breadcrumbs within their designated locations. A few minor CSS tweaks corresponding to Drupal’s specific classes for some of its custom elements and you will have a very versatile template indeed.

Linear Ballistics

4 September, 2008 (08:30) | Uncategorized | By: benjamin

Robocode is an entertaining little Java application that allows you to pilot a tank across a 2D landscape, firing at competing tanks in an effort to be the last left alive. While the framework does provide hooks to accept keyboard and mouse input from a user, the program is primarily known for providing students a look into the world of AI. Pattern recognition, pathfinding, and ballistics are all key to the more advanced robots in the arena.

I found the challenge of precise predictive targeting of tanks moving in arcs to be well beyond my expertise, or at least my patience (later Googling existing methods to learn that they require applications of Calculus I had not yet heard of, much less practiced), but I was able to accurately lead shots against enemies moving linearly, after some meditation on the subject, and wanted to share my methods. Note that although it is possible to factor this into the calculation, I do avoid compensating for the time it takes my tank to turn its gun to whatever heading is necessary before firing a shot.

Each tank is equipped with a scanner that rotates extremely quickly, and triggers the onScannedRobot method upon, surprise, scanning a robot. A ScannedRobotEvent argument is supplied, containing the coordinates, speed and bearing of the enemy tank. It is this information alone that is required to determine where to aim your shot.

The Calculations

  1. Given your own coordinates and the enemy’s coordinates, you can determine the enemy’s current position relative to your own. We’ll call this value {x1, y1}.
  2. Given the speed (v1) and bearing of the enemy, we can determine his rate of movement along the X and Y plains. We’ll call them xd and yd (traditionally dx and dy, but we’re trying to be consistent with the x1, y1 convention).
  3. Thus, given any time t, we can determine the new x and y coordinates {x2, y2}, and, using the Pythagorean Theorem, determine the enemy’s distance at that location, d1.
  4. The bullet we fire will have a constant velocity, v2, multiplied by any time to give us its distance at time t, d2.
  5. Thus, we have a system of equations, which we want to solve at the point where the distances are equal, resulting in a collision if aimed at the right bearing.
  6. v2*t = sqrt((x1 + xd*t)^2 + (y1 + yd*t)^2)
  7. Expanding this equation will result in a quadratic equation solvable for time t using the quadratic formula.
  8. Plugging t back into earlier equations yields the coordinates of the enemy at the time of collision.
  9. Determine the bearing to these coordinates and fire.

Java Threading and Concurrency

4 September, 2008 (07:59) | Projects | By: benjamin

After having laboured intensively over manual thread management in a particular data mining industry project at BCIT, only to learn in even finder detail in BCIT’s Operating Systems class (COMP 4735) the following semester, I finally learned about the java.util.concurrent package released with Java 5, and fell immediately in love with it. Suddenly, it was utterly simple to manage daisy-chained producer-consumer pools of the most unpredictable kinds. A singleton factory produced thread pools mapped against every domain requested, allowing the corresponding InputStreams from the requests to be run through an Executor within a CompletionService. As InputStreams were produced, they would then be consumed by another thread pool managing translation from HTML to compliant XHTML, and subsequent parsing of XHTML files by specific parsing classes corresponding to the particular page sources. The parsers would build objects corresponding to the type of data on the page, and produce those, which were then passed on to the thread pool managing data-layer activity, storing the information on my database server. Errors were then easily distinguished between errors connecting to websites, errors parsing invalid web pages, and errors saving invalid data, and all logged accordingly (with the also useful java.util.logging package).

Following this ordeal-turned-masterpiece, I went on to write a tutorial exploring all aspects of the concurrency framework, including concurrent wrappers for members of the Java Collections Framework and the custom ConcurrentHashMap, ConcurrentLinkedQueue, and all forms of BlockingQueues. Basing my tutorial on the human mind, I extended the Callable interface with an abstract class called SubconsciousThought, tied in its constructor to a given Mind. Extending from this were various thoughts, each tied to Objects of appropriate types, returning the Object in the end only if my thoughts about them were positive. Thread pool size allowed me to control what corresponds to my ability to multitask, task Queue size controlled my memory of Objects to think about. A SynchronousQueue allowed my conscious mind to then focus on a single Object at a time, while my various SubconsciousThoughts competed to load up the next Object in my conscious mind. Multithreading applications suddenly felt natural. I was able to clearly see which calculations could be performed independently of each other, and have them synchronize and communicate smoothly, all through notifications with no unnecessary polling required.

Thus, I recommend to every Java developer that has ever so much as heard of the Runnable interface, or anyone writing any typically asynchronous events at all, to immediately familiarize themselves with with the java.util.concurrent package - it is not just complementary to your work, it is critical to it.

Following is sample code from a mulit-threaded FLV video downloader, that examines a web service which accepts a URI to a page with an embedded FLV video and returns the path to the actual FLV. Separate threadpools make requests for the direct URLs and actually download FLVs from those URLs.

CompletionService<URL> urlRetriever = new ExecutorCompletionService<URL>(Executors.newCachedThreadPool());
CompletionService<byte[]> fileDownloader = new ExecutorCompletionService<byte[]>(Executors.newCachedThreadPool());
 
//get actual FLV URLs from URIs with them embedded
List<String> uris = getURIs(args);
for (String source : uris) {
    urlRetriever.submit(new URLRetriever(source));
}
 
int failedRetrievals = 0;
//for each URL received, begin downloading contents
for (int i = 0; i < uris.size(); i++) {
    try {
        URL url = urlRetriever.take().get();
        File dest = new File("C:\\downloads\\" + i + ".flv");
        fileDownloader.submit(new FileDownloader(url, dest));
    } catch (InterruptedException e) {
        System.err.println("Interrupted during execution");
        System.exit(1);
    } catch (ExecutionException e) {
        System.err.println(e.getMessage() + " while requesting forwarded URL");
        --failedRetrievals;
    }
}

Sudoku Puzzle

4 September, 2008 (07:38) | Projects | By: benjamin

As an excellent skill-building exercise I have used for myself and in tutoring others, I have sometimes issued as a kind of assignment the task of writing a Sudoku puzzle solver. The concept behind Sudoku, for anyone that does not know, is simple: a nine-by-nine grid is provided, partially filled in from a collection of nine symbols (traditionally the numbers 1 through 9). Each row and column in the grid must be filled in so as to contain precisely one of each symbol. In addition, the nine-by-nine grid is also seen as a three-by-three grid of three-by-three grids, with each of those three-by-three grids also being composed of one of each of the nine symbols.

Producing a Sudoku solver requires extensive use of loops to iterate across unsolved tiles, tiles in the given row, column, or “box” for any given tile, etc. In addition, a two-dimensional array is expected to be the most common (and sensible) data structure to house the grid of tiles, and lists and sets will be very useful in accumulating all tiles to be searched for possible symbols, or simplified by eliminating a found symbol from their pools of possibility (assuming possibility pools are being tracked).  Naturally, file manipulation is easily applied as a method of pre-loading data into the system.

For very advanced lessons, one might consider polling a web service or parsing an existing website to retrieve auto-generated Sudoku puzzles to solve.  Puzzles featuring grids of different sizes might also be implemented, and with different character sets.  A 16×16 grid, broken into a 4×4 grid of smaller 4×4 grids, could be implemented using standard hexadecimal numerals, and in fact any Object with appropriate comparators in place.  64×64 grids using base64 character encoding can be found online for an extreme example.  Finally, puzzle solving engines have the potential to be multi-threaded.

I have personally written such a Sudoku solver as a proof of concept, complete with superficial test cases and documentation, although the implementation of the library in action is fairly limited.  Source code is available for this project.

Most of the magic to the program can summarized in the eliminate() and update() methods:

/**
 * Solve a tile by process of elimination, if possible.
 * 
 * @param tile Tile to do process of elimination upon
 * @param group Group to do process of elimination upon
 * @return whether or not operation was a success
 */
private boolean eliminate(Tile tile, Collection<Tile> group) {
    //don't check against self
    group.remove(tile);
 
    //for each option the tile could still be
    for (Object o : tile.getOptions()) {
        //look for the option as a possibility elsewhere
        boolean found = false;
 
        for (Tile other : group) {
            //if found, stop searching
            Set<Object> options = other.getOptions();
            if (options != null && options.contains(o)) {
                found = true;
                break;
            }
        }
 
        //if no other tiles in the group can be it
        if (!found) {
            //this one is it
            tile.setValue(o);
            return true;
        }
    }
    return false;
}
 
 
/**
 * Update the options for all tiles impacted by completion of given tile.
 * Update any newly solved Tiles after that.
 */
private void update(Tile tile) {
    unsolved.remove(tile);
 
    Set<Tile> pending = new HashSet<Tile>();
 
    //simplify row, col and 3x3 box
    pending.addAll(row(tile.y));
    pending.addAll(col(tile.x));
    pending.addAll(box(tile.x, tile.y));
 
    //don't simplify self!
    pending.remove(tile);
 
    //do simplifications
    for (Tile t : pending) {
        if (t.reduce(tile.getValue())) {
            update(t);
        }
    }
}

3rd Grade Chess Report

4 September, 2008 (07:00) | Projects | By: benjamin

Chess, the title page produced January of 1995

"Chess", the title page. Produced January of 1995.

I must take a moment to mention my life’s greatest achievement, produced when I was a mere eight years old, in grade 3 at Thornhill Primary School. A fifty-two page report, single spaced, covering all conceivable aspects of the game of chess, including its rules, traditional notation, strategies and history. The project was supposed to take only two weeks, but given my commitment I was allowed to take an entire month to see it through to completion.

I must thank my mother for outlining the illustrations for the project, but the actual colouring and writing is my own, my mother serving simply as editor and advisor at those stages.

I have aloways loved chess, having learned it from my father at age 4, and playing it irregularly throughout my life, peaking that same grade 3 year, when I inspired a modest classroom fad of playing the game. To this day I continue to play, and even toy with the idea of writing a chess AI from time to time.