Sunday, June 19, 2016

I've had this experience one to many times. And in self defence my code doesn't look ugly even when I've just written it; I don't have to come back and "clean it up".


Wednesday, February 10, 2016

I wrote my solutions to tour.golang.org at gist.github.com



How quickly I've picked up Go

I started writing Go with the cononical hello_world.go program on Jan 11, 2016.

I wrote a working B+Tree implementation in Go on Feb 11, 2016.

So I would say it took me 4 weeks to become "productive" in Go. I still need to use the Playground to work out small issues with Go syntax every now and again.

Sunday, February 7, 2016

Testing Gist & Go Playground

The Gist:



The iframe embed of Go Playground heigh=500

Tuesday, April 1, 2014

Thunks and co with ES6 generators

A thunk is the output of a transformed node.js-style asynchronous function. The transformed function (aka the thunkified function) is meant to work with a generator wrapper. Here is the generator wrapper I am talking about:
co(function*(){
  ...alot of synchronous looking code...
})()
That generator wrapper takes the output of a thunkified async function call in a yield context and passes the ultimate results of the async call back to the original yield location; so code like this works (within the generator wrapper):
output = yield thunkfiedAsyncFn(args...)
Where node.js asynchronous functions are called with a few arguments plus one callback function to receive the output of the async operation, a thunkified node.js function call takes the original arguments MINUS the callbcak function and outputs a thunk function. In the above example what you are yielding to the generator wrapper is the thunk function. Here is a full example of reading a list of files in series: As you can see this is very different from how you would need to do it with the async module. For example, you can directly use the array subscript i of the fns array (normally you have to worry about the closure over i in a callback always being equal to 4.

To do the same async work in parallel you collect an array of thunk functions and yield that array. Example:

Saturday, August 4, 2012

Just published v1.1.0 of my framing protocol module for node.js. https://github.com/lleo/node-frap I rewrote the input parsing routine completely for v1.1.0. It wasn't broken before, but the current version is much cleaner/better looking code. I remove gobs of what I've come to call vomit code. All the verbosity for debugging and assert-bombing to die close to a bug (old C-coder debugging style of mine). Lots of lines-of-code reduction. Makes it easier to read casually. I implemented a lot of BDD tests, based on the mocha framework. I wrote better benchmark scrips. Better but not very good. Overall, I'd say it is more stable and healthier code than v1.0.0.

Saturday, June 23, 2012

IEEE 754 may not be such a kluge I thought it was

I just found out something elegant about double floating point numbers... or maybe this is just a Javascript thing.

function log2(v) { return Math.log(v)/Math.LN2 }
log2(Number.MAX_VALUE) //=> 1024
The Log base 2 of the Maximum double floating point number is 1024. There is something elegant about that. My respect for IEEE 754 just went up.

Friday, September 23, 2011

Again: exports and module.exports in JavaScript Modules

I reread my posts and realized that I haven't been clear as I'd like.

If you require() a module there are a couple simple rules:
  1. you don't need to put the '.js' on the end of the file.
  2. if you require('./my_module') the file must be in
    1. ./my_module.js or
    2. ./my_module/index.js
  3. if you require('my_module') the file must be in
    1. ./node_modules/my_module.js or
    2. ./node_modules/my_module/index.js or
    3. or a node_modules directory toward root (.. or ../.. or ../../.. till /node_modules)

As for the module file itself, you must set the object to be returned from the require() call. This is the part that flummoxed me.

It is simple, in your module there is a module variable automagically. That module variable points to an object that is pre-populated with many properties. Just do a console.dir(module) in your empty module file to see it all.

The object that gets returned from the require() call is pre-allocated in the module.exports property. There is also a variable called exports that contains the very same object that is in module.exports. If you assign a new object to the exports variable, eg exports = {};, that new object will NOT be exported as it is not the same object that is in module.exports. Think of it as if there is a invisible exports = module.exports = {}; line at the beginning of your module. The exports variable is only there for your convenience and only the object pointed at by module.exports matters.

This is simple and I found no one who said it straight out. There was crap about exports being an "alias" for module.exports and other balderdash. If you want to create your own elaborate exported object just do this:
exports = module.exports = {
 ... my big-ass exported object ...
};

Thursday, September 22, 2011

CommonJS exports spec ambiguity

I have just been reading the spec for CommonJS. In the 1.0 Spec it refers to the exports variable and object interchangeably.

  1. In a module, there is a free variable called "exports", that is an object that the module may add its API to as it executes.
  2. modules must use the "exports" object as the only means of exporting.

There is no mention of "module" or "module.exports".

I've also realized I am a blithering idiot. I put console.dir(module); in an empty module and I saw that it was populated with a great many things. Most pertinently, module has a property named exports already initialized to an empty object. If you add something to module.exports like module.exports.foo = 'bar'; then console.dir(exports); will output { foo : 'bar' }. It is sad how much my coding skills have atrophied the last few years. I used to be rather sharp ... oh well.

Tuesday, September 20, 2011

Nodejs: module.exports and exports

I have just had a rough time learning how to create my own module. The problem is that I can't move on just knowing How to get something to work, I need to know Why. It is some form of programmer paralysis; worse than writers block. I needed to know how/why exports worked in Nodejs modules.

Requiring modules is simple

var m = require('./my_module');
m.myFunc(foo, bar);
The file needs to be "./my_module.js", with the following exports line:
var myFunc = function () { ... };
module.exports.myFunc = myFunc;
The Why is the hard part. You can't do exports = {}, but you can do module.exports = {}. Turns out module is the "global" namespace in an require() file. exports is some sort of "alias" for module.exports (I haven't figured that out). What this means is that exports.myFunc = myFunc; is OK, but exports = {myFunc: myFunc} is NOT OK, BUT module.exports = {myFunc: myFunc} is OK. Basically, I've decided not to use this pseudo-whatchamacalit "alias" type thing exports. I'll just use module.exports. Additionally, it is probably best to use the form:
module.exports.myFunc = function () {
...
};
for all exported functions inside ./my_module.js

Monday, August 22, 2011

Tuesday, August 16, 2011

Syncronous coding style with EventMachine and Fibers

I did this a while ago. I am not really happy with it. As I've said before. Event driven code doesn't bother me. Here is an example.

require 'fiber'
require 'eventmachine'

class AsyncIO < EM::Connection
  include EM::P::LineText2
  def initialize df
    @df = df
  end
  def receive_line line
    @df.succeed line
  end
end

def get_line
  f = Fiber.current
  df = EM::DefaultDeferrable.new
  df.callback { |line| f.resume(line) }
  EM.connect '127.0.0.1', 3000, AsyncIO, df
  return Fiber.yield
end

EM.run {
  Fiber.new {
    line = get_line
    puts line
    EM.stop
  }.resume
}

The truth is you should look at EM::Sychrony. Ilya Grigorik explains in he own Blog, how Fibers can help you write synchronous code while keeping the goodness of AsyncIO (ala EventMachine).

I don't find event driven code to be "callback hell" like Ilya Grigorik does. I find evented code easier to read than synchronous code sometimes. In Synchronous code you have to check every time if it failed and why. That is

if (rc < 0)
with
switch (errno) case EINTR:
code after every network call. In event driven code that stuff is dealt with in the event-loop and you just have to define the error callback once.

Ah well just use Node.js . If JavaScript event driven programming is "to hard" for your delicate sensibilities then explain to me how Millions of Web-monkeys pull it off everyday in the browser.

Friday, July 29, 2011

Morans! I am surrounded by Morans!

I posted a response on a blog recently. The fellow claimed, quite explicitly, that "Fibers and EventMachine were a response to Ruby's poor Threading performance". I responded with Fibers and EventMachine were not made in "response" to Ruby's Thread implementation. I am strangely polite in online discussions, where in person I'd have ripped this guy a new asshole.

I explained that Threads exist because n = read(fd, buf, len) blocks. Threads allow execute work to continue in parallel to blocked IO. That he had it backwards, event driven IO, like EventMachine, exist so a user-space program can continue to execute work while the IO finishes in the Kernel. While user-space programmers don't explicitly invoke the switching of one thread to another, context switching is not costless. In fact the cost of context switching is many hundreds of CPU instructions.

Relatedly, Fibers are cheap where Threads are expensive. Fibers switch into a parallel call stack, much like Threads, with the equivalent of a register switch and a long jump. Additionally, the ability to return results from a Fiber while preserving the Fiber's call stack state allow for remarkable new behaviors to be constructed that can not be done with out them.

It seems these Ruby coders one of two types: One, HTML monkeys that have learned how to code, or Two Java refugees that got tired of Bondage-and-Discipline style of programming. Both of these kind of MORANS, don't understand that Ruby is a remarkable Programming language with features not available in other languages. Neither Perl nor Java, have the concept that every variable is an object. Nor do either language have Fibers/coroutines. These features change the very nature of the code you write.

P.S.
I plan to post some code to show synchronous read/write IO calls while doing all the actual IO inside EventMachine. So you get the best of both worlds ala synchronous IO with out blocking. Stay tuned; same Bat Time same Bat Channel...

Saturday, July 23, 2011

Git and RSpec

I just watched a talk by Linus Torvalds at Google about Git. One of the questions touched on one of Linus' motivations for Git. That is Merging. I want to talk about how Git merging dove-tails nicely with Ruby's testing tool RSpec.

Some source control managers (SCMs) make a big deal about "branching" being cheap. Linus points out that branching is not the problem, merging is the problem people deal with. Git makes merging easy by removing the number of conflicts the developer has to deal with. It does this two ways. First is algorithmic and the second is how Git changes your workflow.

Git allows for, and relies on, three way merging. CVS/SVN by contrast only does two way. Three way merging diffs the original file and each of the two conflicting versions of that file. Git can do so because it stores the whole files, not just a long string of diffs (ala CVS/SVN which I'll just call SVN from now on). Three way merges allow the merge algorithm to look at the context of the text being diffed. SVN can only look at line 245 and see it changed. Git can notice that the line didn't change, it mearly moved. Say you and the conflicting file inserted a text before the same line 245. So there is no conflict just code motion in the file. Three way diffs see this, two way diffs can't.

The second way Git deals with merge conflicts is not as obvious; it stems from the work flow. Specifically, branching is inherent in Git's design and merging is easier and better. So you branch often and merge often. More to the point you start your branch from the central "master" branch for your feature add; change & commit a bunch of times to that small branch; then pull or push your change back into "master". By repeating this branch-change-merge-push cycle early and often you have less opportunity for merge conflicts. Put another way, your branch exists for less time and syncs with the central master more often, resulting in less opportunity for two people to introduce genuine conflicts.

So alot of talk is generated about Git working in a fully distributed way. However, that ignores that the Git, encourages syncing up those distributed merges early and often.

So imagine you replace SVN with Git. First you don't have to do it to your whole tree at once. You can do it by subsystem. Also there is Git-SVN gateway tools to help do this. You can still have the central tree ala SVN, but you just branch off it and merge back more often. In SVN you are usually doing this anyways. Each SVN commits end up being after the feature is completed; much like the final merge of a Git branch, but without all the Git commits in the mean time. Or you create a longer lived development branch and merge that back as a monster merge.

I've explored other SVN branching/merging workflows but all they do push the pain to a different part of the process. A smart colleague of mine called it "squeezing the balloon". What you need to do is keep the master branch stable. That can be achieved by branching and merging smaller and faster. The SCM (or VCS if you prefer) makes all the difference.

What also helps is having a test suite you can rely on. First the test suite has to be aimed at the internal API level. Second, it has to be easy and fast to run. This is where the choice of Test framework dove tails with the SCM choice. "Early and Often" is the catch phrase for both.

Testing the API's "contract" is where you should aim your testing framework. As a side note: you are forced to state what that "contract" is which is a level of internal documentation that often gets forgotten. The contract is what each function takes as input and what the results should be; especially the edge cases. Edge cases are given a function "sum" adds all the elements of an array, what if the function is given an empty array or a nil as input. So that is the trivial case. Then there is the out-of-bounds case, like each element of an IP address (dot-quad) is between 0(inclusive) and 256(exclusive). Correctness should be tested if you can. Most of the time, correctness can't be tested with out recreating the logic of the function or testing pre-canned input and results. But that leads of who-tests-the-tester (my favorite quote: "Qui custodiet ipsos custodes?")

Another variation of this "contract" is how it applied to methods of a object. Methods have input and return results, but they may alter the objects state. Input and result have to be tested as above, edge case and out-of-bounds case. But internal state? One internal state to test is internal consistency. Again there are edge cases of initialized(trivial states) and known inconsistent states.

RSpec is a good ruby oriented tool-set built explicitly to test the contracts in your APIs. What are other API test frameworks for other languages is left as an exercise for the reader :)

Thursday, July 14, 2011

Little Idiom of Ruby I like

h = Hash.new { |h,k| h[k] = [] }
h['foo'] << "a"
h['bar'].push "b"
puts h.inspect
outputs {"foo"=>["a"], "bar"=>["b"]}. In other words, we declare a hash with a constructor that sets each new key to have a value of a empty array. Otherwise, we would have to test each hash key to see if it was already initialized to an array, if not initialized we'd set that hash key's value to an empty array. It's a common thing to do, but Ruby makes it easy and automagic.

I suppose in perl you can rely on auto vivification.

push @{$h{'foo'}}, "a";
But as you can imagine the Ruby idiom can be generalized to more complicated initializations.

TextMate clone for winbloze

For anyone who may care there is a TextMate act-a-like called E Text Editor. I supports TextMate bundles and key strokes. I haven't used it. But I imagine it must be manna from heaven if you are a TextMate user banished to the wilds of Microsoft-land.

Wednesday, July 13, 2011

iTerm2 Does Not Suck

Ringing endorsement eh?

Well I've been using iTerm2 for a while instead of the default Terminal. Don't confuse iTerm2 with iTerm. While, I am confused about that, I haven't spent anytime figuring out the diff.

The first problem with iTerm was the colors. It has a very good color palate (MacOSX builtin I presume) and a option in the Pref panel that will send you off to a page of Preset Palets. I was happy to find one that approximated the MacOSX Terminal colors I had come to like. With that color pallet installed I moved over to my next issue.

AntiqueWhite background w/ black foreground. On a PC running Linux AntiqueWhite out of rgb.txt was fine. I entered the same RGB codes for AntiqueWhite into Terminal Prefs and was happy. Entered the same codes into iTerm2 Prefs and not so easy to find. But selected the Emacs pallet and AntiqueWhite2 seemed to give me the happys.

I am transitioning from Emacs, screen. Even my screen command control character is C-o not the default C-a, because, duh, C-a is beginning of line in Emacs. But screen doesn't do top-bottom splits. After a friend suggested iTerm2 I gave it a look then went back to Terminal/screen.

The big change came when I was writing very wide log lines to the terminal. I needed a terminal with full screen width. Given screen wouldn't give me top-bottom splits, I tried iTerm2 again. The commands were easy to learn ⌘-t for new tabs; and ⌘-[ and ⌘-] to go back/forth between panes; and ⌘-⇧-[ and ⌘-⇧-] to got back/forth between tabs.

The scrolling is easy: just mouse scroll up/down in the window; no worries about the lack of scroll bar.

All it all, I've definitely moved from emacs/screen to TextMate/iTerm2 and I think I am more productive because of all the little things I gain. I just feel like all the key strokes programmed into the nerves of my hands are being wasted. I don't even remember alot of the emacs commands. I just pull up emacs, do the command, and look at what my hands do. Then I can say "oh yeah. That's C-space hilite region C-x r t blah blah blah.

NOTE: the unicode characters above, ⌘ and ⇧, may not display correctly on non-Mac OS's. I found them on this page

Tuesday, June 28, 2011

Bye bye Emacs, Helloooo Sexy (TextMate)

If programming editors are a religion I am an Apostate.

While reading up on Ruby, I came across videos of people writing code real time. First, it is cool Ruby can do high level things in short programs. So short you can watch people coding real time. Second, more apropos, several different presenters were using this cool editor I'd never seen. I thought it was Vim with some crazy programming mode turned on. It completed statements and other coding constructs, speeding up the process of writing code.

This new editor was TextMate. It is a MacOSX app only. It has some simple bourne shell-like extension language. Or you can use any language you like. They come in "Bundles". Bundles exist for every language under the sun. Further Bundles exist for Version control systems. Checkin, checkout, update, branch, whatever. With windows to prompt for commit messages and the like.

The Git bundle allows you to switch branches real time. It even switches the files you have open in the editor. It has full colorization display windows for diffs and commit logs.

I have only scratch the surface of TextMate. You can start using it without having to buy into some IDE monstrosity like Eclipse. From what I can tell it rivals Eclipse or other IDEs for full Web Application development. Apparently it can run a full Web Application stack and support all the languages (Ruby/Python/Perl, HTML, CSS, and Javascript) side by side.

I haven't used it for so involved a dev environment. But I like how it allows you to start small and simple, then build up to the full stack development environment. From what I can tell this applied equally to (Configure, make, C/C++) or (Ant/Maven, Java, SWT) or (Rake, Ruby on Rails, Web) Application stacks.

I am still just playing with simple Project editing. My projects tend to be libraries and Server-side stuff anyways.

Tuesday, June 21, 2011

I took a look at perl5...

and found Modern::Perl. I always put use strict; use warnings; and such things in my code. use Modern::Perl; does more and is succinct. Apparently use 5.10; turns on say and the given ... when switch extension. There is a book about modern styled perl that is worthwhile for even experienced Perl programmers. It is the impetus of the Modern::Perl module. You can by the book or download an electronic version here.

I've always liked Perl. I found the blather about "line noise" and classes not compelling. Given the number of newbies using all this perl code, it can't be that impossible to read and write (though newbie code usually blows in any language). Classes are hard/complicated? The quantity and quality of CPAN code begs to differ.

I always thought that a switch was one of the features perl needed. An automatic line separator after each print statement is good. That it is short is even better. Two things come to to mind. One, Perl5 is alive and well. Second, what is left for Perl6?

To the second point, I answer, Grammers. I have looked at Grammers with wonder. Grammers provide a method to parse a full (programming) language. The key element that is hinted at is that each level of parsing provides a hook to attach code. So if people, say cpan authors, write a grammer for parsing C code and publishes it; then you can write code to use those hooks. The code is something like C::Grammar.parse($str, :$actions);.

If someone implemented Grammers in Perl5 there maybe no need for perl6.

'Nuff said.

Friday, June 10, 2011

Just compiled rakudo perl6. Perl6 is UGLY!

Simple things like getting the last element of an array have gotten grotesque. Perl5: $arr[-1]. Perl6: @arr[*-1] ughhh! I don't mind the '@' sigil; that change makes sense. But '*' in the index *-1 doesn't make sense on the face of it.

Why such a change? I didn't look deeper. It is such a non-intuitive change to such a common idiom.

Another seemingly unnecessary change: inline comments. The code goes $x = 1 #`(add one) + 1;. Why would I want to do that? In the 2+ decades I have been coding Perl professionally, I have never felt the need for inline comments. How does that help? How doesn't that obfusicate code?

Perl has a bad rep for being indistinguishable from line noise (or a cat walking on your keyboard). These two changes jumped out at me. They messed with the simple idiom for accessing the last n'th element of an array and added an unnecessary "inline comment" syntax that looks like more gobbleygook.

Supposedly, part of the design goals of perl6 was to make common things easier. So we have $obj.method() instead of $obj->method(); ok fine. And we have '$' for scalars always; '@' for arrays; and '%' for hashes to denote type rather than context. But what is that star '*' doing in the index of the array.

I was looking forward to Grammers as a very powerful tool. Talk about a text munging chainsaw! But some of these other changes are making perl6 very un-perl. Or rather, making perl6 indulge in the worst parts of old perl.

I haven't been paying much attention to perl since 5.8.1 . I hope someone has backported some Grammer-like construct it that is the case, then screw perl6!