Mastering Node: Addons and FunctionTemplate (uuid.node)
Last night, I pushed an addition to my fork of Mastering Node. I decided to add a bit to the Addons chapter. The first example in this chapter only shows how to add a function to a natively-compiled module (i.e. an addon). This example shows you how to start a module which can be used in the following way:
var Uuid = require('./uuid.node').Uuid;
var uuid = new Uuid();
var myId = uuid.generate();
The project files referenced in the following text can be downloaded from the repo: jimschubert/masteringnode
FunctionTemplate
In v8, a FunctionTemplate is used to create the equivalent to:
var template = function() { }
The function at this point is an object and not an instance of the function.
As an example, we will use the linux package uuid to generate a uuid. We will define the header for this addon as:
dotfiles backup using GitHub
I was recently looking for a solution to backup my configuration files (bash, vim, etc) using GitHub. After some looking around, I've compiled a pretty nice project for myself.
First, this script checks dependencies. My dependencies are git, ruby, vim, tree, rake, gem, bundle, and trash. You could check out the code and add any number of dependencies here. Rubygems and bundler are required because the script later installs all gems listed in Gemfile.
Next, the script copies ~/.bashrc to ~/.bashrc.local. This allows you to keep your current bash configuration as a 'local-only' config that doesn't get copied or committed to github.
The script, as I copied most of bootstrap.sh and the rakefile from @gf3, expects the repository to be cloned to ~/.dotfiles. From there, it calls rake.
Rake looks at every file in ~/.dotfiles and copies the corresponding file relatively from ~/ to, essentially, ~/dotfiles-backup/`date`. I recommend first running the backup to make sure your files are properly backed up.
rake backup
The script then calls 'bundle install' to install all gems. It then copies all files from ~/.dotfiles to replace those relative files that were previously backed up from ~/.
The post-install displays a message to remind you to edit .gitconfig and .hgrc.
Because I've done some copying and compiling, these are relative close to the three projects in the README for right now.
Here is an excerpt from the README:
Bash
$ tree ~/.bash
/home/jim/.bash
├── aliases
├── completions
├── completion_scripts
│ └── git_completion
├── config
├── functions
├── paths
└── prompt
The above files are loaded by .bashrc. The files are pretty self-explanatory, other than prompt which colorizes the bash prompt with tweaks for git.
Cool Aliases
- cd : pushd
- bd : popd
- cd.. | .. : back one directory
- cd... | ... : back two directories
- ^ up to five directories
- rm : trash
- undopush
- ip
- GET | HEAD | POST | PUT | DELETE | TRACE | OPTIONS
Config
- sets editor to vim
- sets English/UTF-8
- sets manpager
- sets commands to ignore in history
- sets noclobber (e.g. prevents
cat > IMPORTANT_FILEmistakes ) - sets nocaseglob (e.g.
ls ~/.B*will list contents of~/.bash)
Functions
The two functions, md and c may not seem like much, but they simplify some commands. For example:
$ md projects; git clone git@github.com:jimschubert/dotfiles.git && cd dotfiles
In the above line, md will create the projects directory and cd into it.
c stands for 'code' and works like this:
jim at computer in ~
$ pwd
/home/jim
jim at computer in ~
$ c dotfiles
~/projects/dotfiles ~
jim at computer in ~/projects/dotfiles on master
$
You can change it to whatever shortcut and issue reload, which is also an alias from this setup.
Screenshot
Notice the color scheme and github branch notifications created by ~/.bash/prompt.
Install nodejs under ChromeOS (CR-48)
Why would I want to do this?
I'm a software developer. I love javascript. I love node.js. I love the direction Google is taking web development, user interaction, and the web in general. Installing node.js opens up a lot of possibilities for me on my CR-48. I don't know if this will work on anything other than the CR-48, considering the machine has to be in developer mode for these instructions.
If you don't have a chromebook yet, or you don't know what they are... where have you been? But seriously, visit http://www.google.com/chromebook/ and check them out.
Before I start, let me first say that following these instructions may void your warranty if you have one, open your machine up to vulnerabilities, or replace existing files and cause instability. If you don't know how to revert or fix any issues that may occur, don't continue. I offer no sort of warranty, support, or anything else. Consider this a 'hack' of sorts.
I found a blog post detailing how to install an archive package and ruby on rails in ChromeOS. I followed part of these instructions and I have modified them to fit my needs.
Prerequisites
- You must have a Chromebook, possibly only the CR-48
- You must be in 'developer mode'
- You must have a writable rootfs (see above link for developer mode)
Instructions
Downloading and installing xz
- Download the xz package
- Enter crosh or VT-2 (CTRL+ALT+T or CTRL+ALT+→)
- If VT-2, login to the shell
- Run on the terminal: cd /home/chronos/user/Downloads
- Run on the terminal: tar -zxf xz-*.tar.gz
- Run on the terminal: cd usr
- Run on the terminal: cp * /usr/
Now that xz is installed in /usr/bin (verify by running on the command line: which xz), you will be able to extract certain files that are necessary for nodejs and possibly any other package you'd like.
Download and install nodejs and openssl.
The site claims openssl is optional, but node wouldn't open without it
- Download nodejs
- Download openssl
- Enter the terminal again and navigate to /home/chronos/user/Downloads
- Run on the terminal: xz -d node*.xz
- Run on the terminal: tar -zxfv openssl*.tar.gz
- Run on the terminal: cd usr
- Run on the terminal: cp * /usr/
Now you should have a working install of nodejs. You can use npm, for instance, to install express and jade.

[c#] Instantiating an object with a private constructor
Not too long ago, I needed to modify a type available in the the BCL which didn't have a public constructor or any method for creating an instance of the object. The solution was to use reflection to invoke the type's private constructor.
Caveat!
Most times, these types are designed with private methods for a reason. There may be internal dependencies which can cause all kinds of problems if they're not met. Only do something like this if you're writing tests against the constructor or exploring the capabilities of Reflection.
The ConstructorInfo Class is the one we'll use. If your constructor is parameterless and non-public, you can instead do:
var myType = (MyType)Activator.CreateInstance(typeof(MyType), true /*nonPublic*/);
To instantiate an object from a non-public constructor with parameters, you'll need three things:
- the target type
- an array of parameter types (same order as signature)
- a reference to the constructor
Suppose your target type is defined as:
class Example
{
public string Display { get; private set; }
private Example(string msg)
{
Display = msg;
}
}
To instantiate this object, you can do the following:
// 1. the target type
var exampleType = typeof(Example);
// 2. an array of parameter types (same order as signature)
var argTypes = new Type[] { typeof(string) };
// 3. a reference to the constructor
// Because method signatures must be unique in parameters and return type,
// this will return the matching constructor, or ctor will be null.
ConstructorInfo ctor = exampleType.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null, argTypes, null);
// similar to var example = new Example("You've set me privately!")
var example = (Example)ctor.Invoke(new []{ "You've set me privately!" });
Console.WriteLine("Example's display: {0}", example.Display);
Note:
ConstructorInfo requires FullTrust.
[js] Closures versus Functional Scoping
I was recently asked a very simple JavaScript question: what is a closure?
Of course, I answered it (correctly, might I add) as "it means capturing a variable inside a function". I was asked for an example, so I said, "Well, first I'd like to show a common mistake of closures when using loops." I gave the common looping mistake example:
var someArrayOfThings = /* [blah blah blah objects blah blah] */;
for (var i = 0, len = someArrayOfThings.length; i < len; i++) {
var item = someArrayOfThings[i];
// some function here to access item
}
There was some huffing about this. Maybe the developer didn't understand where I was going, or didn't care. Unfortunately, I wasn't asked to explain why it would cause an error. I should have given the example from MDN verbatim.
So, this guy gave me the following 'example':
var a = 1;
function a() {
var a = 0;
test = function() { alert(a); }
test();
}
a();
Him: What does this do?
Me: Uh... nothing.
Him: No, you're wrong.
Me: Uh... I'm pretty sure I'm right.
Him: No, I'm sure you're wrong. This will alert 0. Always.
So sure? Try it yourself.
Why I was right.
- "Functional scoping" !== "closure"
- Hoisting redefines 'a' from function to number, not the other way around.
- Did he mean to define 'test' as a global?
This guy wasn't even talking about a 'closure', he was displaying functional scoping. I can understand the misconception between the two. A 'closure' occurs when a function closes the functional chain over some variable available at a greater scope, making that variable look like part of the function.
For instance:
var message = "outside";
var first = function() {
var message = "inside";
var second = function() { alert(message); }
return second();
};
first(); // alerts "inside"
In this example, the functional scope of the second function has access to the message which holds "inside". This is exactly the same concept as the developer was getting at. However, just calling the function, as in his example, doesn't close the outer function chain. Yes, variables captured inside functions will hold the value of the variable at the level of scope of when the function was declared. However, in his example he's just calling (or he thinks he is, I'll get to that later) one function to another:
call a ->
set local a to zero ->
define 'inner function' ->
call inner function ->
alert a from outer scope
As you can see, there is no 'capturing' of any variables. You could just as easily write this up without the added complexity of an inner function.
In my example, the execution goes more like this:
parse first ->
create second function ->
capture message "inside" ->
compile second function to alert("inside") ->
call newly compiled function
If you're familiar with C++, this is similar to a function pointer. In C#, it's almost like a compiled expression. Your function is actually encapsulating the data created by the closure.
Then again, I consider this all common sense about JavaScript.
On to the fundamental incorrectness of the not-mine example
So, I asked, "Both variables and the function are a?" "Yes" "Then, I'm sure it won't do anything!" (Ok, I just want to drive that home!) Then I said, "If you rename the function, then yes... it will alert 0."
Function definition versus function declaration.
Here is an obviously very little known fact about JavaScript. You can declare a function in two general ways in JavaScript:
// function definition
var myFunction = function() { alert("My function!"); }
// function declaration
function myFunction() { alert("My function!"); }
I rarely ever use the second form of declaring a function.
In the function definition (first) example, only the variable is hoisted to the top of the current scope. 'myFunction' will always refer to your function. If you reassign myFunction to an integer, it's an integer. If you've previously defined it as an integer and reassign to a function, it's a function. This is the commonly expected behavior and is why you should declare all of your variables at the top of every function.
In the function declaration example, the entire function is hoisted!! This is done because JavaScript allows you to call methods which haven't physically been defined yet. So, the code the developer wrote for me and insisted was correct is actually parsed like this by JavaScript standards:
function a() {
var a = 0;
test = function() { alert("a");}
test();
}
var a = 1;
a();
If you don't believe me, run the first example on jsfiddle and this example. If you look in your browser's console, you should see the same error for both bits of code. e.g. in Chrome 15:
Uncaught TypeError: number is not a function
As you can see, JavaScript implicitly raises all function declarations to the top of your scope! BE CAREFUL WITH THIS.
In contrast, had this developer written the function in my preferred way, I would have said, "It will alert 0, but you shouldn't be assigning the function to a global variable!" So, in the future, it's my way or the highway.
I highly recommend that every developer who writes JavaScript code read JavaScript: The Definitive Guide by David Flanagan. You will learn everything about the language you'll ever need to know. You'll learn quirks like the function-hoisting I've described here.
Even if you're like me, and you've been using JavaScript since 1998 or 1999, you'll learn a LOT. I'll admit, I used to hate JavaScript with a fiery passion. It wasn't until 2006 or so when jQuery appeared and made JavaScript cool again that I started to really dig into it. Anyway, read the book!
DataAnnotations, MVC 3, and Unobtrusive Validations
DataAnnotations are a pretty cool introduction to .NET 3.5+. It is very useful in ASP.NET MVC 3, and I've written a somewhat naive attempt to use this functionality in ASP.NET Web Forms which some people have found very useful.
I'd like to dig a little more in depth...
Bitwise Operations: Examples
One post that I've always loved on stackoverflow is this post by Hugoware which contains some useful extension methods for bitwise operations.
Bitwise operations can be used to perform all kinds of useful calculations. Below are some examples to whet your appetite for knowledge.
1) List of Integers trickery
You may have seen this question somewhere in some form or another: "Given a list of integers of unknown size where all but one integer occurs an even number of times, find the odd integer." This is usually a part of some algorithm coding-for-fun puzzle. When I first came across this question, I tried a number of different ways to loop through a list, none of which were optimal. In the end, I realized you can use XOR bitwise operations to do this.
First, create a list of integers and set your control integer to 23:
List<int> items = new List<int>();
for (int i = 0; i < 100; i++) {
items.Add(i);
if(i == 23) { items.Add(i); }
}
Then, create a value to keep watch, and perform an XOR on every value:
int found = 0;
foreach (int item in items) {
found ^= item;
}
Finally, output to console or inspect the found variable to be sure it contains the number 23.
Why this works
The complexity of this algorithm is O(1). It doesn't get any easier than that. If you were to add more loops or extra data structures to maintain values, you degrade performance.
If you've read my previous post about bitwise operations, you may remember that an XOR toggles the bits. When you start at zero, all even occurrences will be zero when the loop is completed. The only bits left will be the bits from the odd occurrence of an integer (in other words, 0 ^ 23 = 23).
Cool, huh?
2) Division by 2 or 3
This is one of the few things I remember from my Information Systems class at VCU (sorry, Dr. Wynne). My professor work on a project many years ago, trying to debug a performance issue. When running through certain calculations, the application performance would reduce by orders of magnitude. The problem was with how the application was performing division. Sorry, I don't remember the exact details because I think it was being done in Assembly (I guess I don't even remember this story from VCU!). The solution was to perform bitwise division on the value. For example:
List<int> items = new List<int>();
for (int i = 0; i < 1000; i+=2) {
items.Add(i);
}
foreach (int item in items) {
Console.WriteLine("{0} / 2 = {1}", item, item >> 1);
}
Why this works
Let's look at a single number, 6. The bits for 6 look like:
0 1 1 0
This means the 2 bit and the 4 bit are set. If you use the right-shift operator ('>>'), you're moving all of the bits that many positions to the right. So, if you perform '6 >> 1', you get:
0 0 1 1
Sure enough, that's 3!
Now, you may be thinking "How often do I need to divide by 2?" Well, this doesn't just work for the number 2. You can lop off any number of bits.
x >> 2 is the same as x / 4 ( or x / (2^2) ).
x >> 3 is the same as x / 8 ( or x / (2^3) ).
And so on...
What if I want to divide by an odd number?!
Then do something like: x / 3. Seriously. If you're interested, you can take a look at this post on stackoverflow.
What you do in this case is use a magic number which causes the left-most 32bits in a 64bit result to be equal to the result of dividing by 3. Then you shift those 32 insignificant bits off. Be careful, though, because you can easily overflow your value type. Here's an example:
Console.WriteLine("300 / 3 = {0}", (300L * 1431655766) >> 32 );
If you look at the binary for that magic number (1431655766), you'll see:
0101 0101 0101 0101 0101 0101 0101 0110
To see what this is doing in something a little simpler like 6/3=2, you can run this bit of code and inspect the binary displayed.
long tester = 6L * 1431655766; Console.WriteLine(Convert.ToString(tester, 2).PadLeft(36, '0'));
Notice that I used 36 digits to pad because I know 6/3 is 2 and I only need 4 extra bits to show that. In the binary below, instead of separating each by by a space, I've separated the 32 bits we'll lop off from the end result.
0010 00000000000000000000000000000100
When you shift this result by 32 bits, you're left with the answer: 2.
Why does this work?
Take, for example, the magic number multiplied by 243 = 347892351138.
Our answer should be: 243/3 = 38.
01010101010101010101010101010110
x 11110011
______________________________________________
01010101010101010101010101010110
0 10101010101010101010101010101100
00 00000000000000000000000000000000
000 00000000000000000000000000000000
0101 01010101010101010101010101100000
01010 10101010101010101010101011000000
010101 01010101010101010101010110000000
0101010 10101010101010101010101100000000
______________________________________________
1010001 00000000000000000000000010100010
As you can see, the end result (the last line) is the binary representation of 38!
3) Obfuscation
You can use XOR or any other bitwise operation to obfuscate a string. The idea is to take a single character, XOR all characters in a sentence with your secret to obfuscate. To deobfuscate, you XOR all characters in your obfuscated string and the result should be your original string!
Here's a quick example:
char key = '*';
string sentence = "Would you like to play a game?!";
Console.WriteLine("Original string: '{0}'", sentence);
string obfuscated = String.Empty;
foreach (var item in sentence) {
obfuscated += (char)(item ^ key);
}
Console.WriteLine("obfuscated string: {0}", obfuscated);
string deobfuscated = String.Empty;
foreach (var item in obfuscated) {
deobfuscated += (char)(item ^ key);
}
Console.WriteLine("deobfuscated string: {0}", deobfuscated);
The output should look something like (non-printing characters are not displayed, so you may see something slightly different):
Original string: 'Would you like to play a game?!' obfuscated string: }E_FN SE_ FCAO ^E ZFKS K MKGO deobfuscated string: Would you like to play a game?!
What happens when I overwrite a DLL (asp.net)?
I post on Stack Overflow a lot. Sometimes, there are really interesting questions like one I answered last year. I had forgotten about it until this week when the answer was accepted. I thought I'd share it on my blog.
The original post is here. Read on for redundancy.
Loading newer versions of jQuery and jQuery UI (noConflict)
Here's an interesting problem:
You have an ASP.NET Web Forms application which references jQuery 1.3.x and would require a lot of testing to upgrade to a newer version of jQuery. You're adding functionality to this application, and you really want to use jQuery 1.5 or jQuery 1.6 going forward with new development. But..., jQuery 1.3.x is referenced in the master page. Also, you want to load jQuery UI 1.8.x targeting the newer version of jQuery.
...
Bitwise operations and Flags (C#)
I haven't written anything in a while, so I thought I would finally write about the subject of bitwise operations and the FlagsAttribute.
I mentioned this to one of the developers on my team, and he said that he somewhat understood bit operations but he had never found a reason to use them.
Here is the code I will use to discuss the operations
int a = 57754;
int b = 18782;
int aXORb = a ^ b;
int aORb = a | b;
int aANDb = a & b;
int aNOT = ~a;
int bNOT = ~b;
string spacer = "---------------------------------------------";
Console.WriteLine("{0} ({1}) a", GetBitString(a), a.ToString());
Console.WriteLine("{0} ({1}) b", GetBitString(b), b.ToString());
Console.WriteLine("{0} ({1}) a ^ b", GetBitString(aXORb), aXORb);
Console.WriteLine(spacer);
Console.WriteLine("{0} ({1}) a", GetBitString(a), a.ToString());
Console.WriteLine("{0} ({1}) b", GetBitString(b), b.ToString());
Console.WriteLine("{0} ({1}) a | b", GetBitString(aORb), aORb);
Console.WriteLine(spacer);
Console.WriteLine("{0} ({1}) a", GetBitString(a), a.ToString());
Console.WriteLine("{0} ({1}) b", GetBitString(b), b.ToString());
Console.WriteLine("{0} ({1}) a & b", GetBitString(aANDb), aANDb);
Console.WriteLine(spacer);
Console.WriteLine("{0} ({1}) a", GetBitString(a), a.ToString());
Console.WriteLine("{0} ({1}) ~a", GetBitString(aNOT), aNOT);
Console.WriteLine("{0} ({1}) ~(~a)", GetBitString(~aNOT), ~aNOT);
Console.WriteLine(spacer);
Console.WriteLine("{0} ({1}) b", GetBitString(b), b.ToString());
Console.WriteLine("{0} ({1}) ~b", GetBitString(bNOT), bNOT);
Console.WriteLine("{0} ({1}) ~(~b)", GetBitString(~bNOT), ~bNOT);
Console.ReadLine();
// And, the GetBitString method
static string GetBitString(int input){
int sizeInt;
// Number of bits is bytes * 8
// I specifically chose 16-bit values to reduce the amount displayed
unsafe{ sizeInt = (sizeof(ushort) * 8); }
string output = String.Empty;
for (; sizeInt >= 0; sizeInt--) {
output += (input >> sizeInt) & 1;
if(sizeInt % 4 == 0) { output += " "; }
}
return output;
}
XOR ( ^ )
From MSDN:
Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true.
I think of XOR as a "one-toggle". The logic can be seen as (format is [first] : [second] --> [result] ):
0 : 1 --> 1 1 : 1 --> 0 1 : 0 --> 1 0 : 0 --> 0
As you can see,

