Thursday, December 7, 2017

Leaving twitter

So I killed my Twitter account (@bomoko).

In a few days, if the warnings are to be believed, my data will be gone for good.

Now, it's not like this is going to cause a major shakeup in the world. I'm nobody. I had only around 7000 tweets (which, when you think of it, shockingly, makes around a short novel's worth of writing), and nearly 500 followers.
Small beer.

But I think it's probably a good move. For me, at least.

On the public front, I think Twitter's refusal to really clamp down on bullying and hate speech is simply not right. They are a company, not a public utility, and so can choose to use their technology however they see fit.
They're a money-making machine and not a vehicle of social improvement or justice, and they're entitled to be that, but I don't have to contribute my words, my time, or my pageviews.

More privately, I've never really felt comfortable on twitter. I've met two or three good friends there, but I communicate with them via email now.
On twitter I feel like I'm at a party and everyone is cool, but I'm just a little out of step with the rest of them.
I don't have a problem with not fitting in, but I don't like the feeling that I'm trying to fit in (or the pressure to fit in).

So I'm going to be focusing more on this blog, submitting stories, and working on Open Source software. I want to build a body of online work, that's as thoughtful and as deep as I can make it, and I don't think twitter aligns with that.

So yeah.

See you around (here).

Wednesday, November 15, 2017

Generative poem: /usr/bin/diff

Source, Edit, diff

2,3c2,3
< or if time even makes sense
< anymore.
---
> before my next shift, but I
> had to say hi.
5c5
< investigate some signal found
---
> investigate tidal forces in binary systems
7c7
< Some regular beeping out of
---
> So we set up in orbit around
13,20c13,17
< that we clicked
< we were facing something indescribable, something terrible
<
< something like God.
<
< Something like Death.
<
< We're not coming home,
---
> that we clicked that
> we were faced with something entirely new
> something like waves.
> Something like sound.
> We're not coming home just yet,
22,24c19,21
< it hates us,
< and now
< it knows
---
> I miss you,
> and soon
> we'll be
26,27d22
<
< I'm sorry.

Wednesday, September 20, 2017

Lethaba DI Container

In my last post I wrote up some notes about reading the Pimple 1.x source.
At the end of it I mentioned I wanted to write a DI container myself.

Behold, Lethaba DI - a stupidly simple clone of Pimple.

A couple things - I decided against implementing the ArrayAccess interface and followed Laravel in making the container callable, so in order to grab something out of the container instead of this

$container['service'];

we go

$container('service');

But beyond that ... it's pretty much a clone.

Tuesday, September 19, 2017

Reading Source code for Pimple 1.x

I have huge respect for Fabian Potencier, the man is a code machine, and in addition to his work in open source, you have to admire his commitment to educating other devs (check out his "create your own framework" series).

Recently I was researching Dependency Injection and came across Pimple, Silex's (the microframework) DI container. There's a helpful note on the frontpage that tells us that reading the source for Pimple 1.x is a great way of learning how to write a simple DI container.
So I read it. Here are my notes.

Preamble - Dependency Injection


So why worry about DI generally? Well, good question, and one covered quite well in the Wikipedia article I've linked to above. For completeness, though (and for my own peace of mind) I'll give a quick take on it here.
Dependency Injection describes a pattern or technique that, if implemented, frees up your objects from having to worry about how their dependencies are created, and indeed, from creating them themselves.

Compare

Class A
{
    private $databaseConnection;
    public function __construct()
    {
         $this->databaseConnection = new \DatabaseConnection("server", "username", "password", "catalogue");
     }
    /** snip **/
}


In this first example (whatever other issues it has) our class A is tightly coupled to the \DatabaseConnection class. Our class can only ever use this kind of db connection (rather than say some specialized sub-class, or a mock while testing).
If the \DatabaseConnection class ever changes, say it needs a new parameter when it's instantiated, we'll need to change our class's own constructor as well (SRP, hi!).

The usual way of sorting this out is to pass through any objects that our own class might rely on ...

Class B
{
    private $databaseConnection;
    public function __construct(\DBConnectionInterface $databaseConnection)
    {
        $this->databaseConnection = $databaseConnection;
    }
    /** snip **/
}
Notice now we've loosened up our class's relationship to the DatabaseConnection class - when newing up our own class, we now simply pass through a DatabaseConnection object, and because we're coding to an interface, we can merrily use our $this->databaseConnection regardless of what actual class is passed through to us.

This seems to just push back our problem though, right? Isn't the code that goes ahead and creates the instance of our class B now responsible for creating the objects it's dependent on. And What if we create instances of B in more than one place? Surely the virtue of having a constructor is that we only really need to describe its set up in a single place? This is true, which is why the DI pattern exists.

Central to it is the idea of an injector, or--more commonly--a container (see the wikipedia article for the rest of the synonyms). The container represents a place where the creation of objects can be centralized. Rather than have our code, say, create new database connections in several places, we centralize the logic for creating databases in our container. If how we create a database connection changes, we only need to change that in a single place.
Not only that, if any of the objects in the container have dependencies themselves, the container will be able to manage them too - long chains of dependencies are resolved inside the container.

And this is what Pimple does - it's a DI container. We tell it how to create things like our Database connection, and then when we need one in our code, we just ask the container to give us one.

In our example, we could create a new instance of class B with our container doing something like ...

$b = new B($container['databaseConnection']);

or, in some cases it might be appropriate to have the container create our instances of our B class itself ...

$b = $container['B'];


The Code


There isn't much to Pimple 1.1. Just over 200 lines of code with comments and whitespace. It does a lot with a little though.
I'll be giving line numbers from here - so feel free to follow along.

ArrayAccess

First things, it implements (line 33) the ArrayAccess interface. If the name doesn't give it away, this interface lets our objects act as arrays, i.e. calling code is able to interact with the object using the square bracket syntax.

This let's us both put stuff in the container like this

$c['key'] = $value; //C1

and read stuff from the container like this

$value = $['key']; //C2

I'd be interested to know why Fabpot went this way. My guess is that the assignment side is made nice and clean.
Consider an alternative - putting something into the container with some kind of setter

$c->setValue('valueName', $value); //C3

I don't see this being a showstopper, but it's certainly not as concise as C1 above.
That's just a guess, though.

A lot of the functionality of the class is simply implementing the ArrayAccess interface (i.e. providing implementations of offsetExists, offsetGet, offsetSet, offsetUnset).

Defining parameters

I'm following the sections in the documentation here, looking at what kinds of things the service container can store, and seeing how this is achieved.
First off are parameters, these are just straightforward values. There's not much to be said about these - most of the work in the code is done to figure out when we're not working with parameters.

With parameters, the container is simply acting as an abstraction over the internal store (line 35).
It's important that the container be able to work with simple values without too much overhead because simple values are also part of the dependencies needed to create objects (in our DB connection example, things like the username and password may be considered parameters).

Having all our dependencies accessible through a common interface seems like good design.
This point about common interfaces will become clearer when we see the recursive nature of service definition next.

Defining services

Services are the heart of the DI pattern. Insofar as Pimple defines them, they're "Object[s] that [do] something as part of a larger system." Consider the case I described in the preamble - we want to create a DatabaseConnection service. This is achieved by passing an anonymous function to the container that knows how to create, and will return, the object type.

Our example might be something like

$containerInstance['DBConnection'] = function ($c) {
   return new \DatabaseConnection($c['server'], $c['username'], $c['password'], $c['catalogue']);
};

Pretty straightforward -- note, though, the argument $c that's passed to the function, that's an instance of the container itself! This is what enables the container to resolve any dependencies that a service might require (assuming that the dependencies are actually defined in the container - if not, expect errors).

The magic here comes in line 81, in the offsetGet() method, where we try pull the service out. We check whether the thing we're trying to pull out is an Object, and if it is, whether it's invokable. Recall that a php anonymous function just is an instance of a particular class (http://php.net/manual/en/class.closure.php), which is why that check works as it does.

If an invokable class is found, Pimple will call it and pass itself as as argument (for further dependency resolution, if required).

Shared services

Shared services act like a singleton (the Laravel container uses this terminology explicitly) - instead of returning a brand new object every time the service is requested, it'll create the object once, and return the same instance on subsequent calls.

You do this by adding running your function through the container's share() method before adding it, like so:

$containerInstance['DBConnection'] = $containerInstance->share(function ($c) {
   return new \DatabaseConnection($c['server'], $c['username'], $c['password'], $c['catalogue']);
});

This is where things start getting slightly more interesting - the share() function (lines 116-131) does the following:
First checks that what we've passed through is actually invokable (line 118, same logic as described above), throwing an exception if it isn't.

If it is, then it wraps it in a new anonymous function which makes use of a static variable to store the shared service object (i.e. whatever the anonymous function we pass in returns). When you use the static keyword inside a function, the variable declared as static does not lose its value after it's finished executing. This is dangerous, but really powerful (read more here).

Essentially, what the share() method does is check whether it has ever been run before (i.e. is the static variable null) and if it hasn't, it runs the function we've passed it and stores the result.
This is a fairly standard memoization pattern, less often seen in PHP than in the JS world, in my experience.

Protecting Parameters

You might've noticed a problem here. What if we want to store an anonymous function as a parameter? That is, what if we want to be able to retrieve a function from our container without the container running it? As it stands, whenever we drop an invokable into the container, it's going to be run with the container itself as an argument.
To avoid that, Pimple provides the protect() method (lines 142-151) - it's used the same way as the share() method and does the same kind of thing - wraps our function in another function, except, in this case, all the wrapping function does is return the wrapped function, rather than execute it.

Note that we can pull out functions from the container without them being executed by using the raw() method (lines 162-169).

Extending Services

The last little piece of functionality I want to cover is the mechanism used for extending services after creation. The idea here is that we might want to take the results / output of a service and modify it in some way before it's resolved/returned. This is achieved by, once again, wrapping functions within functions. In this case, we're taking both the original callable function and our extension and wrapping them up in a third.

Let's take the documentation's example of modifying a mail service:

$container['mail'] = function ($c) {
    return new \Zend_Mail();
};

$container['mail'] = $container->extend('mail', function($mail, $c) {
    $mail->setFrom($c['mail.default_from']);
    return $mail;
});

See that the function doing the extension takes two parameters, the first ($mail) being the original value of mail in the container, and $c which, as always, is the container instance itself.

Most importantly, how is this accomplished in the extend() method (lines 184-203)?
The meat of it all, after a few tests, lives on lines 200-202. Here, what's happening is that Pimple is taking the existing service and passing it and the extension function that we've defined to a new anonymous function via the "use" keyword (i.e. the new anonymous function inherits them from its parent's scope).
The cool thing about this is that extensions can be extended in this way indefinitely through a series of nested calls.

Next Steps


I was planning on writing my own DI container based on Pimple (as part of a larger project), if I do, I'll post the code up here too.

Sunday, September 17, 2017

Hello New Zealand

So the last few months have been hectic, to say the least.
Wanna know how to derail all your plans?
Move country.

But, here we are now living in the Shaky Isles down in Windy Wellington.

The move has meant that I've had to shuffle a few things around - but in terms of yearly progress, I haven't been doing too badly considering the massive upheaval.

I've managed to make a few contributions to FOSS (p5.js mostly).

I've also managed to get some, but not much, writing done - including a forthcoming story in Grievous Angel (which marks my 3rd pro-sale).

I'd like to resurrect this blog to some extent as well. I've been reading some really great stuff lately, both code and prose, and have been thinking that this is the perfect place to document what I've learned.

For instance, a couple months ago I read most of the source for the Slim Framework, something I heartily recommend, but I've misplaced my notes (in the move, no doubt) - so if I pop them all in my blog, I'll not only not lose them going forward, but perhaps, just perhaps, they'll be useful for others too.

Don't expect any unifying theme here, I'll just be capturing in blog posts what I've been reading, whether that be source code or short stories or philosophy papers.

Anyways - hi from New Zealand. Let's see if we can get some writing and coding done.

Tuesday, December 6, 2016

35 in review

35 has been interesting.

My plans for this year didn't quite pan out - but let's review, for completeness:

1 - PhD, finishing chapter 2. Nope. Work made it so that my PhD was basically stalled since about May.

2 - Publication of a philosophy paper - yep, it happened! Score! (more below).

3 - Learn a new programming language ... well, kinda.... I spent a lot of time this year playing with Processing and p5.js. So I guess that counts?

4 - 60K on my current WIP. Not quite, but I think what I ended up doing was a little better .... see below.

5 - FOSS contribution. Big fail.

Favourite technical books discovered

Sandi Metz' "Practical Object Oriented Design in Ruby" is just a fantastic book on OOD. I enjoyed everything about it and learned a ton. Highly recommended.

Dan Shiffman's "The Nature of Code" which is all about simulating natural phenomena using Processing. This book was extremely enjoyable - Dan is fun and smart and great at explaining things, which is a killer combination. The book is free to read online, but support him if you're able. 
I can't wait to see what he does next.

Favourite fiction

I did a lot better at reading more fiction this year, and I read some brilliant stuff. 

My two favourite books, though, were short story collections from my two favourite contemporary SFF writers.

Ken Liu's "The Paper Menagerie and Other Stories" was just top drawer stuff. The standout for me was "The Man Who Ended History" (read here - pdf) which I'd not read before, but which blew me away.

My other standout book was Kelly Link's "Get in Trouble". What can I say, really. It's Kelly Link, you can't argue with that.

Philosophy


Well, since my work has mostly come to a screaming halt, there's not much to say here.
But, one bit of good news was that I had my first publication with David Spurrett - our "Robots in Casinos" came out in the first half of the year - you can read the abstract here.


Work/Programming/Hacking

Work is going well - I've learned a lot of Laravel, shipped some ASP.Net apps, and am generally just trying to writer cleaner code. Happy.
I also had a lot of fun with Processing and p5.js. That's about the extent of it.

Writing

Well, this has been ... more successful than I could have hoped. Early on in the year I decided I should just focus on writing and submitting short fiction, a strategy that has really paid off.

I started the year off with my story "Revision Theory" being published in Nature (yes, that Nature).
This was a story with a lot of firsts for me. It was my first professional publication, the first publication of mine to be illustrated, and the first to be recorded (the good folks at Nature read it on their podcast). 

I then had my story "After the Reception" reprinted at the Sub-Saharan Magazine. Very, very cool.

My short story "Return to the Source" was published at Zetetic, which is a semi-pro venue I really love (the piece was written with them in mind).

My second pro publication was my story "Ndakusuwa" at Fantastic Stories of the Imagination, which is a publication I really love. They've put out some of my favourite contemporary writers, and I am honoured to have something there. 

Finally, my short story "Diaspora Electronica" has been shortlisted for the Short Story Day Africa 2016 prize. This was really unexpected and hugely humbling -- I'm listed with some great writers. It's more than I could have wished for. I'm truly honoured.
This story will appear early next year in the anthology "Migrations: New Short Fiction from Africa". I'll blog about it further then.

Plans for 36

There are some big personal upheavals on the horizon for me. I'll write about them later too. But given the chaos that 36 looks like it's going to be, I'm trying to not make too many plans.

I'm going to commit to two things.

First, to write and submit at least one story a month. Ideally, it would be two, but sending off one a month--if I'm happy with the final product--is fine.

Second, to continue to push myself professionally. I've been working really hard to become the kind of engineer I want to be. I've made a lot of progress, but there is still a lot to get done.

Here's to 2017.






Sunday, August 28, 2016

Publication: Return to the Source at Zetetic

I've got a new story out at Zetetic: A Record of Unusual Inquiry called "Return to the Source: being an account of the enlightenment of Wei San".

I wrote it specifically with Zetetic in mind, they're an online space for writers and poets to do things that they might ordinarily not, things that other markets might reject outright for being too unusual.
They deserve everyone's support - they're a great market.

I wrote and submitted this piece quickly -- probably too quickly because Zetetic's Managing Editor, George Wells, picked up and corrected at least two horrendous errors and still accepted the piece (thank you!).
I mention the speed of the composition not simply to excuse my errors in my draft, but rather to stress that if I'd thought about the piece for too long, I may not have submitted it at all.

My biggest worry was, and still is, the charge of cultural appropriation. It's clear that I'm both referencing Chinese culture and language as well as Buddhism.
The thing is, despite it's being a fairly simple little story, this is possibly the most personal thing I've ever had published - it is, in a way, a letter of appreciation to my friends and teachers, and it references them, it references my personal experiences. The cultural references are a part of that, a consequence of the context in which I learned about Buddhism. Had I learned about Buddhism from the people at the Lam Rim centre, or from the New Kadampa Tradition, the story would have been quite different. I must stress, though, that my invoking Chinese Buddhism, Ch'an, and the Pure Land are always with the utmost respect.

Story time.

When I was 19 a friend of mine leant me a copy of Paul Reps's "Zen Flesh, Zen Bones", a compilation of several important collections of Zen texts. I was deeply impressed by them. I'd never read anything quite like Koans, but I was deeply attracted to their playful paradoxical nature.
A year or two later, I attended my first meditation retreat. I hated it. HATED it. I was bored out of my mind and my legs and back hurt.
Forget meditation and forget Buddhism, I thought.

When I was around 25/26 I went through a pretty rough patch. From the outside, everything looked good, but inside I was struggling. No need to dwell on this part, but it was, up till that point, the worst period of my life, psychologically speaking.

One particularly bad evening, I went through all of my books to find anything that might help shake me out of whatever it was that I was experiencing. I came across my copy of D.T. Suzuki's "Essays in Zen Buddhism, First Series".

I had been studying philosophy via correspondence and had just finished up my first degree, so when I read Suzuki's discussion of how "Zen" solves the "problem of problems", it resonated with me. I'd been trying to think my way out of a hole, which clearly wasn't working, and Suzuki was offering what seemed to be an alternative approach,  namely that, a way of inquiry (insofar as "inquiry" is the right way to conceive of it in the first place) that "does not rely on the intellect for the solution of its deepest problems", but rather helps us try and see/experience our nature directly.
This was more than a decade ago, so I can't quite remember exactly what I thought I was after, and my understanding of all of this has changed dramatically in the interim.

I do remember that I felt that it offered me some hope, and I needed that.

My wife had been asking me to visit a therapist, but my previous experiences with psychologists hadn't been great (looking back, visiting a psychologist would have been the right first step). So I told her that I'd first try checking out Buddhism, doing it "properly" by throwing myself into it, unselfconsciously, without irony, to see if it would help.

To cut a long story short, it did help.

I went back to where I attended my first meditation retreat, Nan Hua, in search of someone to teach me about Buddhism and meditation. There I met my teacher, Venerable Hui Re. He agreed to help me.

Me (second from left) at Ch'an/Pureland study group with Ven Hui Re (far right)


Along the way, I learned a lot about Buddhism, about myself, about boredom and how important it can be, I made friends, I learned to enjoy really strange breakfast food combinations, I sat through many Dharma talks, I learned to prostrate properly, I learned why we prostrate. I learned about humility. I learned about faith. I learned about the Pure Land. I learned about what I could believe without giving up on rationality, and I learned that there are places where rationality can't help me.


I spent thousands of hours with my ass on this.

Return to the Source

I've been wanting to write a story about Nan Hua, Buddhism, my teacher, and my Dharma family for ages.

I was looking at my copy of John Daido Loori's "Riding the Ox home" and came across the following:


I thought it might be fun to take a swing at writing something that takes "the source" to be computer code, and the story fell out in a single sitting.

The long drive that Wei San takes is analogous to the long drives I'd take from Fourways to Bronkhorstspruit for our Sunday Morning classes. The frustration that Wei San feels when his teacher won't let him examine the machine is analogous to the frustration I felt when Master Hui Re -- who is a Ch'an master -- chose to teach us Pure Land Buddhism rather than the kind of thing I expected to study (Zen/Ch'an). Wei San, like me is a programmer, although I never snuck into the Buddha hall to take anything apart. Neither have I ever "attained enlightenment" (whatever that is, I think I've begun to see the wisdom in Seung Sahn's assertion that "wanting enlightenment is a big mistake").

I've clearly tuckerized my teacher's name. But also my own.
On New Year's Day, 2009, I took refuge in the triple gem, where I was given my Dharma name, Wei San1.

Me (second from the left in the second row) at my Precepts ceremony, January 2015.

Notes:
1. Hey, I couldn't let the idiot protagonist be anyone else right?