Today I Learned

A Hashrocket project

Show What Is In A Git Stash

Usually when I want to inspect anything in git, I’ll use git show with a specific ref. This can even be done with stash refs.

$ git stash list
stash@{0}: WIP on ...
stash@{1}: Some commit on ...

$ git show stash@{0}
# ...

The git-stash command has a built-in way of showing stashes that will save you from having to type out the somewhat awkward stash@{n} ref.

$ git stash show 1

This will show you the stash@{1} ref. You can also omit a number which will show you the latest stash (stash@{0}).

See man git-stash for more details.

Resize Tmux Pane 🖥

Sometimes, after a long day of coding, I resize a Tmux pane using my mouse instead of my keyboard. It’s a habit from my GUI-informed past.

Here’s how to accomplish this without a mouse.

To resize the focused pane left one cell (from the Tmux prompt):

:resize-pane -L

Resize pane number 3 right 10 cells:

:resize-pane -t 3 -R 10


Jump Back To The Latest Jump Position In Vim

Any sort of jump motion, such as gg or 121G, will be recorded in your Vim session’s jump list. If you’d like to return to the latest position in your jump list, you can tap '' within normal mode.

You can then tap '' again and you’ll be returned to the position you were just at. This is great if you want to toggle back and forth between your current position and the previous position.

If the latest jump position is not within the current buffer, then you will be jumped to the initial cursor position at the top of the file.

You can learn more about this by reference :help jump-motions, :help jumplist, and :help ''.

h/t Jake Worth

Jump Back 🐇

A Vim motion I’ve really been loving lately is '' or ``, which returns you to the previous jump position. It references the previous jump, so using it twice in a row will toggle you back and forth between two locations.

I use this a lot after jumping to the next occurance of a word with *, and then changing that word in some way so I can’t return with *. If you’re using normal mode most of the time, this command can help you walk back through your thought process.

For more info:

:help ''

Compile ReasonML To Native With Dune

Dune is “a composable build system for OCaml” with out-of-the-box support for ReasonML. Dune can be used for a lot of things, but in simplest terms it can be used to compile ReasonML programs into native executables.

Considering the following ReasonML program.

/* */
print_endline("Hello, Reason!")

We can then create the following Dune build file.

;; dune
 (name hello_reason))

If we then run dune build hello_reason.exe, then Dune will compile the into a hello_reason.exe executable that can be found in build/default. Run it and see the output.

Read more in the Quickstart guide.

ES6 Nested Destructuring

I picked this up a while ago on Twitter, use it all the time in my React code, and wanted to document it here. If you’re destructuring a JS object like this:

const { username, zip } = props.user;

A valid (and slightly better, in my opinion) refactor is this:

const { user : { username, zip } } = props;

As you add more destructured variables pulled from props, the object you’re referencing stays the same.

Note that this doesn’t define user— if that’s something you want, you have to destructure it on its own:

const { user, user : { username, zip } } = props;

While a little more verbose, I still think this makes for more maintainable destructuring long-term.

Doing Date Math In MySQL

MySQL has an array of functions for interacting with date and datetime values. If you’d like to do math with a date to compute a date in the future or the past, you can use the DATE_ADD() and DATE_SUB() functions.

mysql> select now() Now, date_add(now(), interval 10 minute) '10 Minutes Later';
| Now                 | 10 Minutes Later    |
| 2018-10-18 15:53:29 | 2018-10-18 16:03:29 |

mysql> select now() Now, date_sub(now(), interval 9 day) '9 Days Earlier';
| Now                 | 9 Days Earlier      |
| 2018-10-18 15:54:01 | 2018-10-09 15:54:01 |

There are equivalent ADDDATE() and SUBDATE() functions if you prefer.

Check out the docs for more details.

Get The Time Zone Of The Client Computer

The resolvedOptions function on Intl.DateTimeFormat.prototype provides a number of pieces of information about the client computer. It includes information such as the locale and the numbering system. It also has the time zone for that machine.

Try running this line of JavaScript in your own browser.

$ Intl.DateTimeFormat().resolvedOptions().timeZone

When I run it, I get America/Chicago.

You can use this within your client-side code as a way of determining in which time zone your users are.

Catching errors in React (16 and up)

If an error is thrown while rendering React, React unmounts the entire tree.

In production, this might not be behaviour you want. The behaviour might be inconsequential to the user’s current path and why stop the user cold due to an unanticipated state?

React provides a function componentDidCatch to help manage exceptions and keep the consequence of the error localized to a specific part of your component tree.

This blog post describes the concept of an ErrorBoundary which can look like this:

class ErrorBoundary extends Component {
  componentDidCatch(error, {componentStack}) {
    console.log("error", error)
    console.log("componentStack", componentStack)

  render() {
    return this.props.children;

Using the componentDidCatch lifecycle function this component will catch any error thrown by its children. If an error is thrown it will not render and none of it’s children will render, but all components in different sections of the component tree will render.

The second argumunent to componentDidCatch is an object containing a key called componentStack which is a nice stack provided by React.

H/T Josh Branchaud

Change Prompt in Z Shell

When I live code, or share terminal commands in a demonstration, I don’t want my customized terminal prompt included in that information. It’s noisy.

Right now I’m changing this in Z Shell via that PROMPT variable.

# Complex prompt
jake@computer-name: echo $PROMPT

# Simple prompt
jake@computer-name: PROMPT="$ "
$ echo 'ready to live code'
ready to live code

Go Tests Uncached

Go caches test results, and this can be a problem if you have flickers, are benchmarking your tests, or just want to run all the tests every time.

Disable caching with GOCACHE:

$ go test ./...
ok      monkey/ast      (cached)
ok      monkey/lexer    (cached)
ok      monkey/parser   (cached)
$ GOCACHE=off go test ./...
ok      monkey/ast      0.005s
ok      monkey/lexer    0.005s
ok      monkey/parser   0.005s

Spreading nil Into a Ruby Array

Spreading nil into an array doesn’t add an entry into a Ruby array:

[*nil] # => []
a = [1, 2, 3]
[*nil, *a] # => [1, 2, 3]

One might expect this to insert nil in the array, but this isn’t the case. This feature could be useful when passing dynamically assigned, nullable items into an array.

def foo(arg)

nullable_var = params[:foo]
foo(nullable_var).each { |x| act_on(x) } # => [] if nullable_var is nil

Outer join with ActiveRecord `references` method

I want to join posts to comments regardless if comments exist or not.

You can use includes for that:


But that results in 2 queries, one to get all the posts, and one to get all comments that have the relevant post_id.

With references you can turn this into an outer join:


Now we’re getting all the information we need with just 1 query.

Check out the Active Record guides here

Return value of snapshot in componentDidUpdate

React has a rarely used lifecycle method getSnapshotBeforeUpdate where you get the opportunity to look at your current DOM right before it changes.

The return value of this method is the third parameter of componentDidUpdate.

getSnapshotBeforeUpdate(prevProps, prevState) {
    return "value from snapshot";

componentDidUpdate(prevProps, prevState, snapshotValue) {

The above code will output value from snapshot in the log.

The purpose for getSnapshotBeforeUpdate given in the React documentation is for making sure a value that can’t be set with rendering - like the scroll position - is exactly where you want it based on the state it was before the rerender.

My code example is here.

Group dates by week in Postgres

Timestamps are everywhere in our postgres tables. To group them together you can use date_trunc to normalize the timestamp by minute, hour, day, etc.

You can also normalize the date by week.

> select date_trunc('week', now());
2018-10-08 00:00:00+00

The above example returns the first day of the week for the current moment which is a Monday. Postgres truncates dates to Monday rather than Sunday.

To group dates by week just use the truncated value in both the select clause and the group clause.

select count(*), 
  date_trunc('week', request_time) 
from requests 
group by 
  date_trunc('week', request_time) 
order by date_trunc desc ;

Ignore just one statement with Prettier

Prettier works great for formatting your javascript. In general, it makes formatting something that you don’t have to think about anymore, but occasionally you’ll run across something that you want to format in your own custom way.

You can include a prettier-ignore comment to achieve this goal.

// prettier-ignore
const minesweeperMap = [
    'B', ' ', ' ',
  ' ', 'B', ' ',
  'B', ' ', ' ',
  ' ', ' ', 'B',

const bombs =     4;

When you run prettier on the above code, the declaration of bombs line will be changed to remove unneeded spaces, but the minesweeperMap declaration will be left unchanged.

Pipe all output from a command (stderr & stdout)

When you write a bash/zsh script relying on pipes normally you will not be able to pipe through text from the stderr output with a normal pipe.

For example, curl -v prints some information about the request, including it’s headers and status into stderr.

If we simply try to pipe the output of curl -v into less we will not see the verbose header and request info:

curl -v | less


<html lang='en-US'>
<meta charset='UTF-8'>
<title>Ruby on Rails, Elixir, React, mobile design and development | Hashrocket</title>

But if we want the stderr output as well we can use the |& syntax:

curl -v |& less


* Rebuilt URL to:
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
* Connected to ( port 443 (#0)
<html lang='en-US'>
<meta charset='UTF-8'>

🍒 Bonus:

We can also pipe through ONLY the stderr:

curl -v |1>& less

Output (will not contain the html response):

* Rebuilt URL to:
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

h/t Thomas Allen

Git: Stash Everything

Running the git stash command will take all the changes to tracked files in the working directory and stash them away. You can tack on the --include-untracked flag to make sure that untracked files are also included in the stash.

You can take this a step further with the --all flag. This will stash everything included files that you’ve told git to ignore.

You probably don’t want to do this. I ran this command and realized after the command hung for about 10 seconds that I had just stashed the node_modules directory.

See man git-stash for more details.

Restore from Diff in Vim

I often use diffs in Vim to compare my current file with the previous Git commit. vim-fugitive is one way to do this, via commands like :Gdiff or :Gvdiff (vertical option).

From this diff state, we can restore the code from one pane to the other using the command :diffput. This is useful for restoring one line, or a range, from the previous commit to my working copy.

CSS !important Is Not Supported By Inline Styles

You can get pretty far with React’s inline styling of components. There are however a few limitations. One such limitation is that the !important clause is not supported.

If you try applying !important to an inline style like so:

<div style={{ color: "red !important" }}>
  My div

You’ll be disappointed when you open up the browser and inspect that div tag. The color rule will be ignored and excluded from the output html.


Shell parameter expansion

Shells can perform variable expansion, this is really useful for default argument variables in shell functions.

Here is a simple example of assigning a variable from an argument or defaulting to running a different shell command:

clog() {
  log_date=${1-`date +%Y-%m-%d`}
  git log --after="$log_date 00:00" --before="$log_date 23:59"

This allows me to write

clog to default to today’s date or

clog 2018-10-02 to look at the logs from yesterday

The date in the example clog 2018-10-02 would come through as $1 in the function, so ${1-`date`} means run this shell command if there is no $1.


Show Git Changes For Files That Match A Pattern

The git show command allows you to view the changes associated with a reference, such as a commit sha (e.g. git show 86748aacf14e).

Consider a commit that has changed a bunch of JS files as well as two CSS files. If we run git show abcd1234, we will see all of the changes to each file which can result in quite a bit of noise. What if we only want to view the changes to the CSS files?

We can instruct the command to only show changes to files that match a pattern by tacking that pattern on to the end.

$ git show abcd1234 *.css

Alternatively, we could scope the output of the command to the files that live in a certain directory.

$ git show abcd1235 src/css

Wrap A ReasonReact Component For Use In JavaScript

Consider the following ReasonReact component for displaying a greeting.

let component = ReasonReact.statelessComponent("Hello");

let make = (~name, _children) => {
  render: _self =>
    <p> {ReasonReact.string("Hello, ")} {ReasonReact.string(name)} </p>,

If we will just be using this component in a ReasonML context, then that is all we need.

If we want this component available for use in a JavaScript file, we have a little more work to do. We need to define the shape of the component’s props using a bucklescript directive and then wrap the component so that it gets appropriate exported for a JavaScript context.

Here is what that looks like.

[@bs.deriving abstract]
type jsProps = {name: string};

let default =
  ReasonReact.wrapReasonForJs(~component, jsProps =>
    make(~name=jsProps->nameGet, [||])

Our only prop is name which is a string. The wrapReasonForJs function and accompanying binding to default mean that we can import the compiled JS-equivalent like so:

import Hello from 'src/components/';

See the docs for more details on Reason/JS interop.

Get ONLY PIDs for processes listening on a port

The lsof utility on Linux is useful among other things for checking which process is listening on a specific port.

If you need to kill all processes listening on a particular port, normally you would reach for something like awk '{ print $2 }', but that would fail to remove the PID column header, so you would also need to pipe through tail -1. It get pretty verbose for something that should be pretty simple.

Fortunatly, lsof provides a way to list all the pids without the PID header specifically so you can pipe the output to the kill command.

The -t flag removes everything from the output except the pids of the resulting processes from your query.

In this example I used a query to return all processes listening on port 3000 and return their PID:

lsof -ti tcp:3000

The output of which will look something like:


This is perfect for piping into kill using xargs:

lsof -ti tcp:3000 | xargs kill

No awks or tails necessary! 🐕

Format The Current ReasonML File Within Vim

I’m editing a .re file within Vim. I haven’t yet wired up refmt to something like ALE for automatic formatting on save. By the time I’m done with my changes, indentation is a mess.

I can still take advantage of refmt to clean up my file.

:!refmt --in-place %

Running that command in Vim will cause the current file to be formatted.

How does it work?

It shells-out to refmt which does all the heavy lifting. The --in-place flag means that the target file will be re-written by the formatted result. The % is a handy Vim shorthand for the path and name of the current file.

Animate Smoothly Between Two Background Colors

CSS animations allow you to set up simple rules that the rendering engine can then apply to create smooth transitions between style states.

To smoothly transition between two background colors, we can create a keyframes at-rule with a fitting name (e.g. pulse).

@keyframes pulse {
  0% {
    background-color: red;
  50% {
    background-color: blue;
  100% {
    background-color: red;

Over the course of a single animation, this set of rules will start the background color at red, transition to blue 50% of the way through, and then back to red again.

We can then apply this animation within any of our CSS class definitions.

.square1 {
  animation: pulse 2s infinite;
  width: 100px;
  height: 100px;

Anything with a class of square1 will have a width and height of 100px as well as a pulsing background color.

Notify your application when browser goes offline

At JS Camp this past weekend I saw Josh Beckman give a talk about the appropriate time to trigger a page refresh when the single page application has received some updates.

A key component of that is knowing whether you have an internet connection or not.

Fortunately there is a browser event, offline, that will help you keep track of your offline status.

window.addEventListener('offline', () => console.log('is offline'))

When I turn the wifi off, then is offline is logged to the console.

You can also take advantage of the navigator.onLine (yes a capital L) property to determine whether your application currently has an internet connection.

Reference rejected values on conflict in postgres

I have a table of fruits and I have their quantity:

create table fruits (name text primary key, quantity int);

In that table I have a row for apples:

insert into fruits (name, quantity) values ('apple', 10);

So generally, when I try to insert another apples row, because name is the primary key, I’ll get a duplicate key error:

insert into fruits (name, quantity) values ('apple', 11);
duplicate key value violates unique constraint "fruits_pkey"

So if I don’t know wether to insert or update I can use the on conflict functionality in postgres to set the quantity even if apples is already there.

insert into fruits (name, quantity) values ('apple', 13) on conflict (name) do update set quantity = excluded.quantity;

I can use the excluded special table to reference the row that was rejected by postgres and which contains the quantity that I want to update the row quantity to.

Parameter filtering in Elixir Phoenix logs

Sometimes you want to filter out parameters that are being logged (think GDPR compliance). Enter Phoenix’s handy config filter_parameters :

config :phoenix, :filter_parameters, ["password", "birthday"]

Or if you want to be extra safe, you can filter all parameters and only whitelist ones you want to see. For example: id and order:

config :phoenix, :filter_parameters, {:keep, ["id", "order"]}

Find The Process Using A Specific Port On Mac

The netstat utility is often recommended for finding the PID (process ID) bound to a specific port. Unfortunately, Mac’s version of netstat does not support the -p (process) flag. Instead, you’ll want to use the lsof utility.

$ sudo lsof -i tcp:4567

Running this will produce a nicely formatted response that tells you several pieces of information about the process bound to :4567 including the PID.


Animate ReactNative in ClojureScript with Reagent

Reagent uses ratoms to refresh components. When the state of a ratom is changed, components that deref that state re-render. ReactNative Animation uses a similar technique: changes to an Animated.Value cause a re-render. I was afraid these concepts would collide, and I’d have to bypass Reagent using it’s low-level api to use animations. But much to my joyful surprise, Animated.Value changes trigger a re-render in normal Reagent components.

(ns my-app.animation
    ["react-native" :as ReactNative]
    [reagent.core :as r]))

(def animated (.-Animated ReactNative))
(def text (r/adapt-react-class (.-Text ReactNative)))
(def animated-value (.-Value animated))
(def animated-view (r/adapt-react-class (.-View animated)))

(defn testview []
  (let [bounce-value (new animated-value 0)]
    (.setValue bounce-value 1.5)
    (-> bounce-value
        (animated.spring #js {:toValue 0.8 :friction 1})
    (fn [] [animated-view
            {:style {:flex 1
                     :transform [{:scale bounce-value}]
                     :background-color "red"
                     :border-radius 10
                     :shadow-color "#000000"
                     :shadow-opacity 0.7
                     :shadow-radius 2
                     :shadow-offset {:height 1 :width 0}}}
            [text "test"]])))


This may look complex, but compare it to the low level Reagent api used in other examples.

Enable gzip for all phoenix responses

Enabling gzip for static assets in phoenix couldn’t be simpler. In lib/myapp_web/endpoint.ex change gzip from false to true:

 plug(Plug.Static, at: "/", from: :tilex, gzip: true, only: ~w(assets ...))

But why stop there? We can compress our dynamic document bodies just as easily. In config/prod.exs, add compress: true to the http config of the endpoint.

config :my_app, MyAppWeb.Endpoint,
  http: [port: {:system, "PORT"}, compress: true]

Using vimscript lambdas with map

Vimscript has lambda functions, check them out with :help lambda.

You don’t have to reference an argument with the a: prefix and returns are implicit.

Generally they take the form of:

:let Add = {a, b -> a + b}
:echo Add(1, 2)

You can also pass a lambda to the map func:

:let fruits = ['apple', 'orange', 'banana']
:echo map(fruits, {key, val -> "key: " . key . " val: " . val})
['key: 0 val: apple', 'key: 1 val: orange', 'key: 2 val: banana']

Alwyas be careful with vim’s map() though. It Mutates

To make sure you don’t mutate the list you are mapping over, use copy().

:echo map(copy(fruits), {key, val -> "key: " . key . " val: " . val})

What is that chäräcter ?

If you are in vim and you encounter a weird looking unicode character, and you want to know what the codepoint(s) for that character is/are you can use ga

If my cursor is over ä and I use ga I get output:

<ä> 228, Hex 00e4, Octal 344

If my cursor is over and I use ga I get output:

<a>  97,  Hex 61,  Octal 141 < ̈> 776, Hex 0308, Octal 1410

The first character is a precombined Unicode character, the a with the umlaut already has its own unicode character.

The second character is an a combined with a diacrital mark, and the output of ga reflects that by listing each utf codepoint that composes the character.

Select a Square With Mac Preview

Lately I’ve been taking screenshots of code and my terminal. They seem to look the best when they’re square; that shape translates better to a variety of project management tools and social media platforms.

Mac Preview lets you select part of an image down to the pixel for cropping, and I have found selecting a perfect square very difficult. The solution? Select with SHIFT + click to force a square-shaped selection. ⌘ + K to crop.


Find a Capybara node with regex

My pair and I faced a situation yesterday where we had to find a node with two separated pieces of text.

    <div>Some Other Text</div>
  <div>Some Other Text</div>
  <div>Some Other Text</div>

We wanted to find a node with text “Something” and text “Orange” in our Capybara test.

The find method has a text option that you can pass a regex to.

find("section", text: /Something.*Orange/)

And initially this wasn’t working because of a line break and so we had to use the multiline flag (m).

find("section", text: /Something.*Orange/m)

The five values that define cursor position in vim

We generally think of a cursor having two coordinates, x and y, row and column, but when I call getcurpos() I get a list with 5 values in it.

:help getcurpos()
:echo getcurpos()
[0, 4124, 8, 0, 57]

Here are the definitions of those numbers:

bufnum - the number of the buffer when calling getpos("'A") to get the position with a mark. Always 0 with getcurpos()

lnum - The line number

col - The number of chars used to go this far to the right. is 2. 10 spaces is 10.

off - Is the number of chars past the end of the line. 0 unless using virtualedit.

curswant - Is the column you started on when starting to navigate with j and k. You might start on col 20, and go down to a line with only 10 columns in which case the cursor would be on col 10, but curswant would still 20. The next navigation to a line with more than 20 characters would put you back on col 20.

With virtualedit turned on curswant will always be the column position of the cursor.

Rendering Emojis With Unicodes in Javascript

Ordinarily you can render an emoji in Javascript by using its four-character Unicode code point as follows:

(React JS [JSX] Sample)

<span>{'\u263B'}</span> => <span>☻</span>

Sometimes, however, the Unicode code point for an emoji is more than four characters long and the above method for rendering doesn’t work. In ECMA6, the following syntax will work for emojis whose Unicode code point length is more than four (1):

<span>{'\u{1F4A9}'}</span> => <span>💩</span>


  1. This has only been tested with a five-character Unicode code point.

Sort numerically

The sort command :sort in vim sorts by the string representation by default. For numbers this is weird. If you have 2, 12, and 1 on separate lines they end up sorted like this:


To sort them numerically you can pass the n argument to the sort command, like this :sort n which gives you what you want:


Speed up webpacker by excluding dev dependencies

In our latest project, we were experiencing some long build times after accreting features for a few monhts.

By default webpacker pulls in all of your node_modules for parsing and optimization by babel, which can be quite unneccessary. In order to exclude your devDependencies from that process, you can add the folling code to your development.js config:


var package = require('../../package.json');
var excluded = Object.keys(package.devDependencies).map(function(dep){
  return new RegExp("node_modules/" + dep);

module.exports = merge(environment.toWebpackConfig(), customConfig, {
  module: {
    noParse: excluded

The noParse option can possibly lead to errors when some packages are excluded from parsing (notably, css-loader), you can tweak which dependencies reside in dependencies vs devDependencies in your package.json in order to avoid these issues.

Making virtualedit a local option

virtualedit is a global option. This means that when you call setlocal virtualedit it’s not set just for this buffer but for all windows and all buffers. This is confusing, but only options labeled local to buffer in help can be set to the local buffer. virtualedit is labeled as global.

However there is a hack. You can simulate this as a buffer local option by setting it on BufEnter and unsetting it on BufLeave.

In my .vimrc.local I have

autocmd BufNewFile,BufRead,BufEnter *.part setlocal virtualedit+=all
autocmd BufLeave *.part setlocal virtualedit-=all

Set it when you enter, unset it when you leave, and now the setting is confined to the buffer you’d like to use it in.

Client Connection Vars with Ecto

Postgres has dozens of connection variables it will take, a couple of my favorite ones are statement_timeout and application_name.

Ecto takes a parameters connection option, which is a keyword list of connection parameters.

# dev.exs


# Configure your database
config :myapp, Myapp.Repo,
  adapter: Ecto.Adapters.Postgres,
  database: "myapp_dev",
  socket_dir: "/var/run/postgresql",
  parameters: [application_name: "My App Development", statement_timeout: "5000"],
  pool_size: 10

Example of statement_timeout being respected in Ecto:

Ecto.Adapters.SQL.query!(Myapp.Repo, "select pg_sleep(86400)")

** (Postgrex.Error) ERROR 57014 (query_canceled): canceling statement due to statement timeout
    (ecto) lib/ecto/adapters/sql.ex:200: Ecto.Adapters.SQL.query!/5

Client Connection Variables references:

Use a unix socket with Ecto

Ecto allows the use of a unix socket to connect to postgres, instead of TCP. In order to use a unix socket in a exs file, you should remove the hostname list item, and provide the socket_dir list item.

# dev.exs


# Configure your database
config :myapp, Myapp.Repo,
  adapter: Ecto.Adapters.Postgres,
  database: "myapp_dev",
  socket_dir: "/var/run/postgresql",
  pool_size: 10