text:
Richard Belzer Fears Humans More Than Any Animal
His portrayal of Detective John Munch on 'Law & Order' has set a few Hollywood records -- Munch is the only fictional character, played by a single actor, to appear on ten different television shows across five different networks.
On August 8 at 8PM ET/PT, Belzer will lend his talents to a very different project, narrating Animal Planet's 'The Uprising,' a 2-hour special examining fatal interactions between animals and humans.
"Humans are the most terrifying, the most cunning, the most destructive..." Belzer answers when asked what animal he fears most. Watch the video after the jump!
- Friday 06 AugustBy martbild
Hollywood liberals scare me the most.
- Friday 06 AugustBy vcrozas
Sean Penn probably wants to be Prez....actor that he is he could do that..be pres cause he can act like anything ...but a husband ....remember actors ACT duh play, pretend to be what they are not.....
- Friday 06 AugustBy Jay Love
I didn't watch Belzers little video, and I doubt I will watch his animal special on t.v. but somehow I am pretty sure his whole rant will end up being about hunting, guns, or eating animals instead of being some kind of freaky Vegan looking animal that looks like Belzer? No thanks, I want to eat meat and shot guns, go hunting and blow sh_t up if and when I want to. I don't need the Hollywood liberals telling me how to live!!
- Friday 06 AugustBy Jesse H. L.
I agree with Jay. Nothing better than killing things and watching them suffer. That's what Jesus would want us to do....ok, maybe not.
- Friday 06 AugustBy Chriss
"and shot guns, go hunting and blow sh_t up if and when I want to" How old are you? About 10?
- Friday 06 AugustBy Rich
ur a perfect virus. if a virus can talk theyd be saying how much they wish they can be like you
- Friday 06 AugustBy rocksoliddlm
freaky vegan - what in the hell does being a vegan have to do with you "thinking" they are freaks? so, I don't like the idea of aminals being transported by trucks and trains and killed at the end of the ride - that's freaky to you? um... go get a big mac and feel good about yourself...
- Saturday 07 AugustBy Diana
I would rather spend time with an animal, than to have to be around almost any human. We know where we stand with an animal, but unless I know the person well, I have little trust with anyone. Most people are cruel, and dishonest, they should take lessons from the animals.
- Friday 06 AugustBy Sin D
I agree with him 100% Long after humans are gone, after slowly killing each other off, mother earth and her real children, the animals, will replenish and go on and on and on as if we didn't even exist. Matter of time.
- Friday 06 AugustBy John
Belzer DEFINITELY fears Hulk Hogan. Does anyone remember???
- Friday 06 AugustBy Sin D
Hey Jay Love....I love animals too. Some with a leash and dog toys...some with Bar B Q sauce and a baked potato. Thats not Belzers point. He's just saying a LOT of humans suck. How can you NOT agree with that?
- Friday 06 AugustBy rocksoliddlm
I couldn't agree with him more.. we have made a mess of this world.
- Friday 06 AugustBy AndyLow Ranked Vote downVote upReport this
I love animals, too. Mostly baked, fried, grilled, BBQ'd, roasted.
- Saturday 07 August
sin d
What beautiful thought, if the animals can only survive our being here.
Jennifer Aniston
Is it Brad(ley) and Jen take 2? Jen was spotted out on the town with dreamboat ...
Paris Hilton
After Fairly Legal actress, Sarah Shahi, laid into Paris via Twitter for almost...
Kate Middleton
Kate Middleton is officially a princess. She walked the aisle in an Alexander...
Denise Richards
According to Denise, she's not sure that her estranged ex is completely sober....
Popeater Hot Topics
- This Male Model Who Is Also a PhD-Earning Math Teacher Makes Us Want to Go Back to School
- Bethenny Frankel, 44, Displays Toned Body in an Orange Bikini: See Her Vacation Pictures
- Amanda Seyfried Masters $995 Sky-High Platform Sandals Like a Pro
- Shawn Mendes: Taylor Swift 'the best person in the world'
- ?Killing Jesus' breaks rating record with 3.7 million viewers for NatGeo
- Hilary Duff explains bikini pic: I felt good
Sites We Love
- Shawn Mendes: Taylor Swift 'the best person in the world'
- ?Killing Jesus' breaks rating record with 3.7 million viewers for NatGeo
- More From Foxnews.com
- Zayn Malik Caught in the Middle of One Direction Fight with His New Record Producer
- Kevin Hart to Be Honored at MTV Movie Awards
- More From PEOPLE.com
- Britney Spears Does Some Light Reading At Son's Soccer Game After Sexy Hawaiian Vacay
- Demi Lovato Shows Off Her Hot Body -- And Her New Pooch!
- More From x17online.com


text:
Red Dwarf, Stately.js, ansi_up
Red Dwarf
Red Dwarf (GitHub: rviscomi / red-dwarf, License: MIT) by Rick Viscomi is a heat map visualisation of GitHub repository stars. It can display stars for a specific repository, so the joyent/node heat map is pretty interesting given the sheer amount of stars it has.
Florian's documentation is detailed, and the "door" example is an easy one to follow if you're confused about how the project can be used. Some simple tests have also been included, with a small HTML test harness.
I still hang out in IRC, and I still like using Mutt for email. There's something reassuring about the glare of colourful text-based interfaces that no GUI will ever replace. If you're a fellow console hacker, then you may find a use for ansi_up (License: MIT, npm: ansi_up) by Dru Nelson. It converts text with ANSI terminal colour commands into HTML, so you can take your FIGlet-powered nonsense to the web and annoy people with it there.
Dru says this project has been used "in production" since early 2012 – I wonder what it's being used for?
Brain Training Node
The other day a friend asked me about the validity of video game review scores. There was an accusation of payola against a well-known games magazine, and the gaming community was trying to work out how accurate the magazine's scores were. My programmer's brain immediately thought up ways to solve this – would a naive Bayesian classifier be sufficient to predict review scores given enough reviews?
The answer to that particular question is beyond the scope of this article. If you're interesting in statistical tests for detecting fraudulent data, then Benford's law is a better starting point.
Anyway, I couldn't help myself from writing some Bayes experiments in Node, and the result is this brief tutorial.
This tutorial introduces naive Bayes classifiers through the classifier module by Heather Arthur, and uses it to classify article text from the web through the power of scraping. It's purely educational rather than genuinely useful, but if you write something interesting based on it let me know in the comments and I'll check it out!
To complete this tutorial, the following things are required:
Completing this tutorial will teach you:
- The basics of Bayesian classification
- How to use the classifier module
- Web scraping
Getting Started
Like all Node projects, this one needs a
package.json. Nothing fancy, but enough to express the project's dependencies:
"author": "Alex R. Young"
, "name": "brain-training"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"classifier": "latest"
, "request": "latest"
, "cheerio": "latest"
, "devDependencies": {
"mocha": "latest"
"engines": {
"node": "0.8.8"
The cheerio module implements a subset of jQuery, and a small DOM model. It's a handy way to parse web pages where accuracy isn't required. If you need a more accurate DOM simulation, the popular choice is JSDOM.
Core Module
The classifier module has an extremely simple API. It can work with in-memory data, but I wanted to persist data with Redis. To centralise this so we don't have to keep redefining the Redis configuration, the classifier module can be wrapped up like this:
var classifier = require('classifier')
, bayes
bayes = new classifier.Bayesian({
backend: {
type: 'Redis'
, options: {
hostname: 'localhost'
, port: 6379
, name: 'gamescores'
module.exports = {
bayes: bayes
Now other scripts can load this file, and run
train or
classify as required. I called it
Naive Bayes Classifiers
The classifier itself implements a naive Bayes classifier. Such algorithms have been used as the core of many spam filtering solutions since the mid-1990s. Recently a book about Bayesian statistics, Think Bayes, was featured on Hacker News and garnered a lot of praise from the development community. It's a free book by Allen Downey and makes a difficult subject relatively digestible.
The spam filtering example is probably the easiest way to get started with Bayes. It works by assigning each word in an email a probability of being ham or spam. When a mail is marked as spam, each word will weighted accordingly – this process is known as training. When a new email arrives, the filter can add up the probabilities of each word, and if a certain threshold is reached then the mail will be marked as spam. This is known as classification.
What makes this type of filtering naive is that each word is considered an independent "event", but in reality the position of a word is important due to the grammatical rules of the language. Even with this arguably flawed assumption, naive classifiers perform well enough to help with a wide range of problems.
The Wikipedia page for Bayesian spam filtering goes into more detail, relating spam filtering algorithms to the formulas required to calculate probabilities.
Create a new file called
train.js as follows:
var cheerio = require('cheerio')
, request = require('request')
, bayes = require('./core').bayes
function parseReview(html) {
var $ = cheerio.load(html)
, score
, article
article = $('.copy .section p').text();
score = $('[typeof="v:Rating"] [property="v:value"]').text();
score = parseInt(score, 10);
return { score: score, article: article };
function fetch(i) {
var trained = 0;
request('http://www.eurogamer.net/ajax.php?action=frontpage&page=' + i + '&type=review', function(err, response, body) {
var $ = cheerio.load(body)
, links = []
$('.article a').each(function(i, a) {
var url;
if (a.attribs) {
url = 'http://www.eurogamer.net/' + a.attribs.href.split('#')[0];
if (links.indexOf(url) === -1) {
var left = links.length;
links.forEach(function(link) {
console.log('Fetching:', link);
request(link, function(err, response, body) {
var review = parseReview(body)
, category
if (review.score > 0 && review.score <= 5) {
category = 'bad';
} else if (review.score > 5 && review.score <= 10) {
category = 'good';
if (category) {
console.log(category + ':', review.score);
bayes.train(review.article, category);
if (left === 0) {
console.log('Trained:', trained);
This code is tailored for Eurogamer. If I wanted to write a production version, I'd separate out the scraping code from the training code. Here I just want to illustrate how to scrape and train the classifier.
parseReview function uses the cheerio module to pull out the review's paragraph tags and extract the text. This is pretty easy because cheerio automatically operates on arrays of nodes, so
$('.copy .section p').text() will return a block of text for each paragraph without any extra effort.
fetch function could be adapted to call Eurogamer's article paginator recursively, but I thought if I put that in there they'd get angry if enough readers tried it out! In this example,
fetch will download each article from the first page. I've tried to ensure unique links are requested by creating an array of links and then calling
Array.prototype.indexOf to see if the link is already in the array. It also strips out links with hash URLs, because Eurogamer includes an extra
#comments link.
Once the unique list of links has been generated, each one is downloaded. It's worth noting that I use Mikeal Rogers' request module here to simplify HTTP requests – Node's built-in HTTP client library is fine, but Mikeal's module cuts down a bit of boilerplate code. I use it in a lot of projects, from web scrapers to crawlers, and interacting with RESTful APIs.
The scraper code in
parseReview tries to pull out the score from the HTML. If a score between 0 and 5 is found, then the article is categorised as 'bad', and anything else is 'good'.
To actually classify other text, we need to find some other text and then call
bayes.classify on it. This code expects review URLs from Edge magazine. For example: Torchlight II review.
var request = require('request')
, cheerio = require('cheerio')
, bayes = require('./core').bayes
request(process.argv[2], function(err, request, body) {
if (err) {
} else {
var $ = cheerio.load(body)
, text = $('.post-page p').text()
bayes.classify(text, function(category) {
console.log('category:', category);
Again, cheerio is used to pull out article text, and then it's handed off to
bayes.classify. Notice that the call to
classify looks asynchronous – I quite like the idea of building a simple reusable asynchronous Node Bayes classifier service using Redis.
This script can be run like this:
node classify.js http://www.edge-online.com/review/liberation-maiden-review/
I've combined my interest in computer and video games with Node to attempt to use a naive Bayes classifier to determine if text about a given game is good or bad. Of course, this is a lot more subjective than the question of ham or spam, so the value is limited. However, hopefully you can see how easy the classifier module makes Bayesian statistics, and you should be able to adapt this code to work with other websites or plain text files.
Heather Arthur has also written brain, which is a neural network library. We've featured this module before on DailyJS, but as there's only three dependents on npm I thought it was worth brining it up again.
Node Roundup: MongloDB, parseq.js, node-netpbm
MongloDB (GitHub: onglo / MongloDB, License: MIT) by Christian Sullivan is a database written with JavaScript that's compatible with MongoDB's queries. It has a plugin system for persistence, and a datastore for Titanium Mobile – this effectively allows a form of MongoDB to be used within iOS and Android applications.
Monglo has a
DataStore API that can be used to persist data locally or remotely. It's based around an object that implements each CRUD operation:
var monglo = require('./index').Monglo
, db = monglo('DemoDB')
function DemoStore(){
return {
insert: function() {}
, update: function() {}
, open: function() {}
, remove: function() {}
, all: function() {}
db.use('store', new DemoStore());
parseq.js (GitHub: sutoiku / parseq, License: MIT, npm: parseq) from Sutoiku, Inc. is a flow control library for organising parallel and sequential operations. To manage asynchronous operations,
this can be passed. If several calls are made, then
this() can be passed, and the next function will receive an array that contains the results in the order they were called.
The same author also recently released jsdox, which is another JSDoc to Markdown generator.
netpbm (GitHub: punkave / node-netpbm, License: MIT, npm: netpbm) by Tom Boutell scales and converts images using the netpbm toolkit, which is a venerable set of graphics programs found on many Unix systems.
This library is a wrapper around the netpbm binaries, and takes advantage of the fact that most netpbm programs only read one row of pixels at a time into memory to keep memory usage low.
jQuery Roundup: jQuery UI 1.9.0, Delta Theme, jQuery.textFit
jQuery UI 1.9.0
jQuery UI 1.9.0 is out, which adds new widgets, API refinements, improved accessibility, and hundreds of bug fixes. The new widgets are as follows:
- Menu: A navigation menu with support for hierarchical pop-up submenus
- Spinner: A "number stepper" for input fields (rather than a rotating progress indicator)
- Tooltip: A pop-up message
There's a detailed jQuery UI 1.9 Upgrade Guide which lists deprecations. Oh, and the jQuery UI site has been refreshed as well!
Delta: jQuery UI Theme
Delta (GitHub: kiandra / Delta-jQuery-UI-Theme, License: MIT/GPL) is a jQuery UI theme by Tait Brown, who created the hugely popular Aristo port.
This theme has a metallic finish that reminds me if iOS 6, and includes light and dark variations. It's also dubbed as Retina ready – CSS3 gradients and high-resolution images have been used.
jQuery.textFit (GitHub: STRML / jquery.textFit, License: MIT) by Samuel Reed can scale text to fit its container. It also correctly detects multiline strings with break tags.
To find the best font size, a binary search is performed. The demo on jQuery.textFit's site is slowed down so you can actually see how the algorithm works, in reality it seems to run very quickly.
Vertical alignment and centred text are both supported, as are custom fonts.
Decorating Your JavaScript
The decorator pattern, also known as a wrapper, is a mechanism by which to extend the run-time behavior of an object, a process known as decorating. The pattern is often overlooked because its simplicity belies its object-oriented benefits when writing scalable code. Decorating objects is also neglected in JavaScript because the dynamic nature of the language allows developers to abuse the malleability of objects, but just because you can doesn't mean you should.
Before delving into the decorator pattern, let's examine a realistic coding problem that can be solved with other solutions. The decorator is best understood after the shortcomings of other common solutions have been explored.
The Problem
You are writing a simple archiving tool that manages the display and lifecycle of publications and their authors. An important feature is the ability to list the contributing authors, which may be a subset of all authors. The default is to show the first three authors of any publication. The initial domain model is basic:
Using plain JavaScript we implement the read-only classes as follows:
* Author constructor.
* @param String firstName
* @param String lastName
var Author = function(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
Author.prototype = {
* @return String The author's first name.
getFirstName: function() {
return this._firstName;
* @return String The author's last name.
getLastName: function() {
return this._lastName;
* @return String The representation of the Author.
toString: function() {
return this.getFirstName()+' '+this.getLastName();
* Publication constructor.
* @param String title
* @param Author[] authors
* @param int type
var Publication = function(title, authors, type) {
this._title = title;
this._authors = authors;
this._type = type;
Publication.prototype = {
* @return String The publication title.
getTitle: function() {
return this._title;
* @return Author[] All authors.
getAuthors: function() {
return this._authors;
* @return int The publication type.
getType: function() {
return this._type;
* A publication might have several authors, but we
* are only interested in the first three for a standard publication.
* @return Author[] The significant contributors.
contributingAuthors: function() {
return this._authors.slice(0, 3);
* @return String the representation of the Publication.
toString: function() {
return '['+this.getType()+'] "'+this.getTitle()+'" by '+this.contributingAuthors().join(', ');
The API is straightforward. Consider the following invocations:
var pub = new Publication('The Shining',
[new Author('Stephen', 'King')],
// rely on the default toString() to print: [horror] "The Shining" by Stephen King
// ...
var pub2 = new Publication('Design Patterns: Elements of Reusable Object-Oriented Software', [
new Author('Erich', 'Gamma'),
new Author('Richard', 'Helm'),
new Author('Ralph', 'Johnson'),
new Author('John', 'Vlissides')
], 'programming');
// prints: [programming] "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma, Richard Helm, Ralph Johnson
The design is simple and reliable…at least until the client specifies a new requirement:
In accordance with the convention for medical publications, only list the first (primary) and last (supervisor) authors if multiple authors exist.
This means that if
Publication.getType() returns "medical" we must perform special logic to list the contributing authors. All other types (e.g., horror, romance, computer, etc) will use the default behavior.
There are many solutions to satisfy the new requirement, but some have disadvantages that are not readily apparent. Let's explore a few of these and see why they are not ideal even though they are commonplace.
Overwrite Behavior
// overwrite the contributingAuthors definition
if (pub.getType() === 'medical') {
pub.contributingAuthors = function() {
var authors = this.getAuthors();
// return the first and last authors if possible
if (authors.length > 1) {
return authors.slice(0, 1).concat(authors.slice(-1));
} else {
return authors.slice(0, 1);
This, one could argue, can be the most abused feature of the language: the ability to arbitrarily overwrite properties and behavior at run-time. Now the
if/else condition must be maintained and expanded if more requirements are added to specify contributing authors. Furthermore, it is debatable whether or not
pub is still an instance of
Publication. A quick instanceof check will confirm that it is, but a class defines a set of state and behavior. In this case we have modified select instances and the calling code can no longer trust the consistency of
Publication objects.
Change the Calling Code
var listing;
if (pub.getType() === 'medical') {
var contribs = pub.getAuthors();
// return the first and last authors if possible
if (contribs.length > 1) {
contribs = contribs.slice(0, 1).concat(contribs.slice(-1));
} else {
contribs = contribs.slice(0, 1);
listing = '['+pub.getType()+'] "'+pub.getTitle()+'" by '+contribs.join(', ');
} else {
listing = pub.toString();
This solution violates encapsulation by forcing calling code to understand the internal implementation of
Publication.toString() and recreate it outside of the class. A good design should not burden calling code.
Subclass the Component
One of the most common solutions is to create a
MedicalPublication class that extends
Publication, with a
contributingAuthors() override to provide custom behavior. While this approach is arguably less flawed than the first two, it pushes the limit of clean inheritance. We should always favor composition over inheritance to avoid overreliance on the base class internals (for the developer masochists).
Subclassing also fails as a viable strategy when more than one customization might occur or when there is an unknown combination of customizations. An often cited example is a program to model a coffee shop where customers can customize their cup of coffee, thus affecting the price. A developer could create subclasses that reflect the myriad combinations such as
CoffeeWithCream and
CoffeeWithoutCreamExtraSugar that override
Coffee.getPrice(), but it is easy to see that the design will not scale.
Modify the Source Code
contributingAuthors: function() {
if (this.getType() === 'medical') {
var authors = this.getAuthors();
if (authors.length > 1) {
return authors.slice(0, 1).concat(authors.slice(-1));
} else {
return authors.slice(0, 1);
} else {
return this._authors.slice(0, 3);
This is somewhat of a hack, but in a small project where you control the source code it might suffice. A clear disadvantage is that the
if/else condition must grow with every custom behavior, making it a potential maintenance nightmare.
Another thing to note is that you should never, ever modify source code outside of your control. Even the mention of such an idea should leave a taste in your mouth worse than drinking orange juice after brushing your teeth. Doing so will inextricably couple your code to that revision of the API. The cases where this is a valid option are so few and far between that it is usually an architectural issue in the application, not in the outside code.
The Decorator
These solutions fulfill the requirement at the cost of jeopardizing maintainability and scalability. As a developer you must pick what is right for your application, but there is one more option to examine before making a decision.
I recommend using a decorator, a flexible pattern by which to extend the behavior of your existing objects. The following UML represents an abstract implementation of the pattern:
ConcreteComponent and
Decorator classes implement the same
Component interface (or extend
Component if it's a superclass). The
Decorator keeps a reference to a
Component for delegation except in the case where we "decorate" by customizing the behavior.
By adhering to the
Component contract, we are guaranteeing a consistent API and guarding against implementation internals because calling code will not and should not know if the object is a
ConcreteComponent or
Decorator. Programming to the interface is the cornerstone of good object-oriented design.
Some argue that JavaScript is not object-oriented, and while it supports prototypical inheritance instead of classical, objects are still innate to the language. The language supports polymorphism and that fact that all objects extend
Objectis sufficient to argue the language is object-oriented as well as functional.
The Implementation
Our solution will use a slight variant of the decorator pattern because JavaScript does not have some classical inheritance concepts such as interfaces or abstract classes. There are many libraries that simulate such constructs, which is beneficial for certain applications, but here we will use the languages basics.
The class
MedicalPublication and
Publication implicitly implement
PublicationIF. In this case
MedicalPublication acts as the decorator to list the first and last authors as contributors while unchanging other behavior.
Note that
MedicalPublication references
PublicationIF, and not
Publication. By referencing the interface instead of a specific implementation we can arbitrarily nest decorators within one another! (In the coffee shop problem we can create decorators such as
WithoutCream, and
ExtraSugar–these can be nested to handle any complex order.)
MedicalPublication class delegates for all standard operations and overrides
contributingAuthors() to provide the "decorated" behavior.
* MedicalPublication constructor.
* @param PublicationIF The publication to decorate.
var MedicalPublication = function(publication) {
this._publication = publication;
MedicalPublication.prototype = {
* @return String The publication title.
getTitle: function() {
return this._publication.getTitle();
* @return Author[] All authors.
getAuthors: function() {
return this._publication.getAuthors();
* @return int The publication type.
getType: function() {
return this._publication.getType();
* Returns the first and last authors if multiple authors exists.
* Otherwise, the first author is returned. This is a convention in the
* medical publication domain.
* @return Author[] The significant contributors.
contributingAuthors: function() {
var authors = this.getAuthors();
if (authors.length > 1) {
// fetch the first and last contributors
return authors.slice(0, 1).concat(authors.slice(-1));
} else {
// zero or one contributors
return authors.slice(0, 1);
* @return String the representation of the Publication.
toString: function() {
return 'Decorated - ['+this.getType()+'] "'+this.getTitle()+'" by '+this.contributingAuthors().join(', ');
* Factory method to instantiate the appropriate PublicationIF implementation.
* @param String The discriminating type on which to select an implementation.
* @param String The publication title.
* @param Author[] The publication's authors.
* @return PublicationIF The created object.
var publicationFactory = function(title, authors, type) {
if (type === 'medical') {
return new MedicalPublication(new Publication(title, authors, type));
} else {
return new Publication(type, title, authors);
By using the factory method we can safely create an instance of PublicationIF.
var title = 'Pancreatic Extracts as a Treatment for Diabetes';
var authors = [new Author('Adam', 'Thompson'),
new Author('Robert', 'Grace'),
new Author('Sarah', 'Townsend')];
var type = 'medical';
var pub = publicationFactory(title, authors, type);
// prints: Decorated - [medical] 'Pancreatic Extracts as a Treatment of Diabetes' by Adam Thompson, Sarah Townsend
In these examples we are using
toString() for brevity and debugging, but now we can create utility classes and methods to print
PublicationIF objects for application display.
Once the application is modified to expect
PublicationIF objects we can accommodate further requirements to handle what constitutes a contributing author by adding new decorators. Also, the design is now open for any
PublicationIF implementations beyond decorators to fulfill other requirements, which greatly increases the flexibility of the code.
One criticism is that the decorator must be maintained to adhere to its interface. All code, regardless of design, must be maintained to a degree, but it can be argued that maintaining a design with a clearly stated contract and pre- and post-conditions is much simpler than searching
if/else conditions for run-time state and behavior modifications. More importantly, the decorator pattern safeguards calling code written by other developers (or even yourself) by leveraging object-oriented principles.
Another criticism is that decorators must implement all operations defined by a contract to enforce a consistent API. While this can be tedious at times, there are libraries and methodologies that can be used with JavaScript's dynamic nature to expedite coding. Reflection-like invocation can be used to allay concerns when dealing with a changing API.
* Invoke the target method and rely on its pre- and post-conditions.
Decorator.prototype.someOperation = function() {
return this._decorated.someOperation.apply(this._decorated, arguments);
// ... or a helper library can automatically wrap the function
* Dynamic invocation.
* @param Class The class defining the function.
* @param String The func to execute.
* @param Object The *this* execution context.
function wrapper(klass, func, context) {
return function() {
return klass.prototype[func].apply(context, arguments);
The details are up to the developer, but even the most primitive decorator pattern is extremely powerful. The overhead and maintenance for the pattern itself is minimal, especially when compared to that of the opposing solutions.
The decorator pattern is not flashy, despite its name, nor does it give the developer bragging rights in the "Look at what I did!" department. What the decorator does do, however, is correctly encapsulate and modularize your code to make it scalable for future changes. When a new requirement states that a certain publication type must list all authors as contributors, regardless of ordinal rank, you won't fret about having to refactor hundreds of lines of code. Instead, you'll write a new decorator, drop it into the factory method, and take an extra long lunch because you've earned it.
Tutorial: Writing LispyScript Macros
Writing LispyScript Macros
Macros are a powerful feature of LispyScript. They are much more powerful than C
#define macros. While C
#define macros do string substitution, LispyScript macros are code generators.
Functions take values as arguments and return a value. Macros take code as arguments, and then return code. Understanding this difference and its ramifications is the key to writing proper macros.
Functions get evaluated at runtime. Macros get evaluated at compile time, or pre-compile time to be more precise.
So, when should macros be used? When you cannot use a function! There is more to this answer than what is apparent. Consider this piece of code:
(* 2 2)
And elsewhere in the program we find this.
(* 4 4)
There is a pattern emerging here. In both cases we have the same code
*, and a variable – a number that changes in each instance of the pattern. So we reuse this pattern by writing a function:
(var square
(function (x)
(* x x)))
Therefore, to reuse a repeating code pattern as a function, the code pattern must meet two conditions:
- The code must remain the same across every instance of the code pattern.
- It is only the data that can change across every instance of the code pattern.
Using functions to reuse repeated code patterns has its limitations. You cannot use a function if it is the code part that changes in a repeated code pattern.
Consider the two functions below (str is an expression that adds up given strings):
(var greet
(function (username)
(str "Welcome " username)))
(var link
(function (href text)
(str "<a href=\"" href "\">" text "</a>")))
There is a repeating code pattern here. Given below is the pattern with the parts that change in capitals:
(var NAME
(function ARGUMENTS
(str TEMPLATE_STRINGS)))
We cannot use a function to reuse this code pattern, because the parts that change are parts of the code.
Functions are about reusing code patterns, where it is only the data that changes.
Macros are about reusing code patterns, where the code can also change.
In LispyScript, we can write a macro to reuse this code pattern. The macro needs a name, let's call it
template as it happens to be a template compiler:
(macro template (name arguments rest...)
(var ~name
(function ~arguments
(str ~rest...))))
Now compare this with the meta code pattern in the previous example. The arguments to this macro are the parts of the code that change –
TEMPLATE_STRINGS – these correspond to
rest.. in the macro definition.
Arguments can be dereferenced in the generated code by adding a
~ to the argument name.
rest... is a special argument that represents the rest of the arguments to the macro after the named arguments.
This macro can be used by making a call to
(template link (href text) "<a href=\"" href "\">" text "</a>")
This code will expand as follows:
(var link
(function (href text)
(str "<a href=\"" href "\">" text "</a>")))
This expansion happens just before the expanded code is compiled. This is known as the macro expansion phase of the compiler.
Now let's try another example. We will write a benchmark macro, which benchmarks a line of code. But first we'll write a benchmark function to get a couple of related issues out of the way.
(var benchmark
(function ()
(var start (new Date))
(+ 1 1)
(var end (new Date))
(console.log (- end start))))
This is not an example that always works. Because JavaScript can only resolve time up to milliseconds, but to benchmark an integer
+ operation we need a resolution down to nanoseconds.
Furthermore, the function does not scale. We need to benchmark various operations and expressions, and since this involves changes to the above code we need to write a macro. In the macro we print the result of the operation along with the elapsed time:
(macro benchmark (code)
(var start (new Date))
(var result ~code)
(var end (new Date))
(console.log "Result: %d, Elapsed: %d" result (- end start)))
It can be used like this:
(var a 1)
(var b 2)
(benchmark (+ a b))
The result printed to the console should look like the following:
Result: 3, Elapsed: 0
Elapsed is
0 due to the millisecond resolution, but the example seems to run correctly… until one day someone attempts to do this:
(var start 1)
(var b 2)
(benchmark (+ start b))
Running this gives confusing results:
Result: NaN, Elapsed: 1
The result is
NaN, so something has gone wrong since
3 was expected. To figure out what's going on, let's look at the macro expansion:
(var start 1)
(var b 2)
(var start (new Date))
(var result (+ start b))
(var end (new Date))
(console.log "Result: %d, Elapsed: %d" result (- end start))
The user has created a variable
start. It so happens that the macro also creates a variable called
start. The macro argument
code gets dereferenced in the new scope. When
(+ start b) got executed the
start variable used was the
start Date variable created in the macro code. This problem is known as variable capture.
When writing macros, you have to be very careful when creating a variable inside a macro. In our
template macro example we were not concerned about this problem, because the
template macro does not create its own variables.
In LispyScript we get around this problem by following two rules which are specified in the "guidelines" section of the document:
- When writing a LispyScript program, creating a variable name that starts with three underscores is NOT allowed, for example:
- When writing a macro you MUST start a variable name with three underscores if you want to avoid variable capture. There are cases where you want variable capture to happen, in which case you do not need to use the three underscores. For example, when you want the passed code to use a variable defined in the macro.
The benchmark macro should be refactored using three underscores:
(macro benchmark (code)
(var ___start (new Date))
(var ___result ~code)
(var ___end (new Date))
(console.log "Result: %d, Elapsed: %d" ___result (- ___end ___start)))
Macros are a very powerful feature of LispyScript. It allows you to do some nifty programming, which is otherwise not possible with functions. At the same time we have to be very careful when using macros. Following the LispyScript macro guidelines will ensure your macros behave as expected.
Enyo Tutorial: Part 2
In my introduction to Enyo, I promised that Enyo is "very modularized, reusable, and encapsulated". Today we'll create a reusable component from our monolithic and minimalistic application by refactoring the tip calculator. Afterwards we will style the application to make it ready for app stores and the web.
As mentioned in the previous part of the tutorial, the Enyo style guide suggests using double quotes instead of single quotes. Enyo also uses tabs for indentation. Although I prefer two spaces and single quotes, I will follow these rules during this tutorial.
This tutorial builds on the previous part, which is available here:
- Part 1: Introduction and first prototype, source code commit: 4f6eb
Loading Mechanism
Enyo is using files called
package.js to load dependencies. If you look into the folder
source/, which contains the core of the application, then you'll find a file named
package.js from the bootplate project. Everything in this file will be loaded when the application starts up. Let's create a file called with the filename
calc.percent.js, and add
calc.percent.js to the end of the
Component objects are using events to communicate with their parent kinds. As described in the first part, components can nest other components. It would be nice to split the app into a reusable percent-calculator kind which could be used in other projects.
Published Properties
calc.percent.js file should look like the following example – I'll explain it in detail below.
name: 'PercentCalculator',
kind: enyo.Component,
published: {
sum: 0, //optional default values
percent: 0
events: {
onCalculated: ''
create: function() {
calculate: function() {
var result;
result = (this.sum * this.percent) / 100;
this.doCalculated({percentValue: result});
Like the previous kind, this component has a name:
PercentCalculator. This time the kind is not a control - we have chosen a component with
kind: enyo.Component.
The next lines are the published properties of our kind. They can – but must not – have a default value, and it's
0 in this example. Enyo automatically creates setters and getters for our exposed properties. We will use the setters from that pair later but in this file we access them with
this.sum and
I mentioned previously that components are communicating with events. This example registers
onCalculated, which is exposed to the public. It can be triggered with
this.doCalculated({percentValue: result}); in the
calculate method. The results are communicated to the parent kind.
Refactoring and Integration
In order to use our kind we have to add the component to our first kind from the file
{ kind: "PercentCalculator", name: "percentCalculator", onCalculated: "updateControls" }
Every time the event
calculated is fired the method
updateControls is called. This method is just getting the value and setting the new value of the corresponding DOM node. Here is the snippet:
updateControls: function(inSource, inEvent) {
return true; // stop bubbling
Notice the result is available as a property of the second argument:
The app, however, is not working yet. We have to give the values from the input fields to the component so it's able to calculate and pass back the result. I deleted the old
calculate method and introduced the method
calculateWithComponent. Also, please don't forget to update the
ontap handler of the button. Here is the method:
calculateWithComponent: function(inSource, inEvent) {
var sum = this.$.sumControl.hasNode().value;
var percent = this.$.percentControl.hasNode().value;
As before, the kind is accessed with
this.$ and its name. The automatically generated setters are used for the published properties, and afterwards
calculate can be called on our kind. At this point the component is passing the calculated result back. There are also
change-Handler available for changing properties, but we do not use them here.
Here is the updated kind in full:
name: "App",
kind: enyo.Control,
style: "",
classes: "onyx",
components: [
{kind: "onyx.InputDecorator", components: [
{kind: "onyx.Input", name: "sumControl", placeholder: "Enter sum"}
{kind: "onyx.InputDecorator", components: [
{kind: "onyx.Input", name: "percentControl", placeholder: "Enter percent"}
{kind: "onyx.Button", content: "Calculate tip", ontap: "calculateWithComponent"},
{tag: "div", name: "tipAmount"},
{kind: "PercentCalculator", name: "percentCalculator", onCalculated: "updateControls"}
create: function() {
updateControls: function(inSource, inEvent) {
return true; // stop bubbling
calculateWithComponent: function(inSource, inEvent) {
var sum = this.$.sumControl.hasNode().value;
var percent = this.$.percentControl.hasNode().value;
The commit is 8f931.
I reduced the styles in the
App.css to a simple
background-color: #c6c6c6;, and one CSS class:
.center {
text-align: center;
Then I changed the kind in our
App.js from the basic
enyo.Control to the kind
enyo.FittableRows. A basic control was a nice choice to show you the basics of Enyo and kinds, but we want to use a more complex one which is provided by the framework.
In commit 8bb19 I've added an
onyx.Toolbar as the first child of the components block:
{kind: "onyx.Toolbar", class: "center", content: 'Tip calculator'},
This will display a bar across the top of the screen (or page), in a similar fashion to the
UINavigationBar used in iOS applications. The end result looks something like this:
Production Build
You can run
deploy.sh in the
tools/ folder to start a deploy. It will minify and merge the source files of the project. The result will be saved to
deploy/, and can be used with Cordova or simply uploaded to a web server.
You should now have learned the core concepts of Enyo and built a small application. Here is a short summary:
- Concept of kinds
- Controls, and how to use and when
- Events
- Getters and setters
- Constructors and destructors
- Components
- Loading mechanism
- Published properties
- More on getters and setters
- Production builds
Node Roundup: otr, matches.js, mariasql
Off-the Record Messaging Protocol
otr (License: LGPL, npm: otr) by Arlo Breault is an implementation of an Off-the Record Messaging Protocol:
Off-the-Record Messaging, commonly referred to as OTR, is a cryptographic protocol that provides strong encryption for instant messaging conversations. OTR uses a combination of the AES symmetric-key algorithm, the Diffie–Hellman key exchange, and the SHA-1 hash function. In addition to authentication and encryption, OTR provides perfect forward secrecy and malleable encryption.
It's designed to be used in browsers, but can also be used with Node. The readme has details on how to get started with otr, and the author notes that the project has been used by Cryptocat.
matches.js (License: MIT, npm: matches) by Nathan Faubion is a pattern matching shorthand library that can create new objects with a convenient wrapper:
var myfn = pattern({
// Null
'null' : function () {...},
// Undefined
'undefined' : function () {...},
// Numbers
'42' : function () { ... },
'12.6' : function () { ... },
'1e+42' : function () { ... },
// Strings
'"foo"' : function () { ... },
// Escape sequences must be double escaped.
'"This string \\n matches \\n newlines."' : function () { ... }
The author has used this library to create adt.js, which is a library for making pseudo-algebraic types and immutable structures:
… I say pseudo because it just generates classes with boilerplate that make them look and work like types in functional languages like Haskell or Scala. It works in the browser or on the server.
mariasql (License: MIT, npm: mariasql) by Brian White is a high performance, single-threaded, asynchronous, cross-platform MySQL driver. It's based on libmariadbclient, and the author notes that it works more like a typical Node module:
This module strives to keep with the "node way" by never buffering incoming rows. Also, to keep things simple, all column values are returned as strings (except MySQL NULLs are casted to JavaScript nulls).
Brian has posted benchmarks that compare various SQL operations across several client libraries, including C and PHP-based samples: MySQL client library benchmarks.
jQuery Roundup: jQuery UI 1.8.24, HTML5 Google Authenticator, pXY.js
jQuery UI 1.8.24
jQuery UI 1.8.24 is out, which is a maintenance release:
This update brings bug fixes for Datepicker, Draggable, Droppable and Sortable, as well as adding support for jQuery 1.8.2. This is likely to be the last release in the 1.8 family; you can expect 1.9.0 very soon. For the full list of changes, see the changelog.
The jQuery UI 1.9 release candidates have been around for a while now. Check out the 1.9 RC tags on GitHub for more.
HTML5 Google Authenticator
I use Google Authenticator, which is a two-step verification implementation. Google have released corresponding mobile apps which support multiple credentials. This means third-party services can plug into Google Authenticator, so users only need one app to manage all of their credentials. This works because Google Authenticator is built on open standards, and uses the Time-based One-time Password algorithm.
The TOPT algorithm has already been implemented in JavaScript back in 2011 by Russ Sayers:
Turns out the algorithm used to generate the OTPs is an open standard. When you set-up an account in the smartphone app you are storing a key that's used to create a HMAC of the current time.
This has now been ported to a polished HTML5 Google Authenticator project, built with jQuery Mobile by Gerard Braad. He's also deployed a demo version at gauth.apps.gbraad.nl.
Cryptography and security in client-side code will always be a tricky subject, but hopefully this kind of project will help demystify two-factor authentication and encourage more web application authors to offer it to those of us who are interested in it.
pXY.js (GitHub: leeoniya / pXY.js, License: MIT) by Leon Sorokin is an API for analysing the pixels in a
Canvas elements. The author suggests using it as an algorithm visualisation tool for problems relating to OCR segmentation and document feature extraction.
The documentation has runnable examples of the major API features. For example, the Scanning pXY documentation shows how images can be scanned using the eight possible bidirectional scan patterns.
JavaScript for Node Part 1: Enumeration
JavaScript developers have been accustomed to a very scattered and incoherent API (the DOM) for some time. As a result, some of JavaScript's most common patterns are pretty weird and unnecessary when programming for a unified and coherent API like Node. It can be easy to forget that the entire ES5 specification is available to you, but there are some standard patterns that deserve to be rethought because of ES5's newer features.
Objects in ES5
Since no object in JavaScript can have identical same-tier keys, all objects can be thought of as being hash tables. Indeed, V8 implements a hash function for object keys. This important concept did not go unnoticed in the ES5 draft and so the method
Object.keys was created to extract the internal associative array of any object and return it as a JavaScript Array. In layman's terms, this means that
Object.keys returns only the keys that belong to that object and NOT any properties that it may have inherited. This is a powerful and useful construct that can be utilized in Node when enumerating over an object.
The Old Way
Chances are you have run into the following looping pattern:
var key;
for (key in obj) {
if (obj.hasOwnProperty(key))
This was the only way to traverse an object in ES3 without going up an object's prototype chain.
A Better Way
In ES5 there is a better approach. Given that we can simply get the keys of an object and put them into an array, we can loop over an object, but only at the cost of looping over an array. First consider the following:
var keys = Object.keys(obj), i, l;
for (i = 0, l = keys.length; i < l; i++)
This is usually the fastest way of looping over an object in ES5 (at least in V8). However, this method has some drawbacks. If new variables are needed to make calculations, this approach starts to feel overly verbose. Consider the following:
function calculateAngularDistanceOfObject(obj) {
if (typeof obj !== 'object') return;
var keys = Object.keys(obj),
, RADIAN_CONST = Math.PI / 180
, deltaLat
, deltLng
, halfTheSquareChord
, angularDistanceRad
, temp
, a, b, i, l
for (i = 0, l = keys.length; i < l; i++) {
temp = obj[keys[i]];
a = temp.a;
b = temp.b;
deltaLat = a.subLat(b) * RADIAN_CONST;
deltaLng = a.subLng(b) * RADIAN_CONST;
halfTheSquareChord = Math.pow(Math.sin(deltaLat / 2), 2) + Math.pow(Math.sin(deltaLng / 2), 2) * Math.cos(a.lat * RADIAN_CONST) * Math.cos(b.lat * RADIAN_CONST);
obj[keys[i]].angularDistance = 2 * Math.atan2(Math.sqrt(halfTheSquareChord), Math.sqrt(1 - halfTheSquareChord));
An Even Better Way
In situations like this, instead of looping over the array of keys using Array's native
forEach method will allow us to create a new scope for the variables we are working with. This will allow us to do our processing in a more encapsulated manner:
function calculateAngularDistanceOfObject(obj) {
if (typeof obj !== 'object') return;
var EARTH_RADIUS = 3959
, RADIAN_CONST = Math.PI / 180;
Object.keys(obj).forEach(function(key) {
var temp = obj[key]
, a = temp.a
, b = temp.b
, deltaLat = a.subLat(b) * RADIAN_CONST
, deltaLng = a.subLng(b) * RADIAN_CONST;
halfTheSquareChord = Math.pow(Math.sin(deltaLat / 2), 2) + Math.pow(Math.sin(deltaLng / 2), 2) * Math.cos(a.lat * RADIAN_CONST) * Math.cos(b.lat * RADIAN_CONST);
obj[key].angularDistance = 2 * Math.atan2(Math.sqrt(halfTheSquareChord), Math.sqrt(1 - halfTheSquareChord));
Choosing the right pattern depends on balancing maintainability with performance. Of the two patterns,
forEach is generally considered more readable. In general, iterating over large arrays will generally perform worse with
forEach (although better than the old ES3 way), but it's important to correctly benchmark code before making a decision.
One popular solution for Node is node-bench (npm: bench) written by Isaac Schlueter. After installing it here is something to start with:
var bench = require('bench')
, obj = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 };
// This is to simulate the object having non-enumerable properties
Object.defineProperty(obj, 'z', { value: 26, enumerable: false });
exports.compare = {
'old way': function() {
for (var name in obj) {
if (obj.hasOwnProperty(name))
'loop array': function() {
var keys = Object.keys(obj)
, i
, l;
for (i = 0, l = keys.length; i < l; i++)
'foreach loop': function() {
Object.keys(obj).forEach(function(key) {
// This is number of iterations on each test we want to run
bench.COMPARE_COUNT = 8;
XLSX.js, Tres, ChromaNope
XLSX.js (GitHub: stephen-hardy / xlsx.js, License: Microsoft Office Extensible File License) by Stephen Hardy can read and write Excel-compatible XLSX files. It converts base64 strings into object representations of XLSX spreadsheets, without using ActiveX.
It's built using JSZip, and will generate
data: URIs with a base64 encoded string that contains the spreadsheet's XML.
Tres (GitHub: juliocesar / tres, License: MIT) by Julio Cesar Ody is a mobile framework based on Backbone.js. It provides some convenience classes for working with touch-based gestures and the wide variety of mobile device resolutions, and enough CSS and icons to jump-start development.
Like Backbone.js, Tres has its roots in Rails, so initial versions aim to provide interfaces that work well with Ruby-based projects. This includes console-based tools for generating stub files.
ChromaNope by Kris Hedges is a web service designed to illustrate the effects of various forms of colour blindness. It uses Node and PhantomJS to render any web page against the equivalent protanope, deuteranope, and tritanope version. Definitions of these terms can be found on the Wikipedia Color blindness page.
The Truth About Event Loops
Sponsored Content This post is about a commercial product that we think will appeal to DailyJS readers.
The Truth About Event Loops is an online masterclass by Marc-André Cournoyer, the creator of the Thin web server used by Apple, CloudFoundry, and Heroku. Each class is limited to 25 people, and includes eight hours of content, downloadable recordings, cheatsheets, exercises, reusable source code, and a copy of Create Your Programming Language. The class is priced at $529 CAD, but there are early bird tickets for $479 CAD which is around $488 USD.
Classes last for two days, and the next will be held on October 23rd and 24th at 9AM-1PM ET – keep in mind the time zone if you're booking from outside Canada!
By taking part in this class, you'll learn the following:
- Guidelines for evented I/O
- Why and when asynchronous I/O is faster
- How an event loop works, by building one from scratch
- The system calls at the core of every server
- How to write the fastest network applications around
- Ways to use your machine's resources to the maximum
The aim is to allow you to finally master your web stack from top to bottom!
To give us a taste of the class, Marc has written a tutorial all about the Node event loop.
The Heart of the Node Event Loop
I am a big believer in mastering your tools to become a better developer. And the best way to master your tools is to understand how they are made.
Do you know what's happening inside Node?
There's an event loop. So there must be a loop somewhere, right? A loop handling events. Let's take a look…
The Loop
Event loops like the one in Node are designed to react to I/O events. This could be an incoming connection, data arriving on a socket, etc. What's more, it must react to these events extremely quickly. Like most things in software, the simplest design is usually the fastest. And event loops are usually very simple.
First, it consists of an endless loop:
while (true) {
Everything will happen in that loop. All of your Node programs will be running inside that loop. Which is similar to the loop you'll find in virtual machines and emulators, where an actual processor is simulated instead.
A Turn in the Loop
Somewhere in the loop, your process will wait for I/O events to happen. Luckily, most operating systems come with a function that allows us to do just that. Several options exist, such as
kqueue on Mac OS,
epoll on Linux. The most portable (but slowest) one is
select. For more on this, see select (2).
select watches a bunch of I/O objects (files, sockets) and lets you know when something happens. It looks something like this:
while (true) { // That's our loop
events = select(<I/O objects to watch>)
At this point in the loop, we know an event has occurred. We must react to those events. In Node and many other event-based systems, this is done via callbacks.
In your Node program, you'll define callbacks like so:
object.on('read', function() { ... })
This will register the callback inside the event loop, so that it knows what to do when this event happens. Introducing that in our loop, we'll end up with the following:
while (true) {
var events = select(<I/O objects to watch>)
events.forEach(function(event) {
var callback = findCallbackForEvent(event)
callback() // This calls the callback function
After we're done executing all of the callbacks, we're ready for another turn in the loop – it'll patiently wait for other I/O events to happen.
But There's More!
This is a simplification of how things work internally. However, even if the Node event loop is a little more complex than that, the structure is the same. It's still a loop using
select (or a variation), and triggering callbacks.
If you'd like to dive deeper into event loops and how it works in Node, and how other features such as
setTimeout are implemented, then join the next edition of my online class.
Everything is online. You can ask questions. You'll get exercises. And you'll also get recordings of the class to watch again at your leisure.
The class already helped a number of developers master Node. Here's what one of them had to say:
- Tom Buchok
The class was paced excellently. Overall, this subject matter is complicated — but Marc walks through the material step-by-step and it's straightforward to follow along. I've learned a great deal about how Evented I/O systems work, how they're built and when they might be most appropriate (as well as when they're not!)
The previous edition was such a great success, it sold out in just a few days. So if you're interested, book now!
Node Roundup: 0.8.10-11, Cabinet, Node Si
Node 0.8 releases are still coming thick and fast, with the release of 0.8.10 this week. On average the 0.8 branch has seen approximately 9 days between releases, with an extended summer holiday period of 20 days in August and September.
This version has a few
fs fixes by Ben Noordhuis, although he's already cited an issue in fs.stat() so he's recommending holding off for 0.8.11 which should be released later this week.
Cabinet (License: MIT, npm: cabinet) by Manuel Astudillo is an alternative to Connect's static middleware. The changes from TJ's original module are as follows:
- Memory-based cache, based on fs.watch
- Automatic asset compilation and minification
- gzip
- Support for "virtual" files, including cache manifests
The API is compatible with Connect and Express middleware, but there are additional options:
app.use(cabinet(__dirname + '/static', {
coffee: true,
gzip: true,
less: {
// Specify search paths for @import directives
paths: ['.',__dirname + '/static/stylesheets']
cache: { maxSize: 1024, maxObjects:256 }
The project comes with Mocha tests, and additional options are documented in the readme file.
Node Si
Node Si (License: MIT, npm: si) by Michał Czapracki is a binary prefix number parser and formatter module. It can be used to format numbers like
10000000 as
10M, or
10gb as
It's currently a simple module, but the author plans on adding IEC compliant binary multipliers like 'MiB', case sensitive formats, and fractional SI multipliers.
jQuery Roundup: 1.8.2, jQuery UK, JavaScript Conference 2012
jQuery 1.8.2
jQuery 1.8.2 is out, and new users of the 1.8 line are advised to read the jQuery Blog posts for 1.8 and 1.8.1 before upgrading. This version adds a lot of fixes to the selector engine's pseudo class handling, including
:not, and
jQuery UK
jQuery UK 2013 has been announced for the 19th of April in Oxford. Early bird ticket will be £160, but there are also 'blind bird' tickets available for £130.
To apply to speak at the conference, complete the proposal form. Speakers can also be suggested by the community: jQuery 2013 - Suggested Speakers.
JavaScript Conference 2012
While we're on the topic of conferences, JavaScript Conference 2012 takes place on the 15th and 16th of October 2012 in Düsseldorf. There are several tiers of tickets available, and the main conference ticket costs €590.
There's a talk on jQuery Mobile and a few on Sencha's various technologies. I also noticed a Backbone.js talk, and one on Node as well. The speakers page has details on all of the talks and workshops.
Linking the Hash Map
The Hashmap
The hash map is a classic and indispensable data structure in application programming. It is so ubiquitous that almost every modern language supports it either with a library, or by baking the functionality into the syntax itself. Hash maps are often implemented as an associative array.
A hash map provides constant-time access to a value via a unique key. The most common methodology in JavaScript is to use an object literal as a hash map.
var map = {};
// dot notation
map.foo = "bar";
console.log(map.foo); // "bar"
// bracket notation
map["foo"] = "bar";
console.log(map["foo"]); // "bar"
// mix and match
map.foo = "bar";
console.log(map["foo"]); // "bar"
In this example, the string
"bar" is the value assigned to the object property
foo. Notice that treating an object literal like a hash map is the same syntax as normal property access and manipulation; we can leverage the language itself as a data structure. Because there isn't native hash code support in JavaScript, the
Object.prototype.toString() method is invoked on the key to create the property name.
var map = {};
map[1] = "one";
console.log(map[1] === "one"); // true
console.log(map["1"] === "one"); // true
console.log(map[(1).toString()] === "one"); // true
While object literals suffice for basic hash map uses like caching, there are many operations that require boilerplate code such as listing all values in a hash map:
var map = {};
map["key1"] = "one";
map["key2"] = "two";
map["key3"] = "three";
// get all values
var values = [];
for (var key in map) {
if (map.hasOwnProperty(key)) {
// the key order is not guaranteed with a basic hash map
// and each browser might have different implementations
console.log(values.join(',')); // "two,three,one"
To rescue ourselves from reinventing the wheel, it is advisable to use a hash map class that encapsulates the behavior. The details of implementation is beyond the scope of this article, but there are many open-source libraries and articles that are worth perusing for details. For this article, we will use the following rudimentary hash map class:
* Simple hash map class.
var HashMap = function() {
this._size = 0;
this._map = {};
HashMap.prototype = {
* Puts the key/value pair into the map, overwriting
* any existing entry.
put: function(key, value) {
if (!this.containsKey(key)) {
this._map[key] = value;
* Removes the entry associated with the key
* and returns the removed value.
remove: function(key) {
if (this.containsKey(key)) {
var value = this._map[key];
delete this._map[key];
return value;
} else {
return null;
* Checks if this map contains the given key.
containsKey: function(key) {
return this._map.hasOwnProperty(key);
* Checks if this map contains the given value.
* Note that values are not required to be unique.
containsValue: function(value) {
for (var key in this._map) {
if (this._map.hasOwnProperty(key)) {
if (this._map[key] === value) {
return true;
return false;
* Returns the value associated with the given key.
get: function(key) {
return this.containsKey(key) ? this._map[key] : null;
* Clears all entries from the map.
clear: function() {
this._size = 0;
this._map = {};
* Returns an array of all keys in the map.
keys: function() {
var keys = [];
for (var key in this._map) {
if (this._map.hasOwnProperty(key)) {
return keys;
* Returns an array of all values in the map.
values: function() {
var values = [];
for (var key in this._map) {
if (this._map.hasOwnProperty(key)) {
return values;
* Returns the size of the map, which is
* the number of keys.
size: function() {
return this._size;
HashMap class lacks advanced features, but it is simple, effective, and library-agnostic.
Insertion Order
Even a robust and well tested hash map has one shortcoming if it relies on an object literal backbone: the return order of
HashMap.keys() or
HashMap.values() is unpredictable, meaning insertion order is not preserved. The overhead of tracking insertion order is why most hash map implementations ignore such a requirement and do not guarantee return order.
Although insertion order seems trivial, there are many cases in which it is critical to use hash maps for constant time access while also tracking when key/value pairs were inserted into the map. For example, a user interface library might allow a developer to add widgets to a dashboard.
Widget objects are added to a
Dashboard, and when a
Dashboard is rendered, so too are all of its
Widget children in a predictable order. This is to avoid having a dashboard's widgets randomly allocated to different layout slots per render.
var dashboard = new Dashboard();
dashboard.add(new Calendar("myCalendar"));
dashboard.add(new StockTicker("myStockTicker"));
dashboard.add(new Twitter("myTwitter"));
// modify the Calendar before rendering
var calendar = dashboard.getWidget("myCalendar");
// render the dashboard and its widgets in order: Calendar, StockTicker, Twitter
We access the
Calendar object–and other
Widget objects–by its unique id, with
Dashboard.getWidget() internally delegating to a private hash map. This introduces an implementation problem: we want to preserve the widget insertion order but give the developer constant time access to its
Widget children. A common solution is to maintain two data structures within the
Dashboard by synchronizing a hash map for access and an
Array for order.
The code to ensure consistency and integrity between the two structures is non-trivial and not reusable, hence it is not ideal. Another solution is to abandon the hash map and rely solely on an
Array, but this will slow
Widget access time to a crawling O(n), which is also unacceptable.
Enter the linked hash map.
A linked hash map is a specialized hash map that is synchronized with a doubly linked list. We can merge these two data structures into a new class called
LinkedHashMap, which allows constant time access backed by a doubly linked list to preserve insertion order. There is minimal overhead to synchronize the two structures when performing write operations on the core hash map. By extending the
HashMap class we can add an optimized doubly linked list to track the keys. (If the hash map cannot be subclassed then consider decorating it or rolling your own if there are application-specific or critical optimization requirements.)
* Constructor that initializes the parent HashMap
* and the doubly linked list head and tail.
var LinkedHashMap = function() {
// invoke super constructor
HashMap.apply(this, arguments);
// "inner" Entry class
this._Entry = function(value) {
this.prev = null;
this.next = null;
this.value = value;
// doubly linkedlist instance variables
this._head = this._tail = null;
// extend HashMap and overwrite the necessary functions
var temp = function() {};
temp.prototype = HashMap.prototype;
LinkedHashMap.prototype = new temp();
* Puts the key/value pair in the HashMap and records
* the insertion record if it does not exist.
* @override HashMap.put()
LinkedHashMap.prototype.put = function(key, value) {
var entry = new this._Entry(key);
if (!this.containsKey(key)) {
if (this.size() === 0) {
this._head = entry;
this._tail = entry;
} else {
this._tail.next = entry;
entry.prev = this._tail;
this._tail = entry;
* EDIT: Added optimization suggested
* by Chad Walker (see article comments).
// overwrite the value with an optimized Object wrapper
value = {value:value, entry:entry};
HashMap.prototype.put.call(this, key, value);
* Returns the value associated with the key.
* @override HashMap.get()
LinkedHashMap.prototype.get = function(key){
var value = HashMap.prototype.get.call(this, key);
* EDIT: Added optimization suggested
* by Chad Walker (see article comments).
// we must unwrap the value
return value != null ? value.value : null;
* Removes the key/value pair from the map and
* the key from the insertion order.
* @override Hashmap.remove()
LinkedHashMap.prototype.remove = function(key) {
* EDIT: Added optimization suggested
* by Chad Walker (see article comments).
var value = HashMap.prototype.remove.apply(this, arguments);
if (value != null) {
var entry = value.entry;
if (entry === this._head) {
this._head = entry.next;
this._head.prev = null;
} else if (entry === this._tail) {
this._tail = entry.prev;
this._tail.next = null;
} else {
entry.prev.next = entry.next;
entry.next.prev = entry.prev;
return value;
* Clears the HashMap and insertion order.
* @override HashMap.clear()
LinkedHashMap.prototype.clear = function() {
HashMap.prototype.clear.apply(this, arguments);
this._head = this._tail = null;
* Returns the HashMap keys in insertion order.
* @override HashMap.keys()
LinkedHashMap.prototype.keys = function() {
var keys = [];
for (var cur = this._head; cur != null; cur = cur.next) {
return keys;
* Returns the HashMap values in insertion order.
* @override HashMap.values()
LinkedHashMap.prototype.values = function() {
var values = [];
for (var cur = this._head; cur != null; cur = cur.next) {
return values;
This new data structure, a marriage between a hash map and doubly linked list, is perfect as the sole backbone of
Dashboard to manage widgets.
Moving On
With just a little overhead for write operations to the
LinkedHashMap, even basic problems that require hash map behavior can query the insertion order with ease.
var map = new LinkedHashMap();
map.put("key1", "one");
map.put("key2", "two");
map.put("key3", "three");
// return order is now predictable
console.log(map.keys().join(',')); // "key1,key2,key3"
console.log(map.values().join(',')); // "one,two,three"
LinkedHashMap implements the same API as
HashMap via inheritance, calling code can switch to a
LinkedHashMap at runtime without breaking. The beauty of object-oriented design is that the declared type (
HashMap) of a variable is irrelevant to the runtime type (
LinkedHashMap). The only difficulty is enforcing the API in a type-unsafe language like JavaScript…but that's another article.
Tutorial: LispyScript Introduction
LispyScript is a tree structured programming language that compiles to JavaScript. A LispyScript program is made up of one or more LispyScript expressions.
(<function> arg1 arg2 arg3 ...)
A LispyScript expression is made up of an opening parenthesis, a set of elements separated by space characters, and a closing parenthesis. A LispyScript expression is a function call (this is not exactly accurate, but we will see the exceptions to this later).
The first element evaluates to a function. It may be a function reference or an anonymous function. The rest of the elements are the arguments to the function. The expression evaluates to the return value of the function.
(console.log "Hello World!")
You will notice that we called
console.log, which happens to be a JavaScript function, directly from LispyScript. You can call all JavaScript functions from LispyScript, even loaded library functions and object methods.
console.log also works like
(console.log "2 + 2 = %d" (+ 2 2))
You can have expressions within expressions in LispyScript. Here the expression
(+ 2 2) is evaluated first, and replaced with its return value
4. Then the function
console.log is called with arguments string
2 + 2 = %d and value
And this is all there is to the basic structure of a LispyScript program. LispyScript has a tree structure: expressions within expressions. Let's look at a tree structure almost everyone is familiar with: HTML.
<html lang="en">
<title>My Home Page</title>
<h1>Welcome to LispyScript</h1>
This is a LispyScript HTML template that generates the exact same HTML as above:
(html {lang: "en"}
(title "My Home Page"))
(h1 "Welcome to LispyScript")))
We will learn how LispyScript HTML templates work later. For now, you can see that LispyScript has a tree structure. This same code structure can also be a data structure in LispyScript. This is known as homoiconicity – a fancy term for code having a data structure supported in that language.
When a compiler compiles a language like JavaScript, or Java or C, it first parses the source code into a tree structure known as the syntax tree, and then generates the machine/byte code from the syntax tree. If you could manipulate the syntax tree (which you can't in these languages) while compiling, you could actually modify the language itself in ways not possible in the above mentioned languages and most other languages.
In LispyScript your code – for all practical purposes – is the syntax tree itself. And since the language is homoiconic, you can treat your code as data, and even modify the syntax tree! This is what macros do.
LispyScript does not have a
printf() or
console.log in JavaScript. We know that we can call the JavaScript
console.log from LispyScript. Now if we could somehow transform a
console.log expression, we are done!
(macro print (str rest...)
(console.log ~str ~rest...))
(print "Hello print macro!")
(print "2 + 2 = %d" (+ 2 2))
This example extends LispyScript by adding a
macro expression takes the macro name
macro is a code template that will be expanded at macro expansion time.
Here the
console.log, and we name the first argument
str. The second argument
rest... is a special argument which represents the rest of the arguments to
rest... can represent zero or more arguments.
Inside the template expression we dereference the two arguments by adding a
~ to them. So what happens when we use the
(print "Hello print macro!")
The LispyScript compiler works in two steps. First it expands any macro expressions in the code. The previous expression will be expanded to:
(console.log "Hello print macro!")
And then the compiler compiles the above expression to JavaScript
console.log("Hello print macro!");
The expression:
(print "2 + 2 = %d" (+ 2 2))
Is expanded to:
(console.log "2 + 2 = %d" (+ 2 2))
…and compiled to:
console.log("2 + 2 = %d", (2 + 2));
This is a very simple example and you don't gain much, but it's good enough to illustrate a simple macro. You might wonder why a
(var print
(function (data value)
(console.log data value)))
(print "2 + 2 = %d" (+ 2 2))
This will work too, but have a look at the compiled output:
var print = function(data,value) {
return console.log(data,value);
print("2 + 2 = %d",(2 + 2));
The print function must be included alongside the call to it in the compiled output! When we used a macro the compiled code was only one line.
console.log("2 + 2 = %d", (2 + 2));
This is only an incidental benefit of using macros. We still need to look at the real benefits. Rather than learn when to use macros, it is better to learn when not to use macros. Macros can be dangerous. Consider this function:
(var square
(function (x)
(* x x)))
(console.log (square 2))
The above code will print the answer
This can be rewritten as a macro:
(macro square (x)
(* ~x ~x))
(console.log (square 2))
And the expanded code is:
(console.log (* 2 2))
That's it! The answer is correct. But now try the following:
(var i 2)
(console.log (square i++))
Ouch! You get 6! An embarrassing square of an integer. If you had used the function you would have got the correct answer. This is what happened:
var i = 2;
console.log((i++ * i++));
When you use functions the arguments to the function get evaluated and then passed into the function. So in this case when you pass
i++, the value 2 is passed as
x into the function and
i gets incremented. So
(x * x) yields 4. In the case of the macro the argument is not evaluated when the macro expansion happens. Whatever you pass as arguments to the macro just get substituted as is in the template. So if you pass
i++, it gets substituted as is in your macro template yielding
(i++ * i++) which is
(2 * 3)!
By taking advantage of tree structures and homoiconicity, LispyScript offers an alternative way of developing JavaScript programs. Although macros are powerful, they must be handled with care.
Enyo Tutorial: Part 1
Enyo is a mobile and desktop framework that uses JavaScript and HTML5. Developed by HP and the open source community, it's licensed under the Apache License. If you're looking to build mobile applications with JavaScript, then Enyo is a great choice. In this tutorial series, I'll introduce the major concepts through some worked examples that you can build or download and try out. The Enyo styleguide is suggesting double quotes instead of single quotes. Enyo also uses tabs for indentation. Although I prefer 2 Spaces as indentation and single quotes, I will follow these rules during this tutorial.
Enyo applications are built around object prototypes called
kinds. These can be either
components or
controls. Kinds in Enyo are very modularized, reusable and encapsulated.
Controls, on the other hand, are for controlling DOM nodes and manipulating them. Controls can nest other controls or components – they're the "building blocks" for applications. A good example would be an app consuming an XML feed: a component would process the feed to JSON and rearrange the data. The views of that application representing the feed would be controls.
The Tip Calculator
There are hundreds of tip calculator apps on all the major vendor-specific app stores. We can go one better though – let's build a tip calculator that can run on pretty much anything. Also, our Enyo-based app will be publishable using Cordova (formerly PhoneGap).
The Enyo project provides Bootplate – Enyo's template project. All we have to do is clone the repository and
init the submodules:
git clone https://github.com/enyojs/bootplate.git
cd bootplate
git submodule update --init
First Steps
Next open
debug.html. You should now see the example app. In our developer console, type the following:
new enyo.Control({ content: 'Hello World' }).write();
This creates an Enyo control. It's rendered as a simple
<div id="control">Hello World</div>
Going Deeper: Controls, Getter and Setter, Events
To start developing the tip calculator, delete the contents of
source/App.js – we'll replace it with a new file.
Let's add a
kind called
App to our emptied
name: "App",
kind: enyo.Control,
style: "",
classes: "onyx",
components: [
{kind: "onyx.InputDecorator", components: [
{kind: "onyx.Input", name: "sumControl", placeholder: "Enter sum"}
{kind: "onyx.InputDecorator", components: [
{kind: "onyx.Input", name: "percentControl", placeholder: "Enter percent"}
{kind: "onyx.Button", content: "Calculate tip", ontap: "calculate"},
{tag: "div", name: "tipAmount"}
create: function() {
calculate: function(inSource, inEvent) {
var sum = this.$.sumControl.hasNode().value;
var percent = this.$.percentControl.hasNode().value;
var result = (sum * percent) / 100;
return true; // stop bubbling
An instance is created and rendered into the DOM in our
debug.html file with
new App().renderInto(document.body);
Now I'll explain the previous example in detail. The
kind property is set to
enyo.Control, and there are currently no inline styles – the
style property is empty. The
onyx CSS class should be added, which is an included submodule in the Bootplate that themes our Enyo application and the applications elements.
components property is used to nest more kinds – I've used several to define the required input controls, a button, and a
div to display the results. All of these components have a
name property, which is important and will be explained later.
The button has an event attached, the
tap-event. Enyo supports many other events, e.g. dragging over the screen,
flick, or self-created events.
When a
kind is created the method
create is automatically called by the Enyo framework. The method inherits from its parent kind with
this.inherited(arguments); and can be overwritten. There are several other constructor and constructor-like functions in the lifecycle of a
create or
Every time we tap our button the
calculate method is called.
this.$ is used to address and access controls within the kind.
var sum = this.$.sumControl.hasNode().value
This line is where the value of the control with the name
sumControl is accessed. After that we calculate the tip and render the result into the element.
Every control has some handy getters and setters:
At the end of the method
return true is used to prevent the tap event from bubbling up.
Get the Source
The source is available at my GitHub account: robertkowalski/enyo-dailyjs.
We've now hacked together a very basic tip calculator. This example could be built on to add a canvas element for diagrams,
localStorage for statistics, or simply to add validation to user input.
In the next part of this series we'll have a closer look at components and exposing the published properties of kinds. We'll also create more reusable components from our app.
Node Roundup: mongo-lite, smog, sshfs-node
mongo-lite (GitHub: alexeypetrushin / mongo-lite, License: MIT, npm: mongo-lite) by Alexey Petrushin aims to simplify MongoDB by removing the need for most callbacks, adding reasonable defaults like safe updates, and offering optional compact IDs.
The chainable API looks more like MongoDB's command-line interface:
var db = require('mongo-lite').connect('mongodb://localhost/test', ['posts', 'comments']);
db.posts.insert({ title: 'first' }, function(err, post) {
// Use post
There's also a Fiber-based API, so it can be used in a synchronous fashion.
smog (License: MIT, npm: smog) from Fractal is a web-based MongoDB interface. It displays collections, and allows them to be sorted and edited. It also supports administration features, like shutting down servers, CPU/bandwidth usage graphs, and replica set management.
It's built with Connect, and there's an experimental GTK+ desktop interface made with the pane module by the same authors.
sshfs-node (License: MIT, npm: sshfs-node) by Charles Bourasseau allows remote filesystems to be mounted using SSH. It uses sshfs and requires keys for authentication, rather than passwords.
It comes with Vows tests, and the same author has also released fs2http.
jQuery Roundup: equalize.js, jQuery Builder, Gridster.js
This plugin comes from the "should I just use a table?" department of design technicalities that we still have to deal with in 2012: equalize.js (GitHub: tsvensen / equalize.js, License: MIT/GPL). Created by Tim Svensen, this plugin resizes elements to match their height or any other dimension supported by jQuery Dimensions.
It works by calling a single method on the parent selector:
// Height is the default
The documentation has full examples.
jQuery Builder
jQuery Builder (GitHub: jgallen23 / jquery-builder, License: MIT, npm: jquery-builder) by Greg Allen is a web-based tool for building a custom version of jQuery 1.8.1. As jQuery has evolved it's got a lot easier to include only the components necessary for a given project. This particular solution has been made using Node, and is installable with npm.
Gridster.js (GitHub: ducksboard / gridster.js, License: MIT) from Ducksboard is a grid plugin that allows layouts to be designed by drag and drop. Elements can span multiple columns, and by dynamically added and removed. Any element can be used because Gridster is based around data attributes.
Gridster is distributed with suitable CSS, and supports IE 9+, Firefox, Chrome, Safari, and Opera.
Encapsulation Breaking
Encapsulation is the process by which an object's internal components and behavioral details are hidden from calling code. Only that which should be exposed is exposed, making objects self-contained black boxes to the outside world. Many languages support encapsulation by supplying visibility modifiers (e.g., private) and constructs such as inner classes.
Unfortunately, JavaScript offers very little in the encapsulation department. While there are certain tricks that can wrap protected code in closures (see Module Pattern), many have disadvantages that compromise code flexibility and extensibility.
Standard Convention
Instead of using closure-based encapsulation, which often makes object-oriented inheritance difficult, many libraries and code-bases opt to mark private properties and functions with an underscore prepend. This convention makes inspecting the properties and functions easy within browser debuggers.
var Person = function(first, last){
// private properties _first, _last, and _id
this._first = first;
this._last = last;
this._id = this._generateId();
Person.prototype = {
getId : function(){
return this._id;
getFirstName: function(){
return this._first;
getLastName : function(){
return this._last;
// private function to generate an id for this object
_generateId : function(){
return new Date().getTime().toString();
This convention is commonplace, similar to naming constants in uppercase. The downside is that private properties and functions can still be accessed, thus breaking encapsulation because of careless coding.
Encapsulation Breaking
The dynamic nature of JavaScript allows for a free-for-all environment where a developer can do whatever he or she wants. Consider the following:
var person = new Person("Bob", "Someguy");
console.log(person._first); // logs "Bob"
This appears all fine and well, but now we've coupled our code to the
Person implementation. Any change to the internals – the category of change encapsulation should protect us against – could break calling code.
var Person = function(first, last){
this._firstName = first; // property change
this._lastName = last; // property change
this._id = this._generateId();
// ...
var person = new Person("Bob", "Someguy");
console.log(person._first); // logs "undefined"
These bugs can be difficult to track, especially since the application code may not have changed…an updated external library or resource, in which
Person may be defined, is all that it takes. The best defense against such couplings is to avoid breaking encapsulation. If a property or method is marked as private, do not access, modify, or invoke it. The overhead in rethinking the architecture and design is almost always less than the cost of dealing with the consequences of breaking encapsulation.
In other words: "Developers don't let developers break encapsulation."
Method Stealing
As troublesome as accessing private properties can be in JavaScript, there is another much more insidious practice that seems commonly accepted: method stealing.
The methods Function.prototype.call and Function.protoype.apply are integral to modern libraries and code-bases by allowing a method to inject a custom context (this reference) into the execution scope. Without these capabilities the reliance on closures to achieve the same effect would be too cumbersome.
Just as some properties should be hidden, so too should some methods. Given our prior example,
Person.prototype._generateId() might function as an inadequate UUID generator. A clever developer notices that another available method
Book.prototype._setUUID() sets a
this._id property on all Book objects whose value is much more unique across space and time than
var Book = function(title, author){
this._title = title;
this._author = author;
this._id = null;
Book.prototype = {
getId : function(){
return this._id;
getTitle : function(){
return this._title;
getAuthor : function(){
return this._author;
_setUUID : function(){
var result = '';
for(var i=0; i<32; i++)
result += Math.floor(Math.random()*16).toString(16);
this._id = result;
In return, the developer has chosen to "steal" this behavior from
Book for
Person and modify
Person.prototype._generateId() to invoke
var Person = function(first, last){
// private properties _first, _last, and _id
this._first = first;
this._last = last;
this._id = null;
Person.prototype = {
getId : function(){
return this._id;
getFirstName: function(){
return this._first;
getLastName : function(){
return this._last;
// private function to generate an id for this object
_generateId : function(){
// sets this._id withing _setUUID()
Again this works…ostensibly so, by having
this._id set by
Book.prototype._setUUID(). The design is brittle, however, because
Book's internals can be refactored unbeknownst to
Person, thus breaking
Person objects. If
Book.prototype._setUUID() is refactored to set
this._uuid rather than
this._id then all
Person.prototype.getId() invocations will return undefined. With one myopic decision we broke our application because it was easier to break encapsulation rather than rethink the design.
There is not much of a conclusion except do not break encapsulation. In fact, apply the Golden Rule while coding: treat other code as you wish yours would be treated. Any API deficiencies should be brought to the original author, not hacked apart to make it usable for one use case or instance. The maintenance headache down the road is just not worth it.

subset: commoncrawl


text:
VeriFone Systems Inc. has defied the headlines decrying gloom over the European debt crisis by enjoying continued growth in the region while continuing to expand payment-terminal installations rapidly in Latin America.
No Gloom For VeriFone In Europe, Latin America
DEC 15, 2011 2:44pm ET
To continue, please log in, register or subscribe.
Already a subscriber? Log in here
Free ISO&Agent Subscription
ISO&Agent Magazine
Merchants and consumers are more mindful of security than ever, but there is still much work to be done to educate them on how to protect account data and prepare for the shift to EMV-chip cards. Fortunately, the industry has help. The ETA, which recently appointed Wells Fargo exec Debra Rossi as its president, is welcoming more technology companies to its ranks to help members adapt to the shifting competitive landscape.


text:
Discover a selection of top forums pares dragonica on the internet. Come to share your passion on forums pares dragonica and meet other fans of pares dragonica. Then, why don't you create your own forum of pares dragonica ?
The forum of the guild ZeHero of Dragonica Europe
zehero, forum, guild, #dragonica, europe


text:
Oct 10, 2012 at 05:23PM EDT
Indeedy do. Shame my proposed gif might get me banned. Oh well, the loop was crap anyway. I might do it for a few days next week.
Cheezburger Blog Advertising Developers Jobs Contact Us
Legal Information: Know Your Meme ® is a trademark of Cheezburger, Inc. By using this site, you are agreeing by the site's terms of use and privacy policy. © 2007-2015 Cheezburger, Inc.
Login Now!
Sign up Now!


text:
AT&T U-verse TV
AT&T U-verse TV is Advanced TV
AT&T U-verse TV utilizes fiber optic technology to deliver high definition television. Fiber optic cable is similar to coaxial cable, transmitting data through a pipe. The difference is that U-verse TV is transmitted by fiber optic light bursts rather than electrical signals. Fiber optic light bursts travel long distances, with increased speed and bandwidth, allowing multiple transmissions to occur at the same time with less signal interference so that you can enjoy phenomenal picture and sound quality. Older services, including coaxial cable, simply cannot compete with faster, more reliable fiber optic technology offered by AT&T U-verse.
Enjoy digital video recording (DVR) capabilities, access to over 85 High Definition channels, choice programming, Video on Demand, and a crystal-clear picture when you subscribe to U-verse TV – all at an affordable price!
Enjoy a crystal-clear picture when you subscribe to U-verse TV, along with digital video recording (DVR) capabilities, Video on Demand, access to over 85 High Definition channels, and choice programming - all at an affordable price!
- Customize your own package or choose from a variety of programming packages.
- Digital receivers are HDTV-ready (high definition television).
- Professional installation of your TV and wireless home networking is included at no additional cost.
- Features Guide and convenient channel line-up are included.
AT&T offers U-verse bundle packages that can be customized to fit your needs. Learn more about each AT&T U-verse bundle on the
AT&T U-verse Bundles page.
The AT&T U-verse Standard Receiver
U-verse TV lets you determine your own instant replays, pause live TV shows, or leave the house while your favorite movie is being recorded.
With a qualifying package, the AT&T U-verse Standard Receiver supports Total Home DVR® features, allowing you to watch what you want, when you want, where you want. Access, playback, and control recorded shows on up to 4 TVs. No cable company comes close to matching U-verse service!
Standard Receiver Features:
- Full DVR capability including ability to pause live TV.
- Record up to four programs at the same time.*
- Digital audio and video - 100% (including Dolby Digital availability).
- On-screen program guide with 14-day look-ahead feature.
- Access your Video on Demand library, Pay-Per-View, U-verse Movies, anytime.
- On-screen parental control.
- HD Enabled and Energy Star Certified.
* Four channels can be viewed or recorded to the DVR simultaneously. Based on the service in your area, up to two channels can be viewed or recorded in HD at a time.
Total Home DVR from AT&T U-verse
All you need is one U-verse Total Home DVR to enjoy recorded programs throughout your home. Total Home DVR allows you to:
- Watch up to 4 different recorded shows at the same time. Up to 3 can be viewed in HD.
- Access, playback, and control the same recorded show independently on up to 4 TVs.
- Pause a recorded show from any receiver and watch it from where you left off in another room.
- Record up to 233 hours/SD or 65 hours/HD programming.
- Automatically extend the recording time at the beginning and end of your programs.
- Total Home DVRs automatically group recordings by series to simplify your search.
- Schedule and manage your recordings from any device with an Internet connection.
- No new equipment needed. No additional charges.
* Geographic and service restrictions apply. Total Home DVR requires a DVR receiver at $7 per month for each additional TV, up to 8 total TVs.
AT&T U-verse TV Remotes
With AT&T U-verse TV, you have a choice of two remote control devices: Standard and Easy Find.
AT&T U-verse TV Standard Remote Control
The Standard Remote Control is compatible with all AT&T U-verse TV receivers. Standard remote control features include:
- Universal infrared remote control can control up to 3 additional devices.
- Backlit to work well in low-light conditions.
- Convenient, one-button access to the U-verse features you use most often: Record, Guide, Menu, and Video on Demand.
AT&T U-verse TV Easy Find Remote Control (Model A10)
The innovative AT&T U-verse TV Easy Find Remote Control puts you in charge of home entertainment. The Easy Find Remote Control is equipped with locating, learning, and recharging capabilities, and is compatible with all U-verse TV receivers.
The Easy Find Remote Control combines advanced features and convenience that you have come to expect from AT&T, including:
- Locate your misplaced U-verse TV remote quickly with the touch of a single button that causes the remote to beep and flash.
- The Easy Find Remote Control is environmentally-friendly with its rechargeable battery that lasts up to 3 months on a single charge.
- Get rid of extra remotes. The Easy Find Infrared Remote Control allows you to program up to three other devices. It even learns from your other remote controls.
Additional Features: The base of the Easy Find Remote Control has a built-in clock with dimming feature. The remote is backlit for use in low light conditions and has one-button-access to the U-verse TV features you use most frequently.
AT&T U-verse TV - Parental Controls
AT&T U-verse TV puts you in charge of what your children watch. U-verse TV allows you to block live programs, recorded programs, and videos that are not appropriate for your household. You can even set limits on who can order and watch on-demand videos. The Parental Control feature from U-verse TV allows you to:
- Block channels
Allows you to remove channels you don't want to see in your guide or when browsing channels.
- Set parental locking
Block access to select programming and channels. A Personal Identification Number (PIN) is required to view locked programs.
- Set movie rating controls
Select lowest movie or TV ratings you want locked, locking programs with that rating and higher.
AT&T U-verse TV offers advanced television programming and features that aren't available with standard cable service.
Order AT&T U-verse TV today and enjoy state-of-the-art fiber optic television!
Check out AT&T U-verse Bundles