Brew install Estonian e-Residency ID software

Assuming you have Homebrew installed, tap this cask and install via the following commands

brew tap homebrew/cask-eid
brew cask install eid-ee

That’s it.

Testing a Redux Connected Component with Thunk Actions with Enzyme

Let’s say you’ve got a React component connected to a Redux store

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { saveColor } from '../actions/save';
import ColorButtons from '../components/ColorButtons';

const ColorButtons = ({ colors, onClick }) => (
  <div>
    {colors.map(color => {
      <button type="button" key={color} onClick={onClick(color)}>{color}</button>
    })}
  </div>
);

ColorButtons.propTypes = {
  colors: PropTypes.arrayOf(PropTypes.string),
  onClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  colors: state.colors || [],
});

const mapDispatchToProps = dispatch => ({
  onClickColor: color => () => {
    dispatch(saveColor({ color }));
  },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ColorButtons);

Which calls this action creator.

export const SAVE_COLOR = 'SAVE_COLOR';
export const saveColor = ({ color }) => ({
  type: SAVE_COLOR,
  color,
});

Everything works great in your smoke tests. How do you write unit tests for this? One way would be to expose mapStateToProps and mapDispatchToProps by exporting them (see jsramblings.com). This is indeed smelly, though Redux documentation suggests doing something similar, but this is something I disagree with, because your tests now assume that connect will be called on the exposed internal. What if the signature for connect changes? What if someone makes a change that messes with what’s passed to connect()? That’s now untested.


Why even testĀ it?

It is not necessary to test that our mapDispatchToProps is properly passing a function (login, submit, click etc.) to the connected component, because Redux is already responsible for this. [willowtreeapps.com]

I disagree with the above quote. It is true that Redux is responsible for it, and we make an assumption that it will continue to function properly. Tests are meant to outsource the cognitive load of maintaining assumptions after every change and library upgrade. What happens when we upgrade Redux, and they change the signature of connect()?

We have A → B → C, and B is private. They suggest exposing B, and testing B → C, but instead we should have a test that A → C.


I prefer actually rendering the component, and checking to make sure it still connects as expected. This is not an expensive test.

import React from 'react';
import { shallow } from 'enzyme';
import configureStore from 'redux-mock-store';
import ColorButtons from '../ColorButtons';
import { saveColor } from '../../actions/save';

const buildStore = configureStore();

describe('ColorButtons', () => {
  let store;
  let wrapper;
  const initialState = { colors: ['red', 'blue'] };

  beforeEach(() => {
    store = buildStore(initialState);
    wrapper = shallow();
  });

  it('passes colors from state', () => {
    expect(wrapper.props().colors).toBe(initialState.colors);
  });

  it('can click yellow', () => {
    const color = 'yellow';
    wrapper.props().onClick(color)();
    expect(store.getActions()).toContainEqual(saveColor({ color }));
  });
});

The first test checks to make sure the array available to wrapper.props() is the same array as that one stored in initialState.colors.

The second test makes sure that the store gets an action dispatched to it. It’s not necessary to check to make sure the store digested and reduced the action into the state; you’re not testing the reducers here.

What if the component calls a Thunk action?

This will work for about 20% of your components, but if you ever want to call some async action, you’ll probably dispatch a thunk action. That is, some of your actions will instead return functions that take dispatch. From the connected controller, they look the same, but the action looks slightly different. Say our mapDispatchToProps now looks like this contrived example

const mapDispatchToProps = dispatch => ({
  onClickColor: color => () => {
    dispatch(storeColor({ color }));
  },
});

And the actions now look like this

export const saveColor = ({ color }) => ({
  type: SAVE_COLOR,
  color,
});

export const storeColor = ({ color }) => dispatch => {
  dispatch(saveColor());
  return axios.patch('/api/color.json', { color })
    .then(response => {
      // another dispatched action maybe?
    });

If you tried to test this as-is, you’d get the error

Actions must be plain objects. Use custom middleware for async actions.
  26 |   onClick: color => () => {
> 27 |     dispatch(storeColor({ color }));
     |     ^
  28 |   },
  29 | });

Actions must be plain objects. Use custom middleware for async actions.

This is because your test’s mock-store isn’t configured with Thunk middleware. Configure it like this:

import React from 'react';
import { shallow } from 'enzyme';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import ColorButtons from '../ColorButtons';
import { saveColor } from '../../actions/save';

const buildStore = configureStore([thunk]);

describe('ColorButtons', () => {
  let store;
  let wrapper;
  const initialState = { colors: ['red', 'blue'] };

  beforeEach(() => {
    store = buildStore(initialState);
    wrapper = shallow();
  });

  it('passes colors from state', () => {
    expect(wrapper.props().colors).toBe(initialState.colors);
  });

  it('can click yellow', () => {
    const color = 'yellow';
    wrapper.props().onClick(color)();
    expect(store.getActions()).toContainEqual(saveColor({ color }));
  });
});

Now your test will dispatch just fine. Ship it!

Removing the First Instance of an Element from a ES6 JavaScript Array

To build upon Marius Schulz‘s approaches to removing from an array, if you want to remove the first instance of an element in an array, and you don’t want to mutate it but instead return a new array (because perhaps you want your React components to update), use a slice.

function removeFirst(src, element) {
  const index = src.indexOf(element)
  if (index === -1) return src
  return [...src.slice(0, index), ...src.slice(index + 1)]
}

This will give a new array every time.

const src = ["a","a","a","b","b","c"];
removeFirst(src, "a") // "a,a,b,b,c"
removeFirst(src, "b") // "a,a,a,b,c"
removeFirst(src, "c") // "a,a,a,b,b"

This might seem wasteful, but now you can depend on the identity of the response to change if the array itself changed. If they’re the same, and you pass this in as a property to a React component, the component knows it doesn’t have to change.

const src = ["a","a","a","b","b","c"];
removeFirst(src, "a") === src // false
removeFirst(src, "b") === src // false
removeFirst(src, "c") === src // false
removeFirst(src, "x") === src // true

Prefer `if object.present?` over `if object`

So you’ve got a controller method

class DressesController < ApplicationController
  def show
    @dress = Dress.find_by(params.permit(:id))
  end
end

And a view

<div class="<%= dress ? 'dress&.status' : '' %>">Status Indicator</div>

Looks good! Works great! Now your app grows, and you have a lot of other views that use the dress. Long after your view has been forgotten, and there’s no clear owner because everyone owns it, but that’s cool because it’s regarded as stable, someone comes along and builds another view

<h1><%= dress.named? ? dress.name.gsub(' ','_').titleize : 'Unnamed' %></h1>

Ew gross, so much logic in the view? Gross! Let’s put that logic in a decorator!

class DressDecorator < Draper::Decorator
  delegate_all
  def title
    dress.named? ? dress.name.gsub(' ','_').titleize : 'Unnamed'
  end
end

delegate_all will forward all methods it's sent to whatever it's decorating.

class DressesController < ApplicationController
  def show
    @dress = DressDecorator.new(Dress.find_by(params.permit(:id)))
  end
end

And let's clean up our view.

<h1><%= dress.title %></h1>

But now @dress will always be there, even if it decorates nil, so our old code is broken, and will return

NoMethodError (undefined method `status' for #<DressDecorator:0x00007fbc2696d568>)

Because of this, it's always important to code your intention, rather than code to save keystrokes. Use dress.present?, because that's what you're checking, even though it's the same as dress right now.

<div class="<%= dress.present? ? 'dress&.status' : '' %>">Status Indicator</div>

In other words, watch out for this...

d = Dress.new(foo: 'bar')
!d.nil?
=> true
d.present?
=> true
d&.foo
=> 'bar'

dd = DressDecorator.new(d)
!dd.nil?
=> true
dd.present?
=> false
dd&.foo
Traceback (most recent call last):
NameError (undefined local variable or method `foo' for main:Object)

R2: The Infinite Composer

For the San Francisco Stupid Hackathon, I wrote a program that would convert your keystrokes and mouse clicks into random tones. It was inspired by nbeep, and I wrote it in a few hours having absolutely no idea what I was doing beforehand. It turns out, macOS programming is a lot like iOS. Neat!

It can be installed with:

brew cask install philihp/casket/r2

Postmortem: What did I learn? It’s actually very difficult to build something like this. Even my own brain was trying to trick me into making something useful.

More info

Transitioning PGP Keys

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1,SHA512

2016-11-06 05:25:00 +0000

I am replacing my old DSA-1024 key with a stronger RSA-4096 key. The primary
motivation is to store my key on a Yubikey Nano which doesn't support DSA,
however there is a possibility that the old key has been compromised. Although
I don't have any evidence to suspect this, I certainly haven't been as careful
over the years as I could have.

The old key was:

sec 1024D/1209F481 2010-05-24
Key fingerprint = 093B A359 D87C E901 9AAE ACDF BF99 B090 1209 F481

And the new key is:

sec 4096R/5B640B9F9600F122 2016-02-29
Key fingerprint = 427E 0329 39DB 40F2 9D03 D80F 5B64 0B9F 9600 F122

To fetch the full key from a public key server, you can simply do:

gpg --keyserver pgp.mit.edu --recv-key 5B640B9F9600F122

If you already know my old key, you can now verify that the new key is
signed by the old one:

gpg --check-sigs 5B640B9F9600F122

If you don't already know my old key, or you just want to be double
extra paranoid, you can check the fingerprint against the one above:

gpg --fingerprint 5B640B9F9600F122

If you are satisfied that you've got the right key, and the UIDs match
what you expect, I'd appreciate it if you would sign my key:

gpg --sign-key 5B640B9F9600F122

Lastly, if you could upload these signatures, i would appreciate it.
You can either send me an e-mail with the new signatures (if you have
a functional MTA on your system):

gpg --armor --export 5B640B9F9600F122 | \
mail -s 'OpenPGP Signatures' philihp+signature@gmail.com

Or you can just upload the signatures to a public keyserver directly:

gpg --keyserver pgp.mit.edu --send-key 5B640B9F9600F122

Please let me know if there is any trouble, and sorry for the
inconvenience.

Jolan'tru,
Philihp Busby
-----BEGIN PGP SIGNATURE-----
Comment: http://keybase.io/philihp

iEYEARECAAYFAlgev3IACgkQv5mwkBIJ9IFQ0wCfThA3ak97QRVkgCDuFPDKNZfg
lJEAn0ANZrQsLZU2eBatwqXp89V2YJwViQIcBAEBCgAGBQJYHr9yAAoJEFtkC5+W
APEiqJgP/jUuel2Wf9/uf5AnghP7Qm55niGxCJKGc2+QYUUyzyKKTddcZNkfAqLe
Z4mtMelH2uVppU9KxLfe8aQCfXmY6iijJh2Hqreq0/T/F5pEzCQc5J5d/AcEI4PL
Lb3U8X1nIay7YeFtfqKHSFe06AbK1Bn6viMNHP4mVLqkw5S8A3+umFsTyq7ekfuq
sMZx1uppcjVrxAi4fbHQ5bYWf50aH7C+g2OISFOpTmbdgH7M3B+dTNuJ4TJrvvh6
4NPPglcnHlcBDUVZVFdL4f26Ig7OhGdvoCnBPE+vET8+D9qHpAdsgho5iMFpgp3x
erOQYFm4DvWx+HqdplhnWNpRH9PjjxOKy+14bCGbAurgytTJlACJReuQuVDW1yzU
y3xvKfMPheU6x4o9Px1X6ldhKn/lXwUW7z0wJxxzoCS8rveRF6pUwZhRWjaP5JuX
INIVxByiY9JLXeuImKpiV4UQ0IvYK7McKN9TiVpIYe9YRYn7I6miYf+BPTZmtBOr
qz72V8HwPjrrF+24QANL3wYIIsV2vVL2Lm60TkKt6qfkDXgO841pWGHY9IrPaSVA
S3YF5n/b/rFYx/k8AD7Na8uWS61d996pSn0vBkv8j6ReKlGuuKIxa60yTrNpnlmV
m22Y/8DtgN07K5zulcvD+KcZecPS47TlxspCPpQwzu1bsaCRBScQ
=DWIc
-----END PGP SIGNATURE-----

Raw Document

Why?

Error: ENOENT when installing Pow on macOS

I kept getting this error when installing pow on macOS. There are some old threads about it, with fixes for previous verisons of OSX prior to El Capitan, but for the most part it seems to be a solved bug.

philihp@sterling ~$ curl get.pow.cx | sh
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  9039  100  9039    0     0   8763      0  0:00:01  0:00:01 --:--:--  8767
*** Installing Pow 0.5.0...
*** Installing local configuration files...
*** Installing system configuration files as root...
Password: hunter2

/Users/philihp/Library/Application Support/Pow/Versions/0.5.0/lib/command.js:20
      throw err;
            ^
Error: ENOENT, open '/tmp/pow.98645.1466285627293.3185'

If you’re getting this error too, perhaps the solution will be similar to mine?

It turned out that I had at some point changed the default shell of my root user to /usr/local/bin/fish, then uninstalled fish, and never bothered to set it back. I guess this isn’t really a problem most of the time because not much should (hopefully) ever run as root, but it finally surfaced here when trying to install Pow.

My solution was the following:

  1. Enable the root user with dsenableroot
  2. If you try to sudo su, you will get something like su: /usr/local/bin/fish: No such file or directory
  3. Change root’s shell with sudo chsh -s /bin/sh
  4. Disable the root user with dsenableroot -d

Once I did this, installing worked as normal.

philihp@sterling ~$ curl get.pow.cx | sh
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  9039  100  9039    0     0  17142      0 --:--:-- --:--:-- --:--:-- 17151
*** Installing Pow 0.5.0...
*** Installing local configuration files...
*** Starting the Pow server...
*** Performing self-test...
*** Installed

For troubleshooting instructions, please see the Pow wiki:
https://github.com/basecamp/pow/wiki/Troubleshooting

To uninstall Pow, `curl get.pow.cx/uninstall.sh | sh`

Class ‘foo’ has no initializers

Quick post. It’s been a while. I’m just starting out with Swift, and this error kept coming up for me, but the error message could be a little more descriptive. It means that you have a non-optional member variable that needs to be initialized somehow.

class Foo: NSObject {
  var bar: String
}

That block will fail, saying Class 'Foo' has no initalizers. It isn’t that you need an init custructor, it’s that other things will depend on bar being set, and Swift doesn’t know what value to give it. This can be fixed by making bar optional, and anything using bar will have to handle the case where it’s missing

class Foo: NSObject {
  var bar: String?
}

or by giving it an initial value, so anything using it will either get its value, or (in this case) an empty string

class Foo: NSObject {
  var bar: String = ""
}

Configure MySQL on AWS t2.micro Linux AMI

I moved my blog over to an AWS VM, because I get 12 months of a free t2.micro instance. Can’t beat free hosting for a year, right? And about $10/month after that, on my own private virtual machine. Assumed things were going well, but I came back a few weeks later to find everything had gone to hell. WordPress was not connecting to the database.

[philihp@philihp.com ~]$ sudo service mysqld start
Starting mysqld:                                           [FAILED]

In looking at my /var/log/mysqld.log file, I found

160120 21:49:58 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
160120 21:49:58 [Note] /usr/libexec/mysql55/mysqld (mysqld 5.5.46) starting as process 27540 ...
160120 21:49:58 [Note] Plugin 'FEDERATED' is disabled.
160120 21:49:58 InnoDB: The InnoDB memory heap is disabled
160120 21:49:58 InnoDB: Mutexes and rw_locks use GCC atomic builtins
160120 21:49:58 InnoDB: Compressed tables use zlib 1.2.8
160120 21:49:58 InnoDB: Using Linux native AIO
160120 21:49:58 InnoDB: Initializing buffer pool, size = 128.0M
InnoDB: mmap(137363456 bytes) failed; errno 12
160120 21:49:58 InnoDB: Completed initialization of buffer pool
160120 21:49:58 InnoDB: Fatal error: cannot allocate memory for the buffer pool
160120 21:49:58 [ERROR] Plugin 'InnoDB' init function returned error.
160120 21:49:58 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
160120 21:49:58 [ERROR] Unknown/unsupported storage engine: InnoDB
160120 21:49:58 [ERROR] Aborting
160120 21:49:58 [Note] /usr/libexec/mysql55/mysqld: Shutdown complete

The important thing here is InnoDB: mmap(137363456 bytes) failed; errno 12.

It looks like it couldn’t allocate the memory, which makes sense because a t2.micro instance only has a gig of RAM. Ought to be enough for anyone, right? Not for MySQL! The way to fix this is to open up your /etc/my.cnf file, and add a param innodb_buffer_pool_size = 1M (something reasonable). If you haven’t made any other changes, it should look similar to this:

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mysqld according to the
# instructions in http://fedoraproject.org/wiki/Systemd

innodb_buffer_pool_size = 1M

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

Now if you start MySQL back up, everything should be fine.

[philihp@philihp.com ~]$ sudo service mysqld start
Starting mysqld:                                           [  OK  ]

Using Java 8 Lambdas with Google Guava Caches

With Guava, you can define a simple in-memory cache with

import static java.util.concurrent.TimeUnit.DAYS;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

Cache cache =
    CacheBuilder.newBuilder()
        .maximumSize(100000)
        .expireAfterAccess(7, DAYS)
        .build();

With this you can use .put(K, V) to load values, and .getIfPresent(K), which returns null if the key isn’t present. Sometimes it’s more convenientĀ to use get(K key, Callable<? extends V> valueLoader), where the valueLoader is called on a cache miss, and populates the cache and gives you what a cache hit would have given you. The old Java 7 way of doing this was really ugly:

cache.get(key, new Callable() {
    @Override
    public V call() {
        return calculatedValue(key);
    }
});

Don’t write ugly code. With Java 8 Lambdas, just do this:

cache.get(key, () -> {
    calculatedValue(key);
}