Proper High DPI font scaling in Firefox on Linux

macOS supports high DPI displays particularly well and exposes DPI scaling as a 5-step gradient. Over on the Linux-side, however, things are far less rosy, with wild differences between distros.

Linux Mint, the distro I ended up settling on, had no trouble consistently recognizing my 4K display, over my [way too expensive] USB-C-to-HDMI interface. DPI scaling is chiefly exposed as Text Scaling, which works fine for the most part. However, there are still applications that don’t always pick up on this setting and insist on displaying text at its na[t]ive resolution. It’s pretty obvious that displaying text at 1080p on a 13″ screen, or 4K on a 27″ display, is far from ideal…

On such app is Firefox, for some reason. Luckily, Firefox’s intrepid about:config dialog exposes just the setting we need to override whatever its default behavior is. As fedoramagazine.org describes it:

find the key layout.css.devPixelsPerPx and then change the value from -1.0 to 2

Screenshot by fedoramagazine.org

For reference, I set mine to 1.5 for a 4K screen displayed on a 27″ display. Note that the entirety of Firefox’s UI scales along with any web content. If you’re running multiple screens with different resolutions and sizes, you will notice that this value is system-global, as opposed to per-screen. In other words, it won’t be a one-size-fits-all solution, but good enough for me, for now.


Android device debugging on Linux Mint: “error: insufficient permissions for device: udev requires plugdev group membership”

As I rejoiced in the achievement of finally finding a Linux distro which plays well with my Dell XPS 13 (2019 edition, model 9380), I plugged in my Moto test device, intending to continue working on an Android app. Pressing the Run button promptly made Android Studio (3.4) do its compilation magic, but got stopped in its tracks rather quickly. An angry-looking error message awaited me:

error: insufficient permissions for device: udev requires plugdev group membership

Oops, no device debugging for you.

Android Studio also left a note pointing me to their developer page on the subject. As I suspected, it seemed I had some configuration work left to get device debugging working on Linux. However, following Google’s instructions on setting up adb didn’t do much to resolve my problem. The part about adding yourself to the udev group is important, though, as it’s linked to the actual solution described in the next paragraph.

sudo usermod -aG plugdev $LOGNAME

Adds your user to the plugdev group.

Update: Someone mentioned recently that the below steps may not actually be required; just logging out and back in again at this point, should also do the trick. YMMV of course :-).

An ill-timed dog walk (let’s just say I hadn’t expected to be caught in the middle of a downpour), and a few mildly frustrated Google searches later, I ran across a blog post from 2013 (!) on the subject of “Adding udev rules for USB debugging Android devices“, by Janos Gyerik.

I will not pretend to know why this extra configuration is required, but it describes looking up the device’s identifier and adding it to the aforementioned plugdev access group, so Android Studio can properly access the USB device.

And there you go, a working USB debugging connection to my Android device, thanks to some great advice from 2013!


Unit Testing AWS Lambda Functions in Node.js

Writing backend code – like web services or anything else really – with  AWS Lambda functions is amazingly easy, in particular when you choose Node.js as your weapon of choice. The amount of code required to get going is so sparse, it’s almost magical. However, as you build out your Lambda, complexity will quickly rear its head, and you’ll soon feel the need to add some tests.

Unit testing is a part of any good developer’s workflow, but I feel it’s especially important when dealing with dynamically typed languages, like vanilla Javascript. Its loosely-typed nature makes development fast, but also makes for a certain degree of uncertainty when making changes, or while refactoring. Good test coverage can make up for this, and it can allow you to work faster. If you’re able to mock your Lambda’s dependencies, you’ll be pretty confident that your successful unit test is representative of the eventual production code.

Dependency Injection

“Dependency Injection” is the somewhat intidimidating term used in software engineering to describe something quite simple:

Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation.

It’s most useful when applied in the context of unit testing, because it enables you to mock dependencies that shouldn’t be active during tests.

In Node.js Lambda functions, dependencies are imported using the require() function. It creates a constant in the function’s scope, pointing to some outside code. By default, you’ll do this at the top level of your Node.js file, effectively making the dependency globally accessible to said file. Consider this snippet, where we’re importing the AWS SDK, and creating a new instance of the DynamoDB DocumentClient:

const AWS = require('aws-sdk')
const documentClient = new AWS.DynamoDB.DocumentClient()

What happens when you unit test code that imports the above dependency? In this case, your test will establish a live connection to DynamoDB and potentially start reading and writing data to it! While you could argue this is a test in and of itself, this situation is far from ideal. Each unit test invocation will

  • potentially incur costs
  • write data to a live database, possibly messing up its consistency
  • be slow

Richard Hyatt’s Medium post from 2016 is still relevant today, as it describes how we can make dependency loading asynchronous and injectable by using the exports object to store and reference dependencies.

exports.deps = () => {
  const AWS = require('aws-sdk')
  const documentClient = new AWS.DynamoDB.DocumentClient()

  return Promise.resolve({
    dynamoBatchWrite: params => documentClient.batchWrite(params).promise()

The actual dependency import is enclosed into the deps function scope, and is made asynchronous by wrapping the result dictionary in a Promise. This asynchronicity allows us to overwrite the deps function during tests, while leaving it as-is in production.

The production code will just await the dependencies at the top, after which you’ll be able to access the fully constructed dependencies:

exports.handler = async event => {
  const deps = await exports.deps()

Now, for the test:

const lambda = require('../index')
const sinon = require('sinon')

describe('importOPML', () => {
  beforeEach('mock dependencies', () => {
    const mockWriter = sinon.mock()
    mockWriter.resolves({ UnprocessedItems: [] })

    lambda.deps = () => Promise.resolve({
      dynamoBatchWrite: mockWriter

  it('should succeed with empty opml', async () => {
    // Using lambda here, will call the version that uses the mocked DynamoDB writer.

This happens to be a Chai test that uses Sinon for mocking, but the premise is the same. Before each test block is run, the beforeEach block is executed, which preps the lambda with the mock dependencies.

That’s it. You’re off to the races!


2 Interactive Resources for Brushing Up Your RegEx Knowledge

For the longest time, regular expressions have remained something of an enigma to me. Despite the many, many learning opportunities, across various programming languages,  my ignorance of their perplexing syntax usually directed to me toward implementing my own code-based algorithms instead. It’s clear that most of the time, such roll-your-own solutions don’t cut it performance-wise, and probably end up being just as obscure and difficult to decipher, weeks or months down the road.

During my recent endeavor to learn Python, the need for some sprinkles of RegEx quickly presented itself. This time around, I set out to apply myself, and at least master the basics. While clicking around on the web, in search of quality learning resources, I grew pleasantly surprised at the crop of interactive resources on the subject and would like to highlight two for you. They’re a refreshing change from the selection of the many animal-toting books on the matter.


Screen Shot 2018-11-30 at 06.43.51

RegexOne.com is a delightful donation-supported website that guides you through the basics of regular expressions with a dozen (or so) lessons which are short, to the point, and each capped with an interactive input box. Exercises build on the previous ones to introduce each subsequent concept, highlighting the current match as you type. The little quizzes aren’t too hard, and in case you get stuck, the solution is just a click away. 

Once you’ve whizzed through the lessons, you can fall back on 5 language-specific guides:

  • C#
  • Javascript
  • Java
  • PHP
  • Python

RegEx101.com for on-the-fly testing and debugging

Screen Shot 2018-11-30 at 06.57.24.png

With your freshly harnessed knowledge, hop over to RegEx101.com, an online development, and debugging suite. Your test string will light up with an abundance of helpful widgets, in addition to highlighting matches:

  • full match information
  • capture groups
  • English, context-sensitive translation of what the RegEx statement means
  • a quick reference box
  • a code generator for 9 languages (Javascript, PHP, Python, C#, Java, Ruby, and Rust)
  • a means for sharing and storing your work

In not much more than an hour – with the help of these two free resources – I was able to craft an expression that succinctly extracted the information I needed, without resorting to my own obscure and undoubtedly inefficient one-off algorithm. 



What’s new in Swift 4.2.1?

Yes! There appears to be such a thing, and it was silently shipped alongside Xcode 10’s first point-release, 10.1. Contrary to major releases, Swift 4.2.1’s release wasn’t accompanied by a blog post, nor was its entry added to the Swift changelog. Is there a reason for this all this mystery, or is the 4.2.1 really just so insignificant?

Pierpaolo Frasa must’ve been wondering the same thing, based on his recent post on the Swift forums:

My mac wants me to upgrade to Xcode 10.1, which will include Swift 4.2.1.
However, I can’t find any mention of that swift version either on the download page or in the changelog.


The list of resolved issues is rather short, with 8 compiler issues fixed, and just one problem resolved in the standard library. The highlights include: 

  • A fix for ambiguous compilation error messages like “Command CompileSwiftSources failed with a nonzero exit code”
  • The Bundle class’s init(for:) initializer now works consistently with Swift classes, not just Objective-C classes
  • Long file paths containing white space no longer cause build failures
  • A mutating method that returns Self on a value of protocol type can now successfully be invoked

Check out the “Swift Compiler” and “Swift Standard Library” sections in the Xcode release notes for a complete list of the changes, complete with code samples.


Making the case for Implicitly Unwrapped Optionals!

We’ve all seen them [Apple] do it: nonchalantly defining @IBOutlets as implicitly unwrapped optionals, by appending a ! to their type declarations. Isn’t this supposed to be a big no-no among True Swift Developers? You’d think so, since we’re told that stray exclamation points are often ominous precursors to pesky runtime crashes.

You could argue that declaring outlets as optional weak properties is preferable, as it sidesteps the runtime exception situation altogether. A reasonable rationale.

However, I’d like to challenge this nugget of common sense, and entertain the idea that using a ! here instead of ? is also acceptable.

A quick syntax refresher

In general, outlets form the glue that connect user interface elements – defined in Storyboards or XIBs – to their programmatic counterparts. If you’re the type to eschew Storyboards, here’s a quick syntax refresher:

@IBOutlet weak var profileButton: UIButton?

The @IBOutlet marker imposes no side-effects and can be omitted, if so desired. Personally, I like to have them there, as it makes them easier to call out afterward. The storyboard instantiates, manages and retains the actual button, so it suffices to hold a weak reference.

However, weak also makes the property optional, which is why we need the ? at the end.

The cost of using Optionals

?s are nice and safe, but their use comes at an undeniable cost. In order to be read, they need to be systematically unwrapped with if let or guard let. A minor inconvenience, for sure, but guard statements are prone to popping up all over the place, if not corralled consciously.

Catching mistakes in outlet wiring

Littering guard let statements up the wazoo makes you feel dirty too, I’m sure, but this can be overcome. What trips me up each time, however, is what happens if you hook up an outlet improperly (or simply forget to!).

  • Use an optional, and you’ll be scratching your head – like me – every time. The outlet will remain nil, your controller will initialize properly and you’ll be left clueless as to why something feels amiss.
  • Use an IUO!, and your app will crash 💥. This uncomfortable side-effect will provide an immediate cue, as the stack trace will reflect exactly which property is acting up. As a result, you’ll fix up your oversight swiftly, with no time wasted.

While I’m not quite sure if I should retroactively convert my existing outlet declarations, I started using ! a while ago and still feel good about it.

Favor crashes, over Optionals, in case of developer error

I agree we should strive toward a 100% crash-free rate, but for clear developer errors, I tend to favor a hard crash. I’ve found that selective use of IUO’s, and their resultant crashes, can actually provide a boost to developer productivity.

Truly, I’m not trying to be contrarian. A well placed ! just happens to be the fastest route to “success”, in this case.

P.S. You may get the impression that I use Storyboards, because I use outlets. I don’t 😎.


How to run SwiftLint autocorrect on each Git commit

SwiftLint was developed by the nice folks @realm. It’s a great open-source tool for establishing and enforcing a formal coding style in Swift. It runs on the command-line, but it can be hooked into Xcode directly too. It also has an “autocorrect” feature, which sweeps through your code and automatically fixes the most trivial violations (e.g., colon positioning, double white spaces, etc.). I created a Git commit hook which does exactly this, every time a team member makes changes.

The shell script itself is simple. Only files changed within the commit will be autocorrected. To prevent inadvertent file corrections, these changes are not automatically included in the current changeset. You will have the chance to review the corrections, and make a new commit to finalize them, or amend the previous commit.

git diff --cached --name-only | grep .swift | while read filename; do
    /usr/local/bin/swiftlint autocorrect --path "$filename"

Install this shell script under the .git/hooks directory of your Git repository. Be sure to name it pre-commit (no file extension).

This commit hook should work fine with whichever Git GUI tool you use, as well as the command-line of course.

Note that each team member has to repeat this installation individually. There is no way to automatically distribute git commit hooks.


Abolish Retain Cycles in Swift with a Single Unit Test

Can’t believe we’re still dealing with this in 2017? Well, that makes two of us. While retain cycles are easy to fix, they’re also hard to spot while eyeballing a codebase. Recently, I’ve found that a single unit test can provide solace. With just a few lines of code, it runs continuously as you make changes, all the while verifying you haven’t introduced any new memory leaks.

It’s a simple snippet, but I’ll walk you through it.

The test function makes use of XCTest’s asynchronous expectation system to pick up whether your class’s deinit function gets called. The subclassing trick you see there is needed because Swift doesn’t support reflection yet. The subclass tracks the deinit call by adding that deinitCalled closure.

The test works by allocating the instance on the main queue, while immediately deallocating it on the background queue. This triggers the deinit call, and the test succeeds.

If the test fails due to the 5-second timeout, this is your cue. You have just found a retain cycle! I’ve found it helps to run this test throughout the development process. The delta between code changes remains small enough to pick up where you forgot a [weak self] or [unowned self].

P.S. I was unable to figure out a way to make the test function generic, so I’ve been copy-pasting it around. I realize this is not ideal. However, I find it’s not a big deal because we’re dealing with test code, not actual app code.


Loading custom fonts programmatically in Swift 3

How do you include custom fonts in your application, if they don’t reside in the main bundle? In this case, loading them through the conventional PLIST method doesn’t work, and you will need to resort to CoreGraphics to register them programmatically.

Typefaces are an essential part of good design. On iOS, custom fonts can be added to apps through a somewhat convoluted process. Chris Ching has a good write-up on the topic, but in short: ensure the font files are properly included in your app’s target and declare them in your app’s Info.plist (“Fonts provided by application”). This works well in the straightforward case where the fonts are simply embedded into the main app bundle.

You quickly run into the limits of the PLIST-based registration method when they live outside of the main bundle, e.g. in a separate .framework. In this case, simply register the fonts using the older CoreGraphics APIs.

Marco Arment described the approach on his blog back in 2012, but the example code he lists is Objective-C. Fortunately, the Swift version of this code is much less cumbersome than its Obj-C counterpart, as less C-trickery is required:

// Load bundle which hosts the font files. Bundle has various ways of locating bundles.
// This one uses the bundle's identifier
guard let bundle = Bundle(identifier: "some.framework.identifier")
else { return }

// List the fonts by name and extension, relative to the bundle
let fonts = [
    bundle.url(forResource: "gotham_book", withExtension: "ttf"),
    bundle.url(forResource: "gotham_medium", withExtension: "ttf")

// Iterate over the resulting urls, filtering out nil-values with .flatMap()
for url in fonts.flatMap({ $0 }) {
  // Create a CGDataPRovider and a CGFont from the URL.
  // Register the font with the system.
    if let dataProvider = CGDataProvider(url: url as CFURL) {
        let font = CGFont(dataProvider)
        CTFontManagerRegisterGraphicsFont(font, nil)

Just make sure you don’t forget to remove any duplicate PLIST declarations, or your app will throw an exception at startup.


@sveinhal in the comments suggested this functional rewrite of the above code, which is way more succinct if that’s your cup of tea:

let fonts = [
bundle.url(forResource: "gotham_book", withExtension: "ttf"),
bundle.url(forResource: "gotham_medium", withExtension: "ttf"),

.flatMap { $0 }
.flatMap { CGDataProvider(url: $0 as CFURL) }
.forEach { CTFontManagerRegisterGraphicsFont($0, nil) }

Filling the KVO gap in Swift with ReactiveCocoa

How do you do Key-Value Observing in Swift? Can you? And what about just using Objective-C’s native KVO mechanism? What follows is a gentle introduction to ReactiveCocoa’s unsung hero of property observation: Property (and MutableProperty).

Matt Thompson explained the ins and outs of KVO in exasperating detail in 2013 for NSHipster. In summary, let’s just say it’s a messy Objective-C API, which still happens to work in Swift today. Aside from the occasions where you can’t do without (NSProgress anyone?), I would advise against using it. Its complexity makes it prone to bugs. But Swift doesn’t offer a native equivalent, you say…

I hear you, but suppose you could simply do something like this, to listen for changes and reload a table view in response, picking up any new items:

override func viewDidLoad() {

    viewModel.drafts.signal.observeValues { [weak self] drafts in

Meet ReactiveSwift Properties

I would be omitting an important tidbit about Swift’s native observation capabilities, if I neglected to mention the didSet and willSet property observers. With enough boilerplate code, you can definitely cobble together something akin to KVO. You could, for instance, listen to the property changes yourself with didSet and re-dispatch these events over a delegate. Purists will prefer this approach, because no magic is involved, and no third-party libraries are required.

However, ReactiveSwift aims to encapsulate all this complexity by means of a singular concept, called Property. Simple, because at its core, Property is merely a value box, with a means to notify others of its changes. Here’s the pared-down protocol, taken from the 1.0 release of ReactiveSwift (github.com/ReactiveCocoa/ReactiveSwift/blob/1.0.0/Sources/Property.swift):

public protocol PropertyProtocol: class, BindingSourceProtocol {
	associatedtype Value

	var value: Value { get }
	var producer: SignalProducer<Value, NoError> { get }
	var signal: Signal<Value, NoError> { get }

The producer and signal properties are the actual observables you subscribe to for changes. Why the distinction? The RxJS README has a nice summary:

“Cold observables start running upon subscription, i.e., the observable sequence only starts pushing values to the observers when Subscribe is called. Values are also not shared among subscribers. This is different from hot observables such as mouse move events or stock tickers which are already producing values even before a subscription is active.”

When applied to ReactiveSwift, cold observables correspond to signal producers, while hot signals are represented by “regular” signals. In the context of properties, this boils down to:

  • Starting the producer will emit the property’s initial value, as well as any subsequent changes;
  • Observing the signal will only emit the values changed after the observation was started.


The concrete implementations of PropertyProtocol are contained by the classes Property and MutableProperty. Generally, you’ll be using the mutable variant, since it allows you change the property’s underlying value, thus triggering change notifications. The easiest way is to forego optionals and use let constants instead:

// Defining the property
let avatarUrl = MutableProperty("https://httpbin.org/image/jpeg")

// Setting the property's value
avatarUrl.value = "..."

// Listening for changes, without the initial value
avatarUrl.signal.observeValues { url in

// Listening for changes, including the initial value
avatarUrl.producer.startWithValues { url in

Data binding

Data binding is a means of tying properties to UI components, so that the component updates itself whenever the property changes. Contrary to AppKit, iOS’ UIKit has no notion of data binding. ReactiveCocoa exposes data binding through a single custom property: a less-than sign followed by a tilde.


Its shape emphasizes the binding’s unidirectionality. The following example clearly expresses the fact that the artist name is being set on the artist label’s text property whenever it changes, not the other way around:

// Hook up bindings in your controller's viewDidLoad()
func viewDidLoad() {
    artistLabel.reactive.text <~ viewModel.artistName

// Example implementation of this viewModel (details omitted for brevity)
class ViewModel {
    let artistName = MutableProperty<String?>(nil)

Data binding is a declarative way to express relationships between data and UI components. It reduces the cognitive overhead of manually assigning values. Code locality is also improved, as this approach centers binding logic into a single place.

ReactiveCocoa & ReactiveSwift

What’s the difference? With ReactiveCocoa 5, the core team decided to split up the codebase, in order to more clearly delineate each component’s responsibility and scope. This division also allows framework users to more easily cherrypick which modules they need in their projects.

  • ReactiveSwift: The new kid on the block. This is a pure-Swift implementation of the reactive API. It provides all the nuts and bolts, including Signals, SignalProducers, Properties, Actions and Bindings.
  • ReactiveObjC: ReactiveSwift’s Objective-C-based sibling. This is essentially ReactiveCocoa 2.0 and remains in maintenance mode.
  • ReactiveCocoa: The connecting piece between UIKit and ReactiveSwift. It provides all of the reactive extensions for UIKit components and exposes binding targets for them. It also introduces Triggers, a means for converting Objective-C selectors into signals. You can also wrap good ol’ ObjC KVO with signals, so they can be interspersed with ReactiveSwift signals and producers.
  • ReactiveObjCBridge: Bridges the ReactiveCocoa 2.0 API with the ReactiveSwift API, so ReactiveObjC remains accessible from Swift, enabling interoperability with old code.