28 October 2013

Bank Security Madness

This has probably been said by countless people before, but banking security is just mind bogglingly dumb.

Yesterday I phoned the NAB bank. Along with the usual questions I was asked to name a recent transaction. I couldn't recall one so I asked my wife who was standing next to me. The phone operator proceeded to tell me that I wasn't allowed to ask her because I was the person who needed to know the answer! NAB, if you make me communicate with my wife using a pen and paper instead, then you're not going to gain any security, you're just going to annoy customers.

The next thing that struck me was that the transaction used for authentication could be a debit. Now, generally speaking you don't need to do any authentication to put money into an account. Anyone can deposit into your account as long as they have the account number; thereby rendering this authentication method (as it stands) useless at best.

Today I phoned the ANZ bank. Their system is straight forward enough. I just need to know my Customer Reference Number, my telecode, my security code, and my web password. And I'd better well be able to remember which is which before I run out of attempts.

Authentication is a hard problem to solve, but surely we can do a bit better than this.

8 October 2013

Javascript dictionary using objects as keys

One thing that bugs me about Javascript is the inability to have a dictionary with objects as keys. Objects are dictionaries, but essentially toString gets called on anything you use as a key, which isn't always very helpful.

Typical solutions are to call stringify on each object, which is relatively slow and doesn't guarantee reference equality, or to have a custom hashing function, which feels like unnecessary effort. (The jshashtable library generally looks useful, but unless you provide the hashing function the performance drops considerably.

So my requirements are:
  • A dictionary that takes objects as keys
  • And will only resolve values using the same instance of the object (not just some string match)
  • Is fast
  • Without any custom hashing functions
It took a little while to realize that since the key is an object, the value can be stored directly on it, so long as we know which property the value got stored in. Job done. But because my poor head wants to deal with something like a traditional dictionary API, it can be achieved something like this:

function Dict() {
    Dict.id = (Dict.id || 0) + 1;
    this._prop = '_dict' + Dict.id;
Dict.prototype = {
    add: function(key, value) {
        key[this._prop] = value;
    contains: function(key) {
        return typeof key[this._prop] != 'undefined';
    get: function(key) {
        return key[this._prop];
    remove: function(key) {
        delete key[this._prop];

// Sample usage
var a = {};
var b = {};
var c = {};

var dict1 = new Dict();
dict1.add(a, 123);
dict1.add(b, 456);
var dict2 = new Dict();
dict2.add(c, 789);

alert(dict1.get(a));         // 123
alert(dict1.contains(c));    // false
alert(dict2.contains(c));    // true
alert(dict2.contains(c));    // false

OK, it needs a whole lot more work, but you get the idea. We keep track of a global ID so that a key can be used in more than one dictionary simultaneously. If we want to have some way to enumerate over the values or get a count, then we'd also need to store keys/values in the Dictionary itself. I'd probably go with a doubly-linked-list, otherwise add/removes would get slow.

The main disadvantage is that we are adding an extra property to the key objects, which may be undesirable in some circumstances. But overall it solves the requirements without too much mess.

23 September 2013

Using $q promises to run synchronous code asynchronously

The Q Javascript library provides a great way to handle the results of asynchronous tasks in a simple flexible manner. But the APIs required to actually generate and return promises for your own synchronous code are often a bit verbose, particularly if you want to catch and pass on exceptions as well.

Here's a convenient shortcut: Just call $q.when() with no arguments, then place all of your synchronous code (that you want to behave asynchronously) in a subsequent .then() call. This will automatically pick up any results, or exceptions, and pass them on as promises.

function myAsyncSqrt(value) {

  return $q.when()
    .then(function() {
      return Math.sqrt(value);
var promise = myAsyncSqrt(16);
  function(res) { alert('answer:' + res); },
  function(err) { alert('uh oh:' + err); });

30 August 2013

Allowing .Net unit tests to access internal members

Good code encapsulation requires that various members be marked as private, or at least internal. However this can make it difficult for unit test frameworks such as NUnit to access them.

You can grant an external (e.g. unit test) assembly access to internal members by doing the following:

  1. Give your test assembly a strong name (via Project Properties, Signing, Sign the assembly)
  2. Compile the assembly (eg. My.Test.dll)
  3. Open the Visual Studio command prompt
  4. Navigate to the folder where My.Test.dll got built
  5. Run:  sn -Tp My.Test.dll
  6. This will display the full public key for the signed assembly. Copy it. (it'll be about 320 chars)
  7. Open the AssemblyInfo.cs file for the assembly containing the code with internals to be tested.
  8. Enter a line such as: [assembly: InternalsVisibleTo("My.Test, PublicKey=1234")] where 1234 is the full key generated in step 6.
Note: this only works if the full key is used, not the shorter summary key.

19 August 2013

How to mock an Angular service for testing

To inject a fake version of myService, and intercept calls to myMethod, do something like this:

Or check out the cool video here.

    var myMethodFake = function() { ... };

    beforeEach(function () {
        module(function ($provide) {
            mockMyService = {
                myMethod: jasmine.createSpy('myMethod').andCallFake(myMethodFake)
            $provide.value('myService', mockMyService);

    it('does stuff', inject(function(myService) {

15 August 2013

Default IE XSLT for viewing XML

Being blogged just because it shouldn't have taken me nearly as long to figure this out as it did.

How to download the default XSLT template that IE uses for viewing XML. (The pretty looking one with collapsible/expandable elements):

  1. Use Visual Studio
  2. Click File | Open | File
  3. Open C:\Windows\System32\msxml3.dll  (because VS knows what to do with a DLL)
  4. Expand to: XML \ DEFAULTSS.XML
  5. Right-click and Export..
  6. Save it as an .xsl
All done.

18 March 2013

The Hard Problem of Consciousness

Personally I find the phenomena of human consciousness to be a powerful evidence that there is more to reality than the physical material world that naturalism is selling to us. Following is an attempt to gather and articulate my reasoning.

What is the ‘hard problem of consciousness’

David Chalmers introduced ‘the hard problem of consciousness’ as the internal experience that we perceive. “It is undeniable that some organisms are subjects of experience… Why should physical processing give rise to a rich inner life at all? It seems objectively unreasonable that it should, and yet it does.” Questions include: why do we experience colour, sound, emotions – as distinct from the physical questions of how we collect, transmit and process this information.

It is distinct from other problems of consciousness, which he calls the ‘easy problems’ (although non-trivial in themselves), such as creativity, learning, introspection, and so on. The hard problem focusses on experience – why we perceive anything at all. Whereas the other problems are all just about behaviours – the way the brain reacts to stimulus. They’re essentially just information processing problems: receive input, access memory, process, produce output.

The answer does not lie in physical matter

Clearly brains are made of atoms. A single atom has a (relatively) simple behaviour. Apply some stimulus, and it will exhibit a somewhat predictable result. Put a small number of atoms together and their limited behaviours combine to be collectively more complex. Exponentially. So it’s perfectly reasonable to expect that a brain-sized bag of atoms can exhibit behaviours at least as complex as the brain itself. But at the end of the day, actions within are still just like long causal chains of dominoes. Individual atoms are just reacting to the forces on them.

So what physical thing might be doing any sort of experiencing or perceiving? Physically, we still only have atoms. If a single atom has zero ability to experience, then neither does two or any number of atoms together. Regardless of how complex the structures, and how complex the behaviour, there is still nothing to do the perceiving.  If you have a whole stadium full of blind people, then corporately they still wouldn’t figure out whether the lights were on just by talking to each other. Chalmers suggests that maybe atoms do have their own simple experiential life - I'm far from convinced.

It should also be noted that the physical atoms – in the form of proteins and so on – that comprise the brain are being constantly refreshed, without apparent interruption to experience.

The answer does not lie in informational structures

It is often argued that experience must be an emergent property of the complex network of interconnected brain bits. However, I find this unconvincing. Informational systems still just produce behaviour. They can all still be distilled down to a Turing machine equivalent. (A Turing machine is the mathematical description of a computation process. Again: receive input, access memory, process, produce output.) Experience is not found at the logical level either.

A thought experiment: Physics tells us that only a finite amount of information can be packed into a space. What if we could capture a brain (or an entire person) into a set of bits. A complex algorithm could be devised to ‘simulate’ the brain on a Turing machine. It could then be converted to a universal Turing machine (bigger dataset, tiny algorithm). What are we left with: the entire logical structure of a functioning brain would just be a phenomenally long string of ones and zeros flipping on and off. It could still produce the same complex array of behaviours – but where is the ability to experience hiding in that string of bits? How does it perceive the colour blue?

A second: consider a constructed brain where it was possible to capture and log every logical input and output (along with its precise time and location) at each functional logical unit – as fine-grained as desired. Now rewire each functional unit so that it ignores its input and instead plays back from the log; and rerun it with the same stimulus. Every unit will give the same result as before, and present itself to the rest of the network in the same manner as before. It appears to run equivalently to the first run, even logically at the most granular level.  However, the entire execution is a fraud – just a play-back of a fixed stream of data, devoid of experience.

One question…

While we’re simulating brains, what might we get if we perfectly scanned and simulated a real brain? Would this demonstrate that experience derives from the physical? No. It may be observed to behave like the original brain, but we have no way of verifying if it is actually experiencing anything. After all, only the entity itself can be aware of its own experience. It may be what is often called a philosophical zombie – behaving, but not perceiving.

Natural or beyond

Whatever the solution to the hard problem may be, it is generally presented that the answer will be found without needing to invoke anything beyond the physical world that science is comfortable with. I find this to be circular reasoning. We are told that consciousness can be fully explained by the material world, because that is all there is. We are told that the physical world is all there is because we are not aware of any phenomena that cannot be explained by physical laws. Hmm.

To me, a much more satisfying answer is a dualist approach. The brain gathers information. It does a great amount of processing, and problem solving. But ultimately it has a non-physical element that is able to genuinely experience the data gathered by the brain. I call it a soul. But whatever it is, the problem is real, and I really don’t think it’s going to be solved with hand-waiving and a material reality alone. I’m not suggesting “we haven’t found an answer yet, so it is reasonable to appeal to the super natural”. Rather, I am arguing a case that there can be no answer in the natural alone.

The logical next question is ‘what good is an observing soul if it can’t influence the behaviour of the deterministic brain?’ That can be for another post.