Winter in Yosemite

A few weeks ago I had a chance to go winter camping in Yosemite. I ended up camping in almost the same spot I did last time, except starting the hike at the Badger Pass Ski area saved me about 4 miles of hiking.

The overnight temperatures barely got below freezing, so it was pretty warm.

The hike out was great, the views were beautiful, but I have to say it… winter backpacking is a bit boring. It got dark around 5:30 giving me hours and hours to kill in the dark before bedtime. I ended up going to sleep at 7 or so, which meant I slept like shit.

Aw well, snowshoeing was a blast, the views were unimpeachable, and I got to use my winter tent for the first time in years. Not all bad.



Flatten Nested Lists in Prolog

A follow up to my last post, here’s how you flatten a list in prolog.

% Base cases, empty lists match empty lists
flatten([],[]).

% Pick the head and tail out of a list
flatten([H1|T1],L2):-
  % Try and flatten the head, if it fails (because the head is not a list), wrap that element in a list).
  (flatten(H1,H1Flat); H1Flat = [H1]),
  (flatten(T1,T1Flat); T1Flat = [T1]),

  % Join our two flattened lists together
  append(H1Flat,T1Flat,L2).

An Annotaed Solution to the Prolog Zebra Problem

My solution is the simplified Zebra problem from this SWI-Prolog tutorial.

Here’s the problem statement:

There is a street with three neighbouring houses that all have a different colour, namely red, blue, and green. People of different nationalities live in the different houses and they all have a different pet. Here are some more facts about them:

  • The Englishman lives in the red house.
  • The jaguar is the pet of the Spanish family.
  • The Japanese lives to the right of the snail keeper.
  • The snail keeper lives to the left of the blue house.

Who keeps the zebra? Don’t work it out for yourself: define a predicate zebra/1 that tells you the nationality of the owner of the zebra!

% Define a toLeft predicate
% Succeeds if the list contains the sublist H1,H2 at any location
toLeft(H1,H2,[H1,H2|_]).
toLeft(H1,H2,[_|T]):-
  toLeft(H1,H2,T).


zebra(Who):-
  % We have a street of length 3
  length(Street, 3),

  % The street will have an Englishman's red house and a Spaniard with a pet Jaguar
  member(house(english, red, _), Street),
  member(house(spanish, _, jaguar), Street),

  % The Japanese house is to the left of the snail house
  % The blue house is to the left of the snail house
  toLeft(
    house(_,_,snail),
    house(japanese,_,_),
    Street
  ),
  toLeft(
    house(_,_,snail),
    house(_,blue,_),
    Street
  ),

  % We're looking for who owns the Zebra, so create that rule here
  member(house(Who,_,zebra), Street).

“your system has run out of application memory” on macOS Tahoe

I’ve been getting occasional “your system has run out of application memory” since I upgraded to macOS Tahoe. I’ve casually tried to fix it, but hadn’t found any good solutions until now.

The main clue: mds_stores using much much more memory than any other process. The solution: the caches this process is building became corrupt at some point during the macOS 26 betas and now the process just can’t get over that hump to finish them up. The solution is to delete the stores.

sudo mdutil -X /; sudo mdutil -X /System/Volumes/Preboot; sudo mdutil -X /System/Volumes/Data

After running this restart. Boom, no more out of control mds_stores.

Thanks to ZodiacPigeon on Reddit for the secret command.

Selecting the most recent non-blank value in Numbers

Stephanie is running an ultra in Wisconsin this weekend, I wanted to track her progress and give myself an idea of her pace and when I could expect her to complete the next segment.

Here’s the numbers table I setup:

As each split comes in, I add her new pace and time and everything updates. The only tricky bit is that my “estimate time” calculations depend on the most recent pace value; I expect she’s going to slow down significantly over 100 miles. Here’s the formula I ended up using:

INDEX($'Actual Pace m/mi',MAX(IF(ISBLANK(Stephanie’s Progress::$C$2:$C$13),0,ROW(Stephanie’s Progress::$C$2:$C$13))))

Let’s break it down:

IF(ISBLANK(Stephanie’s Progress::$C$2:$C$13),0,ROW(Stephanie’s Progress::$C$2:$C$13))

If a value is blank, return 0, else return the row number.

INDEX($'Actual Pace m/mi',MAX(...))

Whatever the max row number is, use INDEX to fetch the value at that row.

Pretty straightforward! The only thing that made this so difficult is that there’s inconsistencies in the way that Numbers formulas handle named column references, which caused my IF statement to try to fetch values out of bounds of the column. Hence me needing to use Stephanie’s Progress::$C$2:$C$13 in a few places.

The Dodge Hornet is the worst car I’ve ever driven

I rented a car this weekend and I tried the Dodge Hornet. This car is ass, it’s bad in ways I didn’t know a car could be bad.

Bad Quality

Granted, this was a rental car, so maybe it’s seen more abuse than a family car, but the interior was falling apart. The vent controls had been snapped off, the brackets in the hatchback that lift the trunk cover were broken, the trim on the rear window was falling off and would loudly flap in the wind at highway speeds.

The car felt like it was made entirely of chintzy plastic that would fall apart the minute it drove off the dealer’s lot.

Bad UI

The software in this car is BAD, which is especially frustrating because it’s all digital displays, so they could have fixed all these problems long after the physical design was done. The displays all feel like they were designed in an office with no affordances for how the car would actually be used.

Some examples…

The car beeps when you exceed the speed limit. As anyone that has driven a car before knows, this means the car is constantly beeping at you. Even more aggravating, if you are in heavy traffic the car will just beep once a minute as you move with traffic. It’s annoying and doesn’t solve any problems.

This car is a plug-in hybrid, which means you can fill it with gas or charge it. The charging port is on the driver’s side, the gas is on the passenger side. There are dual gauges to monitor charge and gas and the charge dial is on the passenger side and the gas gauge is on the driver’s side. It’s the exact opposite of where they are on the car. This is confusing and unnecessary.

The car has bluetooth CarPlay, which actually works great! The screen is high resolution and the Apple interface looks better than any other car I’ve ever driven. THAT SAID, the CarPlay UI is far too small. The application icons are about the size of the tip of my pinky, which means switching between maps and music requires you to concentrate and carefully jab the screen in exactly the right spot. I can’t imagine what a nightmare this would be for someone with fine motor control issues or the elderly. UI like this in a car should be illegal. It’s dangerous and irresponsible.

Like I said, this is car is hybrid. It’s also a “sports car” so it comes with a tachometer. The interface is all digital, so the designers had some fun with fluid animations, glowing effects on the dial, some “carbon fiber” backgrounds. I bet it looks fantastic on the designer’s laptop. In practice, an animated tach on a hybrid is dumb as hell. During regular driving, the engine is regularly shutting off while coasting or braking. Which means that cool-ass animated tachometer is constantly dropping to 0, then shooting back up to 3k with a little burst of animation and color. Having your instrument panel go nuts every few seconds is distracting. Every time I looked down at the gauges, they looked fine. I knew something important had happened because I saw the flash of color out of the corner of my eyes, but it took a few hours of driving before I caught the tach in the act of turning-off-turning-on and realized what was going on. This was dumb as hell.

Bad Physical Controls

At the very start of my drive I was all ready to rant about how there is no physical volume control nob for the stereo. Turns out there is a nob! It’s inexplicably located in the upper-right-hand corner of the gear selector panel between the front seats. Which, conveniently for me and where I set my seat hight, is exactly blocked from my vision by the gear selector. At some point I got tired of reaching around the gear selector to twiddle a dial I couldn’t see, so I started adjusting the volume from the steering wheel, which brings me to my second gripe…

The buttons on the steering wheel are inset. This means you can’t slide your finger over the buttons to feel for their edges, you’ve got to lift your thumb up and jab inward to hit the buttons. I only drove this car for 6 hours, but at no point was I comfortable just tapping the buttons without looking, I had to look nearly every time. This is aggravating and dangerous.

Speaking of the steering wheel controls, there is a small rotary nob on the right side. This nob is used to change the instrument cluster display, so if you want to display your speed in a large font or engine performance or whatever, that’s how you change it. However, in order to change the instrument cluster you’ve got to enter the instrument cluster mode, which is indicated by tiny 12-pt font at the bottom of the main screen. If you don’t correctly enter this mode that same rotary knob controls next and previous tracks for your music. Also, it’s a rotary nob, so if you give it a spin, you just skipped the next 5 tracks. Nobody has ever wanted to do this. 99% of the time I only want to skip a single track, which means every time I use that dial I’ve got to carefully roll it over once to make sure I don’t skip too many tracks.

Finally, the turn-signals are ass. Doug DeMuro rants about them a bit here. All other turn signals I’ve used can either be lightly held down for changing lanes, or locked all the way down for making a full turn. These stalks don’t lock down. The car tries to figure out if you’re just changing lanes or making a turn and will act appropriately. However, the car is not good at this. I frequently had my turn signals stay on after completing a turn. You have to manually turn them off by moving the stalk in the opposite direction, which may turn the signal off or may turn your other signal on. It’s infuriating and unnecessary.

Everything was buggy

Sometimes the parking brake would turn on automatically when parking, but then stay on when you tried to drive. You can tell this is happening because the rear tires squeal as they skid down your driveway.

The side-view mirrors fold in when you use the key to lock the car, but they don’t unfold when you use the RFID key proximity sensor to open the doors. They don’t always unfold when you start the car. At one point I started the car then got out of the car and that caused the mirrors to unfold.

I never did get the battery to charge. I even got out the owners manual to see what setting I was supposed to change. Everything was set correctly as far as I could tell, but no battery charging. I haven’t yet filled up with gas, but the car also seemed to use more gas than I was expecting, probably because a hybrid without a battery is mostly just a shitty gas car.

I am now tracking you

I just added Umami tracking to the blog. I can see what pages people are visiting, where they are coming from, and how they browse through the site.

No identifiable information is collected, no cookies are set, and all the data is compliant with GDPR and CCPA regs. I just want to see how people are finding these pages, and if any of them are getting action!

Weekend Trip to Yosemite

Last weekend was my birthday and I was able to get a last-minute backcountry pass for the Pohono Trail (starting at Glacier Point). Since this was a solo trip, I was able to take just a tarp for my shelter, so my pack was relatively light (only 17lb not counting food and water). Not ultralight, but less than ½ the weight of my family backpacking trip load, and small enough that I could take my smallest pack (Arcteryx Brize 32).

Look at the view of Half Dome from Glacier Point, it’s amazing! I can’t emphasize how impressive the views from Glacier Point are. Only downside is that the crowds are intense. Luckily enough I got there early enough to get a good parking spot, eat some lunch, and get hiking.

I didn’t have a particular spot in mind, but there was a stream powering Silver Strand Falls, so my tentative goal was to get there (about 9 miles or so from the trailhead) so I’d have a nice water source for putting out my fire. I wasn’t sure how many of the streams I was going to cross would have water, so I when I reached Bridalveil Creek, I filtered 2L of water for my bottles, filled up my water filter, and filled up the water bag for my bidet.

Speaking of bidet, I can’t emphasize enough how nice taking a backcountry bidet on a trips like this is. We always pack out our used TP (gross) but it’s better than leaving it ½ buried and blowing around the trail (even grosser). The bidet means we never stand a chance of running out of TP, don’t need to cary the gross stuff out, and it leaves you feeling even cleaner than when you started.

When I finally got to the creek above Silver Strand Falls… it was dry. Luckily I still had plenty of water for the night, so I backtracked to Crocker Point to setup camp.

Look at the gorgeous site.

New on this trip, instead of carrying a ground-sheet to set my sleeping pad on, I brought a ⅛” foam mat. It weighs almost nothing and I kept is strapped to the outside of my pack to use as a sit-pad for lunch, snacks, water filtering, etc. Not only is it more useful than a ground-sheet, but it felt like it offered more protection to my pricy and somewhat fragile inflatable sleeping pad.

Not a bad view for dinner.

The week before this trip I made a double-batch of dehydrated spaghetti. The recipe was blindingly simple: boil 2lb lean ground beef and rinse with hot water to remove as much fat as you can. Break 2lb spaghetti in a big bowl until all the pieces are about 3″ or less (this makes it easier to pack and easier to fit into your pot). Cook the spaghetti until it’s way past al dente, combine it with the meat and 2 jars of sauce. Mix well, and dehydrate at 135 overnight.

One key tip for meals like this is to add additional fat back into the meal when it’s time to eat. This time I used 10g of olive oil, which worked fine, but it was enough oil that I could taste it in the sauce. If I were to do it again, I’d replace the oil with clarified butter. I think it’d have a better taste to go with the meal.

Anyway, for cooking, I just add the spaghetti to the pot, cover in water, bring to a roiling boil, then turn off the burner and let it soak for 10 minutes. Perfection.

After dinner, I was able to chill on Crocker Point and watch the sun set over the valley. Eventually it got dark enough that I could see all the headlamps of the climbers on El Cap.

R0002283 7.15.56 AM.

Look at all of those people! I counted 22 individual headlamps just on El Cap. I can’t believe that many people are just chilling up there on that massive 3000 foot face.

As is customary, here’s a night shot of the view from my sleeping bag. I took this after waking up in the middle of the night. The moon was down at this point and the stars were beautiful.

Funny enough, I tried to capture the same shot with my proper camera (not my iPhone) and it didn’t turn out as well. The 30s exposure is long enough that the stars move a bit, making them all a bit blurry. The iPhone is smart enough to combine the different exposures into one without letting the star-trails ruin the photo.

Breakfast in bed. Actually just coffee in bed. The last few trips I’ve been making coffee while breaking down camp. Take a poop before I start hiking, and get a few miles into the day before stopping for breakfast. Not that it really mattered on this particular trip since I was in no rush to get back to the car, but it’s good way to break down camp quickly without spending forever doodling around camp making breakfast and cleaning up.

It obviously works, I passed a ton of campsites at Crocker Point, all partially through breakfast. Including one group that left their campsite unattended to go check out the view. Their breakfast dishes and ½ eaten oatmeal were all over the place and their bear canisters were left open. The only wildlife I saw on this trip one tiny mouse, so they probably had no issues leaving all that food out, but man… that’s how you get bears. Do better people!

Speaking of Crocker Point, it’s a gorgeous view with big flat areas for a tent, but that shit was crowded! There were five groups there when I passed in the morning, and I passed some hikers a few hours later that had camped there too. I’m not sure the comfy campsites are worth camping right next to that many people. No fire rings at Crocker Point, but lots of visible signs of old fires (someone said that rangers had destroyed all the fire-rings up there to prevent people from having campfires). Not a great place to have a fire, there’s no water to put it out anywhere nearby.

I stopped at Bridalveil Creek one last time to eat breakfast and filter a bit more water. I sat there for maybe 30 minutes and didn’t see a single other hiker. Nice!

BTW, we got a new bear can recently. bareboxer.com I like it! It’s small, relatively light, not super expensive. I was not sure how well I’d like the relatively complicated lock that requires a tool to open. It comes with a “key” but you can use any thin metal device to open it. To be honest, when our usual bear cans get cold, they are a pain in the ass to open. That plastic gets stiff, your fingers are cold. It’s not the worst thing in the world, but it does kinda suck. The Bare Boxer has none of those problems. Plus, if you can pack light, it’s probably got enough space for a 2-day solo trip.

Here’s one last shot of El Cap:

All in all a great trip! If I were to do it again, I’d start from one of the trailheads further to the west. Glacier point is beautiful and all, but having to hike from Glacier Point to Sentinel Dome past Taft point means you’re spending the first 4 miles of your hike dodging day hikers. I’d rather skip the views AND skip straight to the “wilderness” experience.

I think what I’ll do next time is park at the Wawona Tunnel, hitchhike up to the Sentinel Dome trailhead, then just hike all the way down the hill to my car. Probably not anything I can convince the girls to do, but fine for a solo hiker.

For those that are into it, here is my LighterPack for this trip. I could have saved 1lb by leaving my puffy jacket and gloves behind, I didn’t need either… but it was probably good insurance to take them anyway since I didn’t know how cold it would be.

The political compass quizz needs a 3rd dimension

My political Compass quizz

I took the Political Compass quiz. No idea how accurate or respected these kinds of quizzes are, but my alignment matches exactly what I expected it would, tending towards the extreme for being socially liberal, tending towards the center for economic conservatism. I know the phrase “social liberal, fiscally conservative” has been co-opted by absolute dickbags, but if you ignore the dogwhistle baggage of the statement and take it literally, I can see that being something I agree with (FWIW, the phrase “common sense” was similarly ruined by Sarah Palin).

Taking this quiz made me realized that these things need a 3rd dimension. We could put far left and far right economists in a room, ask them to fix the American Healthcare system, and they could slowly and painfully hash out a workable solution. There’s a wide range of ways to fix this, from “Medicare for all” on the left to “Obamacare” on the right. The right to left economic scale contains a whole host of reasonable positions.

But! That’s not the discussion we had back in the late-aughts when we were trying to fix healthcare. The argument was not between left and right, but between “let’s fix our healthcare system” and “why fix what isn’t broken?”. The argument was between people who recognized a problem and wanted to solve it, and a coalition that refused to acknowledge the issue at all.

This is the same dynamic Americans see any time there’s economic policy to be made. We aren’t spending our time arguing about the best way to fix homelessness in the richest nation on earth, we’re spending our time arguing about whether homelessness is even a problem. It’s the same with the growing wealth disparity between lower-middle-class Americans and the ultra-rich, astronomical college costs, housing costs, etc. It’s endlessly frustrating.

The best use for the action button

The best action button setting I have so far is using it for TODO dictation. I have it set call a shortcut that creates a new item in my reminders, those reminders are automatically imported into Things. Not only is it insanely useful, but the entire thing feels like I’m a suit-wearing CEO from 1986 leaving messages for my personal assistant.

Action button configured for a shortcut

Shortcut for dictating text

Please stop tracking me

Google has finally admitted that it tracks your search history, activities, the websites you visit and the services they use even in Incognito mode.

– news.abplive.com

I’m fairly technical and extremely online, so Google tracking me when I’m in incognito mode is unsurprising, which is why I mostly don’t use it for anything other than debugging weird website behavior or logging into stuff with a alternative account.

I have what I think is a fairly pragmatic and nuanced take on online trackers: If I’m using your site, feel free to collect any and all information you want about me. If I’m not using your site, you should know nothing about me.

What does this mean in practice?

It means that if I’m using Youtube to watch videos about camping and hiking and snowboarding, then use that shit to show me advertising for camping, hiking and snowboarding products. Advertisers are happy because they get access to targeted users, I’m happy because I the ads I see are, at the very least, not offensive and possibly useful. Google is happy because they’re making $$$ from happy advertisers, win win win.

It also means that Google should never know anything about my browsing habits on sites that are not owned by Google. They shouldn’t know my REI purchase history, they shouldn’t know that I’m visiting Patagonia.com, they should have no knowledge of anything I’m doing on a site that isn’t explicitly owned by Google.

All personal data, profile information or browsing history should be available to only the company or site I’m currently engaged with and never shared with marketing firms, data brokers or social networks. I suspect this is how most naive internet users assume the internet works, this is how it SHOULD work, and the US (or, if we want to be a bit more realistic, California) should enact strong legislation to ensure that this is how it does work.

This is a bad use of AI

github.com/vanna-ai/vanna

AI tools excel in areas where an exact answer isn’t necessary (“draw a picture of a unicorn”) or where it’s easy to verify the correctness of the answer (“write a python script to download and merge some log files”).

This is neither.

The answers Vanna.ai gives you must be correct, and verifying the correctness requires you to parse and understand a poorly formatted SQL statement written by a computer. If you can already do that, you could just write it yourself from scratch.

Or, to quote Brian Kernighan:

Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?

If Vanna.ai is writing SQL that’s more clever than what you could write, how are you ever going to be able to tell if it’s correct?

Two small notes on the blog

First, I’ve written my first WordPress theme. I wanted to use WordPress here just so I could make the maintenance of my blog as trivial as possible. My goal was something that emulated the old manually-coded HTML of ancient blogs, and I think I mostly hit it. There are a few things I want to updated to make it more modern, but it’s good enough for now.

Second, I hooked my blog up to ActivityPub. In addition to following me via my RSS Feed, you can also follow the dedicated activity pub account. Search for @blog@jimkubicek.com in your Mastodon client of choice to subscribe. Here’s a direct link if you’re on mastodon.social.

The Ember Cup

Stephanie and I got matching Ember cups for Christmas. I’m generally happy with mine, but there are some things that folks should know to avoid frustration.

First, here’s what this cup is not:

  1. It’s not a way to warm up a chilled drink. It can warm Chemex coffee that has been cooling on the counter, but it will take 60+ minutes and isn’t worth it. In fact, the heating elements won’t start the warming process until they detect warm liquids. If you want to pour some milk into your Ember to get a head start on warming it up, you’ll have to trigger the warming process from the phone app.
  2. It’s not designed to keep a cup of coffee warm when away from the base station indefinitely. Maybe our house is colder than average or I like my coffee warmer then average, but the battery doesn’t last long enough to support an extended trip away from the charging base. On a fully-charged battery I can easily drink one hot drink while sitting outside, but the battery will die pretty quickly into the second cup.
  3. The battery does not quick charge. I haven’t timed how long it takes, but getting back up close to 100% isn’t a casual thing, you can’t just throw it into the charging coaster for a few minutes to top up the battery. When you get the low-battery warning, you’re going to need to leave it sitting there for at least 30 minutes to get a decent charge up and well over an hour to fully charge the battery.

This may sound like I’m kinda down on the cup, but that’s not the case! For my use case, it’s actually just fine. I bought this to sit at my office desk and keep my drink toasty while I ignore it for long periods of time. In this use case, I would have the charging base on my desk and the cup would be charging most of the time. If I want to work outside or in another room, I can have a hot drink for 45 minutes or so, which isn’t too bad.

This cup replaces a HydroFlask mug that I’ve been using. The HydroFlask is still expensive for a cup, but it’s a lot cheaper than the ember and does do a pretty good job keeping drinks warm, but it’s got a few downsides. While it does a great job keeping drinks toasty, it doesn’t keep them warm forever. Second, it’s a little too insulated; if you put boiling hot water in it, the water will be too hot to drink for a long time. The trick is to keep the the lid off for a while, until it hits drinkable temp and then slap the lid on to preserve the temperature. Get this timing wrong and you scald your mouth or end up with a lukewarm drink. Second, it’s a metal cup with a plastic lid, so it gets a bit of the weird travel-mug tastes. I don’t know what the Ember is made out of, but it doesn’t taste or smell any different then a ceramic mug. Also, since the Ember has no lid, it very quickly cools down to the perfect drinking temperature and stays there.

Would I recommend that someone buy an Ember mug? Maybe? It’s $130, so it’s not a trivial purchase. If you get your coffee from a already-warmed source (i.e. not a cold Chemex) and you spend most of your time drinking from a place where you can plug in a charging puck, then I’d consider it.

If Ember releases a new model with a quick-charge mode and a robust heating element that can reheat my cold coffee in a reasonable amount of time, I would reccomend the cup with no reservations.

Setting up Github Actions for Deploying Pelican

Github actions allow me to implement continuous delivery for this blog. Each time I merge to master, jimkubicek.com is built and deployed.

First, this action should run anytime the master branch is updated.

name: Build and Deploy

on:
  push:
    branches: [master]

Now we need to create our deploy steps. Let’s use a Ubuntu container with the latest commit in our branch checked out.

jobs:
  deploy:
    name: Deploy to jimkubicek.com
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v1

Install Python 3.8 (or whatever version you’re using):

    - name: Set up Python 3.8
      uses: actions/setup-python@v1
      with:
        python-version: 3.8

Upgrade pip and install the latest version of the Pelican static site generator and the Invoke task runner:

    - name: Install Pelican
      run: |
        python -m pip install --upgrade pip
        pip install invoke pelican[Markdown]

In order for SSH to work correctly, we’ll need to make sure that our public and private keys are created and placed in the correct location. On your local machine, let’s generate a valid keypair.

ssh-keygen -t rsa -f -b 4096 ./github_actions -C github_actions

Now, let’s copy the public key up to our server.

ssh-copy-id root@example.com -i github_actions

Now copy the private key into the pasteboard and add it to your github secrets. This action uses a secret with the name PRIVATE_KEY. Paste the contents of your clipboard into this secret.

cat github_actions | pbcopy

Now, in our action file, we’ve got to read this secret and get it setup on disk. The env command extracts the secret out and stores it into an environment variable. Make sure that the .ssh directory exists, and save that private key into the id_rsa file. SSH requires that the key has restricted access, so set the access to 400. Finally, add our IP address to the list of known and approved hosts. The downside of this is that if your server is MITM’d you’ll continue to just blindly trust it. I’m not sure of a way around this, if you know, let me know.

Here’s the final SSH setup stage:

    - name: Setup the SSH key
      env:
        PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
      run: |
        mkdir $HOME/.ssh
        echo "$PRIVATE_KEY" >> $HOME/.ssh/id_rsa
        chmod 400 $HOME/.ssh/id_rsa
        ssh-keyscan -t rsa <SERVER_IP> >> $HOME/.ssh/known_hosts

Finally, use Invoke to upload to our server.

    - name: Push to example.com
      run: inv publish

Setting up Let’s Encrypt with Nginx

This blog is a static site generated with Pelican. It’s now almost 2020, which means that using https isn’t just a good idea, it’s pretty-much mandatory. The good news is that setting up Ubuntu, Nginx and Let’s Encrypt is incredibly straightforward. Start to finish it only took me a bit over an hour to get everything working together, which was far faster than I expected.

These instructions are based off a walkthrough in Digital Ocean’s documentation, which inexplicable can’t be directly linked to. Update There are better instructions available on the certbot page. You should probably follow those instructions.

Before we get into the individual steps, there’s a handful of assumptions. First, you have a server you can SSH into and it’s serving your site via Nginx. You should also have a domain name already setup, no bare IP addresses.

sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot

In order to validate that you own the domain that you’re attempting to configure the certificate for, you’ll need to expose the .well-known path. Modify your sites-available/default Nginx configuration to add the following location.

location ~ /.well-known { 
    allow all; 
}

This directive ensures that requests to /.well-known will succeed. The is necessary to support the ACME Challenge from Let’s Encrypt. This challenge is used to verify that you own the domain name.

Now that Nginx is configured to allow certification of your domain, it’s time to run the certbot command to validate the domain.

sudo certbot certonly --webroot --webroot-path=/var/www -d example.com -d www.example.com

This command will validate that you own the domain for which you are requesting a certificate, place that certificate in /etc/letsencrypt. After the certificate is generated, you’ll need to configure Nginx to use TLS/SSL. The recommended way to do this is to generate Nginx “snippets” containing the required configuration.

sudo vi /etc/nginx/snippets/ssl-example.com.conf

Inside the snippet file, add the following lines, replacing your domain name as required.

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

Now we need to create a snippet for setting strong encryption settings. Run sudo vi /etc/nginx/snippets/ssl-params.conf to create the file. Below I’ll include how I have my file setup, but you should probably reference raymii.org for up-to-date instructions on configuring SSL, as these recommendations will change over time.

ssl_protocols TLSv1.2 TLSv1.3
ssl_prefer_server_ciphers on 
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384
ssl_dhparam /etc/ssl/certs/dhparam.pem
ssl_ecdh_curve secp384r1 
ssl_session_cache shared:SSL:10m 
ssl_session_tickets off 

ssl_stapling on 
ssl_stapling_verify on 
resolver 8.8.8.8 8.8.4.4 valid=300s 
resolver_timeout 5s 

# disable HSTS header for now 
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" 
add_header X-Frame-Options DENY 
add_header X-Content-Type-Options nosniff 

That’s about it. Overall I was pleased with how easy the setup was. Having an unencrypted server is no longer an option for me.

Creating a Swift Collection

Let’s say you’d like to create your own collection class. In this example, it’s going to be a collection of books that only allow the addition of a new book if it’s written by a select list of your favorite authors.

typealias Book = (title: String, author: String)

struct MyCollection {

    private let validAuthors = ["Tom Robbins", "Jim Davis"]
    private var books: [Book] = []

    mutating func addBook(book: Book) -> Bool {
        if (find(validAuthors, book.author) != nil) {
            books.append(book)
            return true
        } else {
            return false
        }
    }
}

So good so far. Now we need to add some accessors. It would be nice to know how many books are in the collection. Indexed access to the books would be great. The ability to iterate over our books in a for x in y block would be fantastic. Let’s go about adding that behavior.

In order to enable using our collection in a for loop, we’ve got to adopt the CollectionType protocol. Let’s add that to our MyCollection declaration.

class MyCollection: CollectionType {

Let’s read the definition of the CollectionType protocol.

protocol CollectionType : _CollectionType, SequenceType {
    subscript (position: Self.Index) -> Self.Generator.Element { get }
}

Well then. That looks simple, except what is Self.Index and Self.Generator.Element? Let’s read the definition of _CollectionType and SequenceType.

protocol _CollectionType : _SequenceType {

    /// A type that represents a valid position in the collection.
    ///
    /// Valid indices consist of the position of every element and a
    /// "past the end" position that's not valid for use as a subscript.
    typealias Index : ForwardIndexType

    /// The position of the first element in a non-empty collection.
    ///
    /// Identical to `endIndex` in an empty collection.
    var startIndex: Index { get }

    /// The collection's "past the end" position.
    ///
    /// `endIndex` is not a valid argument to `subscript`, and is always
    /// reachable from `startIndex` by zero or more applications of
    /// `successor()`.
    var endIndex: Index { get }
    typealias _Element
    subscript (_i: Index) -> _Element { get }
}

protocol SequenceType : _Sequence_Type {

    /// A type that provides the *sequence* 's iteration interface and
    /// encapsulates its iteration state.
    typealias Generator : GeneratorType

    /// Return a *generator* over the elements of this *sequence*.
    ///
    /// Complexity: O(1)
    func generate() -> Generator
}

Informative. Now we need to know what _SequenceType, ForwardIndexType _Sequence_Type, and GeneratorType do.

protocol _SequenceType {
}

protocol ForwardIndexType : _ForwardIndexType {
}

protocol _Sequence_Type : _SequenceType {

    /// A type whose instances can produce the elements of this
    /// sequence, in order.
    typealias Generator : GeneratorType

    /// Return a *generator* over the elements of this *sequence*.  The
    /// *generator* 's next element is the first element of the
    /// sequence.
    ///
    /// Complexity: O(1)
    func generate() -> Generator
}

protocol GeneratorType {

    /// The type of element generated by `self`.
    typealias Element

    /// Advance to the next element and return it, or `nil` if no next
    /// element exists.
    ///
    /// Requires: `next()` has not been applied to a copy of `self`
    /// since the copy was made, and no preceding call to `self.next()`
    /// has returned `nil`.  Specific implementations of this protocol
    /// are encouraged to respond to violations of this requirement by
    /// calling `preconditionFailure("...")`.
    mutating func next() -> Element?
}

Whew. I think we’ve exhausted that rabbit hole. Now we can start building up our collection class. First, let’s create a book generator. Since the specifics of this type only need to be known to MyCollection, we’re free to create it as a private inner struct.

private struct BookGenerator: GeneratorType {
    typealias Element = Book

    private var books: [Book]
    private var idx = 0

    init(_ books: [Book]) {
        self.books = books
    }

    mutating func next() -> Element? {
        if idx == books.endIndex {
            return nil
        } else {
            let obj = books[idx
            idx++
            return obj
        }
    }
}

Fantastic. Now let’s take a look at how we’re going to adopt the _SequenceType protocol.

typealias Generator = GeneratorOf<Book>

func generate() -> Generator {
    return GeneratorOf(BookGenerator(books))
}

This is a bit of trickery. The GeneratorOf<Book> type is a type-erasing generator. GeneratorOf is a GeneratorType that takes a Generator on initialization. Using GeneratorOf as our generator type allows us to declare a public generate() method that returns a known type (GeneratorOf) without exposing to the world the actual Generator type we’re using.

Now, how are we going to adopt _CollectionType?

typealias Index = Array<Book>.Index
typealias _Element = Book
var startIndex: Index {get { return books.startIndex }}
var endIndex: Index {get { return books.endIndex }}
subscript(_i: Index) -> _Element {get { return books[_i] }}

We’re looking great! Let’s test it out.

var mine = MyCollection()
mine.addBook(("Wild Ducks Flying Backwards", "Tom Robbins"))
mine.addBook(("A Garfield Treasury, Vol 14", "Jim Davis"))

for book in mine {
    println(book)
}

Works great! For completeness, here’s all the code from my test playground:

import Cocoa

typealias Book = (title: String, author: String)

struct MyCollection: CollectionType {

    typealias Generator = GeneratorOf<Book>
    typealias Index = Array<Book>.Index
    typealias _Element = Book

    private let validAuthors = ["Tom Robbins", "Jim Davis"]
    private var books: [Book] = []

    var startIndex: Index {get { return books.startIndex }}
    var endIndex: Index {get { return books.endIndex }}

    private struct BookGenerator: GeneratorType {
        typealias Element = Book

        private var books: [Book]
        private var idx = 0

        init(_ books: [Book]) {
            self.books = books
        }

        mutating func next() -> Element? {
            if idx == books.endIndex {
                return nil
            } else {
                let obj = books[idx
                idx++
                return obj
            }
        }
    }

    mutating func addBook(book: Book) -> Bool {
        if (find(validAuthors, book.author) != nil) {
            books.append(book)
            return true
        } else {
            return false
        }
    }

    func generate() -> Generator {
        return GeneratorOf(BookGenerator(books))
    }

    subscript(_i: Index) -> _Element {get { return books[_i] }}
}

var mine = MyCollection()
mine.addBook(("Wild Ducks Flying Backwards", "Tom Robbins"))
mine.addBook(("A Garfield Treasury, Vol 14", "Jim Davis"))

for book in mine {
    println(book)
}

Creating a Homebrew formula for a Python project

I just finished writing a homebrew formula for a python script I wrote, I’m going to walk through how I did it. Hopefully this helps anyone else who is thinking about distributing their code.

Why did I use Homebrew and not Pip? Two reasons: first, my code requires some Java .jar files. The front end is python, but a big chuck of the code is Java, so I didn’t have any particular allegiance to Pip. Second, I think Homebrew is the most common package distribution method on OS X. Not everyone will have Pip installed, but anyone who can use my script, will have Homebrew installed (It is the easiest way to install Keybase, which I require).

As an example, I’m going to write a Formula to install my python script Switters.

First, you should push your package to Github. This will give you both a place to host your downloads and a homepage URL that you will need to add to your Formula. Homebrew requires that you version your project, so make sure your commit is tagged with a version.

You’ll need to find the download link for your repo. Checkout the Releases page on github for the download URL. It should look something like https://github.com/jkubicek/Switters/archive/0.1.2.tar.gz.

Now, run the command to create your formula.

brew create https://github.com/jkubicek/Switters/archive/0.1.1.tar.gz

This creates a formula at $HOMEBREW_REPOSITORY/Library/Formula/switters.rb and opens it in your text editor. If you get a warning, “Version cannot be determined from URL”, add the correct version to the formula with version '0.1.1'. You’ll also need to add your homepage. It’s fine to use the project’s Github page here.

Homebrew recommends that you explicitly add your python dependencies. For dependencies hosted on PyPI that means you’ll need to browse PyPI to find the download URL for your resource. Here’s an example resource entry for Tweetpony:

resource "tweetpony" do
  url "https://pypi.python.org/packages/source/T/TweetPony/tweetpony-1.5.0.tar.gz"
  sha1 "c6e217f2676e9980a5ad01d0da125f0e1914398a"
end

The URL is straight from the PyPI page. PyPI only gives you the MD5 hash, which is no longer recommended for Homebrew. To get the sha1 hash, use shasum.

curl -O https://pypi.python.org/packages/source/T/TweetPony/tweetpony-1.5.0.tar.gz
shasum tweetpony-1.5.0.tar.gz

Copy the resultant SHA into your forumla.

Now you’ll need to check the build system. Don’t bother with Homebrew’s interactive installation. It doesn’t run your install method, so it doesn’t let you debug the installation steps. Instead, run a regular install command with a few helpful flags. The results of the --verbose flag are obvious. The --debug flag will stop the installation on errors and give you an interactive prompt. From here you may print a stack trace or open up an IRB session. Very helpful.

brew install --verbose --debug switters

Take note of the SHA that Homebrew reports, you should add this to your Formula.

If everything goes well, the script should have run successfully and… nothing should have been installed. You’ve got to add the installation method.

First, let me explain the structure of my Switters project. I’ve got an executable at the top level of my project. There are two local python modules, switterslib and zxing and two Java .jars located in zxing_java. In order for everything to work, I’ve got to make sure my imports from PyPI are installed correctly and that the local resources are put in the correct spot. First, lets get our remote resources setup.

ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages"
%w[tweetpony qrcode requests].each do |r|
  resource(r).stage do
    system "python", *Language::Python.setup_install_args(libexec/"vendor")
  end
end

What does this do? First, we append HOMEBREW_PREFIX+"Cellar"+name+version+"libexec/vendor/lib/python2.7/site-packages onto the PYTHONPATH environment variable. This ensures that Python will be aware of this directory and look here for the necessary modules. We’ll see how that works in a bit. Next, we iterate through our resources, create a stage environment, and call a special Homebrew python command that installs our dependancies into libexec/vendor. After installation, the actual location of these libraries will be libexec/vendor/lib/python2.7/site-packages, hence the environment variable we set as our first step.

ENV.prepend_create_path "PYTHONPATH", libexec
libexec.install Dir["switterslib"]
libexec.install Dir["zxing"]
libexec.install Dir["zxing_java"]

Here, we append the raw libexec path onto PYTHONPATH and copy the switterslib, zxing and zxing_java directories into it. This ensures that when our formula is installed, our python script can find these packages.

bin.install "switters"
bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"])

Finally, we install our script into the bin directory and run the env_script_all_files command on everything in the bin directory. This creates a shell script that sets up our python environment (hence having to add specific directories into PYTHONPATH) and calls each script in the bin directory. This script is located in the HOMEBREW_PREFIX+"Cellar"+name+version+"/bin" dir. Everything in this directory is then symlinked into /usr/local/bin/ which is (hopefully) in your PATH and now you’ll be able to call the script from anywhere!

I’m learning Android Dev

It’s about time I took a look and saw how the other half lived. I’m learning Android development. I bought the BNR Android book and have started working my way through the chapters. Keeping in mind I’ve only been doing this for two or three days, here are my thoughts:

  • Big Nerd Ranch writes exceptional books.
  • The Android Emulator is slow. It’s like DMV slow.
  • I’ve spent a surprising amount of time cleaning builds and restarting Eclipse and the emulator. I wouldn’t expect to get into that kind of debugging so quickly, especially on such a simple project. And while I’m complaining about Eclipse, non of their image assets are Retina. Since this is the only non-retina app I’ve used in a while, the appearance is strikingly bad.
  • String handling in Android is much better than in iOS. Has anyone written anything similar for iOS? Checking the googles…
  • I haven’t used Java since 2006 or 2007. It was surprisingly easy to pick back up.

I realize that my complaints about Eclipse and the emulator can be fixed by switching to a different IDE and using alternate emulators, but I’m making a conscious effort to learn the official way to develop Android apps before I strike out on my own and customize my own environment.

Waterfield Designs Staad Backback

Just a few weeks ago Waterfield Designs released their first pack, the Staad Backback. Strangely enough, every review I’ve seen is just a regurgitation of the press release and the product page, so I thought I’d give a little write-up after actually handling the pack.

First, my current backpack is the Tom Bihn Smart Alec. This is the best backpack I have ever owned. It’s comfortable, it’s durable, it’s sufficiently waterproof to ride my bike to work in a downpour. It has the most usable pocket system I’ve ever seen in a backpack. It’s also a bit big for what I need day-to-day, so I’ve been casually browsing around for a something smaller to get me back and forth to work.

After seeing my at the Staad, I decided to go with the waxed canvas, chocolate leather slim version of the bag. I went back and forth on the sizing, but I currently have a 13″ laptop and a bag big enough to haul groceries in, so if I’m going to buy a new bag I might as well go with the smallest bag that’s useful.

First Impressions

As I write this, I have just recived the pack, so I don’t have any real usage notes to report. Here are my first impressions; things that I was wondering about, I’ve seen people ask about or details that surprise me.

The buckle is not vintage. Every review I’ve read mentions the “vintage” buckle. I think what they mean is it is a “vintage style” buckle. The buckle itself is brand-new and plastic. That being said, it’s an interesting buckle. If you watch Gary’s video notice how smoothly he opens the flap. It really is that smooth. The video glosses over the closing action a bit and makes it hard to see the exact mechanism for closing the bag. When you want to close the bag, you push the main tab down, then manipulate the small plastic bit through the slot. On a brand new Staad this is easy, as the stiffness of the webbing and the leather tab keeps everything in place and ready to close. I’m interested to see how this changes as the bag ages and everything breaks in.

Here are some animations illustrating the opening and closing action:

opening the clasp
closing the clasp

This clasp is fun to operate. It is one of the most satisfying closures I’ve used, rivaling the feeling you get when you rip open the fly on old broken-in button fly jeans.

The outside pockets are small, best suited to thin objects. I’ve got medium sized hands, the pockets are almost the exact size of my hands. Too small for a Moleskine, just right for Field Notes. You aren’t going be fitting a water bottle in here. These pockets are best suited for small items, earbuds, wallets, notebooks, gum, etc. Because of the stiffness of the waxed canvas, the pockets don’t stretch or deform, so you aren’t going to be able to cram a lot of stuff in there even if you wanted to.

I didn’t notice this in any images or descriptions, but the laptop and iPad pockets have a very nice fleece lining. The iPod pocket is thin, just big enough for a bare iPad (I couldn’t put my iPad mini + cover in the pocket without the cover sliding off).

I had two bottles of wine in the house. Both fit into the main compartment easily and I think I could have fit a third in there. This assumes that none of the other pockets have anything bulky in them. The pocket tapers towards the top, so putting the wine in requires unzipping the zipper. Once zipped it is fairly secure and the wine doesn’t fall out even when the bag is inverted. There’s no way you could fit a six-pack without taking the bottles out of the carrier.

The main compartment won’t fit anything much bigger than a long-sleeved t-shirt. Pack light.

The underside of the flap is black leather.

Zipper pulls are generic plastic pulls. They’re fine, same pulls my Tom Bihn bag uses. I wish bag makers like Waterfield Designs and Tom Bihn would use something a little nicer, though.

Laptop sleeve ends about 2 inches above the bottom of the bag. You’d have to set the bag down very hard to have the laptop bump.

The interior pockets close with Velcro, but it’s a nice Velcro. The loop part is tight, the hook part is not rough or scratchy; it’s almost smooth. The pockets are not deep. A Field Notes notebook sticks up enough that the velcro closure cannot close.

This is probably obvious to everyone considering this bag, but it’s worth being explicit: this bag is going to get a worn look very quickly. The leather flap already has scratches on it from me opening and closing the clasp. The waxed canvas has some scuffs. Anyone considering buying this bag probably desires the broken-in look, but if you like your gear to keep looking pristine, this is likely not the bag for you.

Amend Files to Previous Commit

I run into this frequently when doing big a big refactor. I’m carefully committing my changes in nice bisectable units, but then Woah! there’s a change that should be included in a previous commit. Here’s how you fix this up in Git.

Disclaimer: We are modifying Git history. Do not do this if you have already pushed these changes.

$ git log --oneline

39e1678 Removed allowsAirPlayVideo method
6c750a1 Removed UILineBreak enums
ce2c34f Removed all UITextAlignment enums
a5c04ad Remove dispatch_release() calls
8681487 Removed Refresh Header

There we go. My current changes should be included in commit 8681487, “Removed Refresh Header”. Fixing this is easy. Add your changes to the staging area, then run:

git commit --fixup=8681487
git rebase --interactive --autosquash 8681487~1

The first command commits your changes, but modifies the commit message to be the same as 8681487 with “fixup!” appended in front. Running rebase in interactive mode with “autosquash” turned on will move our previous commit right after the commit we’d like to modify and update that commit with our new changes.

Easy as pie!

Debugging Smashed Memory in Obj-C

We were getting a crash inside a button. Calling po self wasn’t helpful.

(lldb) po self
$1 = 0x0ce854d0 [no Objective-C description available]

Well.. That’s weird. I wonder what’s at that memory location?

(lldb) memory read 0x0ce854d0
0x0ce854d0: 00 00 00 b0 93 6a ce a0 0e 00 00 00 00 00 00 00  .....j..........
0x0ce854e0: 10 c7 e7 0c 00 00 00 00 00 00 00 00 00 00 00 00  ................

That… doesn’t look right. Let’s turn on some debugging tools and see if that helps. Open the ‘Edit Scheme’ window and navigate to the Diagnostics tab. You’ll want to turn on “Enable Scribble” and “Malloc Stack”. You can read more about these methods here, but in short, “Enabled Scribble” will cause the allocator to write 0xAA to newly allocated memory and write 0x55 to deallocated memory. “Malloc Stack” will log the allocation and free history of your memory.

debugging settings

Let’s get our app to crash again and see if that helped.

(lldb) po self
$1 = 0x0cdcd2d0 [no Objective-C description available]
(lldb) memory read 0x0cdcd2d0
0x0cdcd2d0: 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55  UUUUUUUUUUUUUUUU
0x0cdcd2e0: 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55  UUUUUUUUUUUUUUUU

Well, there we go. Obviously someone else is freeing self while we’re in the middle of a method. Let’s grab the PID of our crashing process. Easiest way to get this from an iOS app is to check out any log statements in the terminal.

2013-04-22 10:59:38.194 Sing![14105:2203] Loggin'
                           PID^^^^^

Mosey on over to your trusty terminal and let’s see what’s happening at that memory address.

$ malloc_history 14105 0x0cdcd2d0

This is going to fill your screen with a massive spew of text. You’ll probably want to pipe the results to your text editor of choice. The important bits are right there at the top, though. Check it out:

ALLOC ... 
----
FREE  0xcdcd2d0-0xcdcd3a7 ... CFRunLoopTimerInvalidate | _timerRelease | ... -[SongPreviewButton dealloc] ... free

About 100 lines of junk omitted. But there you go. We’ve got a timer that’s holding on to a button, preventing it from being freed when it should be, then all of a sudden the timer lets go and everything falls apart. Simple!

Unit Testing Parse Cloud Code

Like many people, I was thrilled when Parse announced their cloud code product. I’ve just started a little iOS project that required both persistent cloud storage and pulling data from a 3rd party API. Since the API had a great JavaScript library, but no built-in Obj-C support, moving the code onto the server had some big benefits: greatly simplified networking in iOS, allowed me to reuse the 3rd party library as is, and decreases my turnaround time should I need to modify this code in the future.

Now, I’m usually not a strict test driven developer, but these cloud code modules are a different story; the code is running on a server and accessing a 3rd party API. In this situation, quick build/test/debug cycles are impossible and testing is the only way go.

Here’s how I set up my testing environment. Please keep in mind that this is the first time I’ve used Node.js, first time I’ve written unit tests for JavaScript and the first real JS project I’ve worked on. In fact, before this, the only JS code I’d written was hackly little Safari extensions, so this is a whole new world for me. I’m writing this for someone with experience similar to mine; if you are experienced with Node, feel free to skip ahead.

Setting up the test environment

I assume you’ve already got Node and npm installed. If you don’t, they both can be installed via Homebrew.

I used Mocha.js for the testing framework and Expect.js for assertions. Mocha supports any assertion framework you can throw at it. Expect seems to work well and doesn’t generate Lint warnings like Should.js. Run the following commands from your project directory.

$ npm install mocha
$ npm install expect.js

These commands install the mocha and expect frameworks in the local node_modules directory. This greatly simplifies your environment. Code can be shared between collaborators without worrying about what framework version each dev has installed.

At this point, your Parse directory should look like this:

cloud /
  main.js
config /
  global.json
node_modules /
  .bin /
  mocha /
  expect /

Creating Cloud Code Modules

We’re all set to test, but first we need something to test. We’re going to add some code that just returns a helpful message. Modify main.js to look like so:

var message = require('cloud/message.js'

Parse.Cloud.define("get_message", function (request, response) {
    message.getMessage(request, response

What I’ve done is load each Cloud Code function from a separate module, this worked well for me because each function is independent of all other functions, but YMMV. Let’s setup some code to test. First, create a file named message.js in your cloud directory. Now modify it to look like so.

exports.getMessage = function (request, response) {
    response.success("Good job, buddy"

A bit about how Node.js loads modules, since this was all new to me. When each module is loaded, there is an object created called exports that is available within that module. Any function attached to that object will be available externally when your module is loaded. So in this example, our message module creates one function called getMessage. When we call var message = require('cloud/message.js'); the object returned from the require() function is that exports object.

Creating Tests

Now let’s create some tests. First, the default directory for Mocha tests is test, so let’s put our test there. Create the test directory and put a file in there named, “messageTests.js”. Modify it to look like this:

var message = require('../cloud/message.js'
var expect = require("expect.js"

describe('Message', function () {
    describe('response', function () {
        it('should return the correct message', function () {
            expect().fail("No tests yet"
        
    

First we import our message and expect modules. The describe() function is used to define the scope for associated tests. The it() function defines a Mocha test. Let’s run our test.

$ node_modules/.bin/mocha

Notice that the error message says, “Message response should return the correct message:”, so structure your describe and it messages to make that message nice and readable. Let’s replace our failing test with an actual tests.

it('should return the correct message', function (done) {
    message.getMessage({}, {
        success : function (message) {
            done
            expect(message).to.be.eql("Good job, buddy"
        }
    

There’s a few things to notice here. First, the done() function is an optional parameter to the describe() and it() methods. Any tests within will not complete successfully until the done() function is called, so you can use it to test callbacks and ensure that they were called. Second, notice the format of the expect() function. You can read the documentation for more details, but in general, the tests always follow this form, beginning with an expect() function and ending with a function.

Run the tests again and success! All our tests pass. All in all, it took me less than a day to try out different testing and exception modules, settle on Mocha and Expect, then write enough tests to nearly fully cover the Cloud Code I had written. Coming from Objective-C, the power and flexibility of JavaScript amazes me. Writing these tests was almost a joy.

JSLint: Expected ‘return’ at column X, not column Y

I’ve been writing some Javascript using the default settings in Chocolat, tabs instead of spaces and each tab is equivalent to 2 spaces. Running most of my javascript files through JSLint is fine, but there were a few lines that were generating warnings, even though the spacing looked just fine.

if (validateCardRequestDidSucceed(stripeResponse) === false) {
    response.error("Stripe card request failed with unknown error")
    return
}

What’s wrong here? That spacing looks just fine to me. Turns out that the default settings in JSLint want spaces instead of tabs and 4 spaces per indentation. JSLint, by default, ignores tabbed indentation, but somehow that return had been indented with spaces.

Replacing the spaces with tabs cleared up the issue.

In other news, I should probably switch to 4-space indentation. I’m not picky about spacing and, all things being equal, I might as well stick with the JSLint conventions.

When isKindOfClass is not kind of class?

I’ve been running into an issue over the past few days where [objA isKindOfClass:[ClassA class]] is returning false when clearly objA is a kind of ClassA.
I’m running these tests using SenTesting kit and I’m not compiling the .m files in my test target, which is the only issue that StackOverflow suggests.

I am including my Storyboards in my testing target. Perhaps that’s the problem? Let me just remove those Storyboards from the testing target…

BOOM. That was it.

Also, for future reference, in case anyone finds their way here while looking for how to load storyboards in a SenTestingKit test target, here’s how:

NSBundle *mainBundle = [NSBundle bundleForClass:[self class
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:name bundle:mainBundle
viewController = [storyBoard instantiateViewControllerWithIdentifier:MainViewController

Abusing UIView

Sometimes I long for the day when I get to create an iOS app that just uses Apple’s default interface element. Of course, this doesn’t last long, because using and abusing UIView is fun. Over the years I’ve picked up a few tips and tricks for making the most out of your time. The best tip is, first and foremost, you need to start copying Apple.

This cannot be emphasized enough. Apple’s framework developers aren’t perfect and they have made mistakes, but overall they provide excellent frameworks, especially for UI development. Make your class interfaces look like Apple’s class interfaces. Try to subclass Apple’s own elements before going off and creating your own. Don’t reinvent the wheel.

That being said, any iOS app of a decent size will create many custom UIView subclasses and learning how to properly subclassing UIView will reap benefits.

  1. You’ll get a lot of useful behavior right out of the box.
  2. You increase readability of your code and make it easier for future developers to understand what you’ve written.

Here are some tips for abusing UIView

Subclass the right class

If you are creating a generic control, subclass UIControl. If you are creating a custom button, subclass UIButton (or just create a custom button! That’s usually all you need). If you are creating a custom switch, subclass UISwitch (lols, just kidding. UISwitch is a terrible and fragile class to subclass. Write your own switch if you need something custom).

I see so many developers implementing complex touch event listeners in their UIView subclasses or a needless delegate protocol when they could have just gotten the same behavior for free by using the proper superclass.

Use UIViewAutoResizingMask

Your first attempt at custom layouts should always use UIViewAutoResizingMask (this changes in iOS 6.0, read more on developer.apple.com). Setting these up takes a trivial amount of time and you stand a pretty good chance of eliminating your custom layout code. Writing flexible and extensible layout code is very hard, which is why most developers don’t bother and just hard-code a bunch of magic numbers into their view layouts. Your layout may always be 320px wide today, but someday you’re going to enable landscape orientation in your app and having to go back in and debug your layout all over again is going to be a major headache.

Override layoutSubviews

Realistically speaking, you’re probably going to have layouts that springs and struts can’t handle. If you need to do custom layouts, do them in the correct location, by overriding layoutSubviews. You should always put your layout code in this method. Here’s some great reasons why you should be doing this.

  1. layoutSubviews will only be called once per run-loop. You can call [self setNeedsLayout] as much as you want without worrying about taking a performance hit laying out your views needlessly.
  2. layoutSubviews is common knowledge. Other developers (and yourself in 6 months) should know to look here for layout code. No need to try and scan unfamiliar code to find the method doing layout; it’s always the same one.
  3. Putting all your layout in one method makes handling state changes much more robust. Big Nerd Ranch has a writeup you should read.

It’s fairly common to have your layout depend on the properties of your subviews. This is how people tend to handle layout and it’s wrong.

- (void)setDeleteButtonVisible:(BOOL)visible {
    if (visible == _visible) return

    _visible = visible

    if (visible) {
        // move some stuff around to make room for this button
    } else {
        // move stuff around to cover the empty space
        // where the delete button was
    }
}

The biggest issue with doing this is that it scatters your layout code all over your class. Once you get two, three, four or more properties that influence your layout, each property setter becomes an incomprehensible mess of layout code. Don’t do this. A much better way to handle property-based layouts is to override layoutSubviews.

- (void)setDeleteButtonHidden:(BOOL)hidden {
    if (hidden == self.deleteButton.hidden) return

    self.deleteButton.hidden = hidden
    [self setNeedsLayout
}

- (void)layoutSubviews {
    [super layoutSubviews

    if (self.deleteButton.hidden) {
        // layout for hidden delete button
    } else {
        // layout for visible delete button
    }
}

You can feel free to call [self setNeedsLayout] as much as you want, those calls will be consolidated and the layout methods will only be called once per run loop. For complex layouts, this can be a massive performance win.

Override sizeThatFits:

- (CGSize)sizeThatFits:(CGSize)size is the unsung hero of custom UIView subclasses. This method can be used to set minimum sizes, maximum sizes, and optimal sizes. The trick here is that the UIView method sizeToFit calls through to sizeThatFits: with the current size, then resizes the view based on the response. sizeToFit: is always the method that you should override, it’s the designated initializer of sizing methods. A great use for this method is to allow users to initialize your class with a zero sized rect while still maintaining a proper frame.

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame
    if (self) {
        [self sizeToFit
    }
    return self
}

- (CGSize)sizeThatFits:(CGSize)size {
    if (size.width  < kMinWidth)  size.width  = kMinWidth
    if (size.height < kMinHeight) size.height = kMinHeight

    return size
}

Now, if someone really wants to initialize your view to an absurd size you can prevent this by overriding setFrame:, but in my experience, when someone resizes something to the wrong size, it’s obvious what they did wrong. When they’re attempting to resize something and it just won’t become the correct size, it’s usually a mystery why. Don’t surprise your users, let them shoot themselves in the foot, but make it obvious that they are shooting themselves in the foot.

Respond intelligently to weird frame sizes

If your UIView is instantiated by calling init, the default implementation will call through to initWithFrame: and pass CGRectZero. This is very common, and it shouldn’t cause your view to blow up or completely break. If you have a minimum size that your control should be, resize yourself in initWithFrame. If you don’t have a minimum size, make sure your subviews are pinned to the correct edges of your bounding rect so that they behave correctly when your view is resized. These two views should both have the same frame and be layed out identically:

CGRect frame // Declared to be something reasonable
MyCustomView *view1 = [[MyCustomView alloc] initWithFrame:frame
MyCustomView *view2 = [[MyCustomView alloc] init
view2.frame = frame

A UIView that blows up when instantied with a size zero frame is a perpetual source of developer annoyance. Don’t do this. If you need to use default frame sizes, provide an initializer that doesn’t take a frame as a parameter, and override initWithFrame: to ignore the input frame size. Make a note in the documentation to this effect.

Override pointInside:withEvent:

The default behavior of pointInside:withEvent: returns YES if the point is within your bounds. Override this method if your shape does not completely fill its bounds. For example, if you have a button with a transparent center region, you may not want to respond to taps in that region. Override this method to return NO for any points within that transparent area.

Even more useful, if you have a control that is smaller than the Apple HIG recommended guidelines of 44x44px, you can respond to touches outside your bounds, effectively increasing the tap target for a given button.

Don’t override drawRect:

Overriding drawRect: causes a performance hit. I haven’t profiled it, so I don’t know if it’s a signifigant performance under normal circumstances (it’s probably not), but in most cases, folks who override drawRect: can accomplish what they want much easier by setting properties on a view’s layer property. If you need to draw an outline around a view, here’s how you would do it:

#import <QuartzCore/QuartzCore.h>

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame
    if (self) {
        self.layer.borderWidth = 2.f
        self.layer.borderColor = [UIColor redColor].CGColor
    }
    return self

Learning how to properly subclass UIView will save you a lot of coding, a lot of debugging and will make it much easier for future maintainers of your code to read and understand what you’ve done, arguably the most important consideration for a developer.

Sensational.ist

This is my million dollar idea. The idea is called “Sensational.ist”. Install an extension in your browser. Whenever you read a news article that is full of sensationalist nonsense, trigger the extension. If enough people have labeled an article as sensationalist, all new visiters will see a warning page.

Caution: This article is complete bullshit.

This article was likely written with a goal of being confrontational to drum up pageviews and advertising dollars. By visiting this site you are supporting the fucks that are ruining online journalism. Please don’t visit this page. Rest assured that whatever meager content that was there is utter nonsense and by avoiding it you are helping to get that ass goblin fired.

Sort Obj-C Methods with Automator

Big view controllers in big projects tend to accumulate a lot of private methods and properties. In a perfect world, these methods and properties should be carefully organized into functional groups and carefully documented. In the world we actually live in, that shit doesn’t happen, which is why I’ve resigned myself to organizing everything alphabetically.

To make my life easier, I created an automator service that sorts everything for me. Here’s how you create it yourself:

  1. Open Automator.app
  2. Create a new workflow and select “Service”
  3. Drag the “Run Shell Script” workflow into the workflow pane.
  4. Above the workflow, change the drop downs to read “Service recives selected text in Xcode” and check the “Output replaces selected text” box.
  5. Change the shell drop down to “/usr/bin/ruby”
  6. Paste the gist below into the text view.
  7. Save the service with an appropriate name and you’re done!

{% gist 3759637 %}

Keep in mind that any comments need to be inline and all method names need to be on one line, no splitting accross multiple lines. I’m not too concerned about this, as it fits my style (I have word wrap turned on) and since nobody ever reads comments on declarations in the .m file anyway. When I get a chance I’d like to update this to clean up property declarations (all the names at the same tab-stop) and remove extraneous spacing in method declarations.

Open sourcing? Eliminate all warnings

A few months ago Matt Gemmell created a fantastic writeup on creating open-source components. One salient point he missed, though, is that you must compile and test your code with the strictest warnings available. You never know who’s going to be using your code and what warnings they have enabled. Assume the worst, and turn on nearly every warning you can in your project. Peter Hosey’s list is a great start (there’s even some AppleScript to automate turning on all these warnings). If you’d like to be extra cautious, use the -Weverything flag in Clang to turn on all the warnings.

Having trouble with Adium and iMessage?

I exclusively use Apple’s iMessage for chat. Most of my coworkers use Adium. Ever since I started this job there have been weird issues were coworkers can’t see me online and don’t respond when I message them. I’ve confirmed that they are not actually getting the messages (and they aren’t quietly hellbanning me).

Also, the name of my lapop is the Emoji characters .

Also, your default location in iMessage is the name of your computer.

Turns out there’s a bug in either iMessage, Google Chat or Adium (probably Adium, since iMessage <-> Google Chat works just fine) where Emoji characters in your location cause you to not be visible in Adium. I changed my location to something more vanilla and now all my coworkers can see me online. Hooray!

Configure git to only push current branch

I’ve always used plain git push to update my remote repos and I’m finally getting tired of seeing this error every time:

(master)> git push
...
To git@github.com:jkubicek/my_proj.git
   21b430d..dd378ca  master -> master
 ! [rejected]        release -> release (non-fast-forward)
error: failed to push some refs to 'git@github.com:jkubicek/my_proj.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. If you did not intend to push that branch, you may want to
hint: specify branches to push or set the 'push.default' configuration
hint: variable to 'current' or 'upstream' to push only the current branch.

I can only blame this on my utter laziness, because the answer is right in the error text. Run the following command to configure git push to only push your current branch.

git config --global push.default current

I should have done this months ago.

Don’t Lazily Load Your Views

I seem to run accross a lot of developers lazily loading their properties. As an example:

- (UILabel *)myTextLabel {
     if (_myTextLabel == nil) {
         _myTextLabel = [[UILabel alloc] init
         [self addSubview:_myTextLabel
     }
 }

At least in iOS developement, I suspect this is caused by Apple’s sample code, particularly Apple’s default setup for Core Data projects. There are some valid reasons why you’d want to lazily load a resources, but there’s lots of great reasons why you shouldn’t. Here’s a few:

Property calls should not have side effects

There are lots of exceptions for setters (like updating the UI after setting a property), but there are very few exceptions for getters. You shouldn’t need to worry about your object changing state when you access a property.

Lazy loading is confusing

self.myTextLabel = nil
if (self.myTextLabel) {
 NSLog(@"What the shit? How did I get here?"
}

Lazy loading leads to tricky initialization order dependences

- (UILabel *)myTextLabel {
    if (_myTextLabel == nil) {
        _myTextLabel = [[UILabel alloc] init
        _myTextLabel.text = self.myTitle
        [_myTextLabel sizeToFit
        [self addSubview:_myTextLabel
    }
}

Now your label will have different text depending on whether you set myTitle before or after you access myTextLabel.

Lazy loading leads weird code

Like this:

if(self.myTextLabel) // just need to setup my text label

Initialization, layout, UI updates should be localized

You should be performing all initialization in the init method, UI updates in an update UI method and layout in layoutSubviews. Not only does this make debugging far easier (having layout issues? I feel bad for you, son. I’ve got 99 problems, but performing view layout anywhere other than layoutSubviews isn’t one.), but it ensures that your view is always in a consistent state. Big Nerd Ranch has a great writeup on why this is important.

Clearly there are exceptions to all these rules and situations where lazily loading your view properties is the right thing to do. But remember, always write code that emphasizes clarity first and optimize for speed or memory constraints later.

OK. For serious this time

OK. This is a fresh start. I think I’ve got this blogging thing figured out for once. I’m using Octopress to create the site. I attempted to install Octopress a few months ago, but ran into a whole host issues trying to get ruby 1.9.2 to build. Luckily, Ruby 1.9.3 seems to fix all my issues, and installed smooth as silk. I never really got a chance to use Octopress 1.x, but 2.0 is going great. Here’s what I wanted in a blogging platform.

  1. Pre-rendered HTML pages I don’t have any illusions about the amount of traffic I’ll be getting, so performance isn’t that a concern for me. I do want to avoid the “black box” of PHP and MySQL that I’d been used to with WordPress. The chances of me learning every little detail of the blogging platform are slim, but if I do decide to dive in, I want it to be as easy and as frictionless as possible. Octopress is just a bunch of scripts. Nothing sneaky there!

  2. Easy to modify A little bit of HTML, a bit of javascript, maybe a little ruby. Writing themes and modifying the behavior of the site is something well within my reach.

  3. Run the site locally Right out of the box, Octopress makes it easy to get a full version of your site served locally. Try that, WordPress!

  4. Text only input I want to be able to write a blog post from anywhere on any device. Having plain text input ensures that I’ll have no excuses if I want to get something written. Plus, if I need to search my entries or make bulk changes, I’ve got my command line tools right here. Oh, and shit, I can also sit in coffee shops running full-screen Vim (green text on black background) to look like an über-hacker.

  5. Good code formatting I’d like to make this a mostly develpment blog. Good code formatting is important. Easy code formatting is just as important.

Most importantly, I’ve got a pretty sizeable chunck of writing saved up and ready to deploy. I’m hoping I can just throw these files in my favorite text editor and hit “publish”. I’m sure a few will get thrown out in the editing process, but I’m hoping that I use those first few posts to build up some intertia.

Let’s see where this takes us!