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))

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? ?' ','_').titleize : 'Unnamed' %></h1>

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

class DressDecorator < Draper::Decorator
  def title
    dress.named? ?' ','_').titleize : 'Unnamed'

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

class DressesController < ApplicationController
  def show
    @dress =

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 = 'bar')
=> true
=> true
=> 'bar'

dd =
=> true
=> false
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

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 --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'

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

gpg --keyserver --send-key 5B640B9F9600F122

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

Philihp Busby


Raw Document


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 | 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 | 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:

To uninstall Pow, `curl | 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.

[ ~]$ 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:

# Disabling symbolic-links is recommended to prevent assorted security risks
# 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

innodb_buffer_pool_size = 1M


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

[ ~]$ 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;

Cache cache =
        .expireAfterAccess(7, DAYS)

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() {
    public V call() {
        return calculatedValue(key);

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

cache.get(key, () -> {

How to parameterize an RSpec shared context

I had a RSpec shared_context which was creating a FactoryGirl user mock and then logging in with it, and then running some shared examples for testing permissions on a generic user. I needed to modify it to accept a parameter of using a different user.

It originally looked like this:

RSpec.shared_context "auth" do
  let(:current_user) { FactoryGirl.create(:user) }

  before(:each) do
    allow(User).to receive(:find_by_id)
    allow(User).to receive(:find_by_id).with( { current_user }

  shared_context "logged in" do
    before(:each) do
      login_as current_user

In my spec files, it was included by doing this:

describe MyController do
  include_context 'auth'

  context "when logged in as a normal user" do
    include_context 'logged in'


However I needed MyController to override current_user and use an admin user instead. Rather conveniently, you can override a context by sending it a block.

describe MyController do
  include_context 'auth'

  context "when logged in as an admin" do
    include_context 'logged in' do
      let(:current_user) { FactoryGirl.create(:admin) }


This works because the let inside of the block given is called again, and the new block calls let(:current_user) again and overrides the original block and FactoryGirl.create(:user) is never called.

This is documented here, however they don’t really show that it can be used for making your shared_context parameterized. So I’m going to say the word parameterized a lot here, and hope that when I (or you!) google “How do I parameterize an RSpec shared_context?”, you find this post.

Weblabora, Sailing, and Portland

Hi friends. I’ve been learning a lot of things recently, but nothing cool enough to be worth an entire blog post of its own, so here they are.


I’ve been resurrecting Weblabora recently by abstracting out the game logic into a JAR and rewriting the front-end with more modern technology. The front-end is also open source on Github and will be hosted at Not much to see right now, but I am making slow and steady progress. The idea, this time, is to make it so that more games can be added relatively easily.

A JAR of the game library is published to Maven repositories is the first JAR I’ve published under the com.philihp group


Lately I’ve been learning how to sail. The other day in practicing man-over-board drills in a J/24 we spotted a watermelon floating in San Francisco Bay. We rescued it and ate it for lunch.



For the second half of 2015 I will be living in Portland, Oregon. That’s about all there is to say about that.