tag:protips.maxmasnick.com,2013:/posts Dev pro tips 2018-11-02T16:07:17Z by Max Masnick tag:protips.maxmasnick.com,2013:Post/1339318 2018-11-02T16:04:51Z 2018-11-02T16:07:17Z Fixing files that should have been pointers in LFS but weren't

There is a relatively easy fix for a message from git lfs like:

Encountered n file(s) that should have been pointers, but weren't

If the files in question are already on a remote and you don't want to rewrite history, run:

git lfs migrate import --no-rewrite path/to/file.ext

This will create a new commit moving path/to/file.ext to LFS.

If you do need to rewrite history, see the documentation for migrating data to LFS.

To check whether this worked, run:

git lfs ls-files | grep path/to/file.ext

You should see an entry for path/to/file.ext in the resulting output.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1314602 2018-08-23T21:51:28Z 2018-08-23T21:51:29Z Work-around for broken Pocket bookmarklet

I've found that Pocket's bookmarklet is not reliable in Safari and Safari Technology Preview due to browser security measures against 3rd party cookies. This results in their official bookmarklet asking me to "Please login" every time I try to use it.

Fortunately, there is an easy work-around with a very simple bookmarklet:

window.location.href = 'https://getpocket.com/edit?url='+encodeURI(window.location.href)

You can use the Bookmarklet Maker to turn this code into an actual bookmarklet.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1280256 2018-05-04T16:06:06Z 2018-05-04T16:06:06Z Fix FileVault's "Some users are unable to unlock the disk" error when the APFS boot disk is manually encrypted with a "Disk Password"

This happened to me because I restored my boot disk from a full disk clone (thanks to a bad macOS update installation). I didn't want to restore to an unencrypted disk, so when I booted from my backup disk to do the restore, I used Disk Utility to encrypt my internal boot disk with a password.

After encrypting and then cloning the backup to my boot drive, I was greeted with a screen like this on my first boot from my boot drive:

Fine, no problem. I entered my disk password, and the normal login screen showed up. I entered my user password and everything was working...except I could not re-enable unlocking my disk with my user's password:

After searching around for how to fix failure of "Enable users" when "Some users are unable to unlock the disk", I discovered that there are a set of command line utilities for dealing with FileVault and I was able to fix the problem by decrypting the disk and then re-enabling FileVault.

Here's the command to decrypt: diskutil apfs decryptVolume /dev/disk1s1

To get "/dev/disk1s1", I simply looked at the info for my hard drive ("HD") in Disk Utility. (Normally this would be named "Macintosh HD", but I always rename mine.)

Then I simply re-enabled FileVault through System Preferences.

Warning: Messing around with disk encryption (or messing around with anything involving your boot disk) is risky. Always have a known good backup before you try anything like this, and proceed at your own risk – I am not responsible if you break your disk trying to follow these instructions.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1262798 2018-03-18T20:12:53Z 2018-03-18T20:12:53Z Unroll/extract/read tweets from a tweetstorm

I've found a few decent ways to extract all the tweets from a "tweetstorm" for easier reading or quoting:

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1262081 2018-03-16T17:15:32Z 2018-03-16T17:15:32Z PyCharm: View DataFrame or Series using SciView from the "Evaluate" window with a keyboard shortcut

When using PyCharm for debugging data science code, I often want to view a Pandas DataFrame from PyCharm's interactive debugger. It took me a bit to figure out how to do this from the keyboard — here's what I do:

  1. While debugging, open the "Evaluate" window (bound to cmd-; in my configuration).
  2. Type in the name of the variable for the DataFrame and press enter, which gives me this:
  3. Now the question is how to activate the "View as DataFrame" button with the keyboard (see green arrow above). Turns out you can bind "View as Array" to a keyboard shortcut, which will also trigger "View as DataFrame". So I tab from the "Expression" text field to the "Results" area and then hit my "View as Array" shortcut (cmd-enter). This opens the DataFrame in SciView.

Here's the "View as Array" keyboard shortcut configuration:

I've found "floating mode" to work best with SciView. cmd-w will close SciView in floating mode, but for some reason when I do this, the "Evaluate" window will lose focus and I can't figure out how to focus it again without mousing. Keyboard Meastro to the rescue here:

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1248798 2018-02-16T22:18:34Z 2018-02-16T22:18:34Z Open tweet in Twitterific bookmarklet

Source: var x = /twitter.com\/.*\/status\/([0-9]+)/.exec(window.location.href); if(x == null) {alert("Doesn't look like this is a tweet.")} else {window.location='twitterrific:///tweet?id='+x[1]};

Converted to bookmarklet: javascript:(function()%7Bvar%20x%20%3D%20%2Ftwitter.com%5C%2F.*%5C%2Fstatus%5C%2F(%5B0-9%5D%2B)%2F.exec(window.location.href)%3B%20if(x%20%3D%3D%20null)%20%7Balert(%22Doesn't%20look%20like%20this%20is%20a%20tweet.%22)%7D%20else%20%7Bwindow.location%3D'twitterrific%3A%2F%2F%2Ftweet%3Fid%3D'%2Bx%5B1%5D%7D%7D)()

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1204061 2017-11-08T18:09:55Z 2017-11-08T18:10:05Z Trim whitespace with AppleScript

This is directly from macscripter.net, but they have some encoding issues that I've fixed:

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1190796 2017-09-12T21:44:14Z 2017-09-12T21:44:14Z Make YouTube videos full screen on iPad ]]> Max Masnick tag:protips.maxmasnick.com,2013:Post/1190258 2017-09-11T02:17:56Z 2017-09-11T02:25:27Z Keyboard Maestro macro to open .pickle file in IPython

I often want to view the contents of .pickle files on my computer. I like doing this in the IPython REPL, so I would manually open a new Terminal window, switch to my data science virtualenv, import pickle, and then load the .pickle file in question into a variable. Sounds like a prime target for automation, eh?

Here's a Keyboard Maestro macro that will take the selected .pickle file in Finder and open it up in IPython (inside iTerm2), assigning it to the variable x.

Here's what it looks like (the macro is triggered through LaunchBar with this custom action):

After the macro runs, I type in x to show the object in the Pickle file (in this case, it's just {"hello": "world"}.

Here's what the macro looks like in Keyboard Maestro:

Here's the code:

Note that this requires your Python virtualenv to be set up like this and you have to have a "data" virtualenv. If either of these things aren't true, you'll need to modify the shell commands in the AppleScript accordingly.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1186058 2017-08-23T21:04:04Z 2017-08-23T21:04:04Z Add padding under each Jupyter cell

Put one of the following in a Jupyter notebook cell and run. If you make changes, clear cell contents, save, and refresh the browser.

All cells:

import IPython.core.display as di

$('<style>.cell { margin-bottom: 100px !important;}</style>').appendTo('head');
""", raw=True)

To add padding just after code cells:

import IPython.core.display as di

$('<style>.code_cell { margin-bottom: 100px !important;}</style>').appendTo('head');
""", raw=True)

To add padding just between code cells:

import IPython.core.display as di

$('<style>.code_cell+.code_cell { margin-top: 100px !important;}</style>').appendTo('head');
""", raw=True)
Max Masnick
tag:protips.maxmasnick.com,2013:Post/1179092 2017-07-31T21:12:29Z 2017-07-31T21:12:29Z Show currently executing queries in MySQL


Max Masnick
tag:protips.maxmasnick.com,2013:Post/1163180 2017-06-12T15:18:20Z 2017-06-12T15:18:34Z Fix broken camera on macOS without restarting

Sometimes the built-in camera on my Mac will stop working (no green light; no video). Restarting will fix it, but this appears to also work: sudo killall VDCAssistant

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1158719 2017-05-30T03:15:48Z 2017-10-14T13:42:20Z Disabling the startup chime on macOS Sierra

From How-To Geek:

Run sudo nvram SystemAudioVolume=%80 in the Terminal to disable the startup chime. Works like a charm on my late 2014 iMac.

To re-enable, run sudo nvram -d SystemAudioVolume (I didn't test this part).

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1153468 2017-05-12T11:12:34Z 2017-05-12T11:12:34Z macOS: Set audio balance to middle to correct drift with an AppleScript

On multiple Macs, I have had the left/right balance of my headphones randomly drift. Apple says this can be caused by changing the volume while the CPU is under load, which doesn't seem to be what is happening to me. In any case, it's annoying.

Here's an AppleScript that will automatically reset the sound balance to the middle for the current output device:

There's also a $5 app called Balance Lock that in theory will solve this problem – I haven't tested it.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1152686 2017-05-09T11:34:46Z 2017-05-09T11:34:46Z Loading multiple MySQL result sets into Pandas DataFrames

Note: This could be done in a loop. I don't do this because I often have results set-specific code that I want to run (e.g. renaming variables).

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1150522 2017-04-30T20:21:17Z 2017-04-30T20:21:17Z Darkening gray text with ImageMagick

The following ImageMagick command will take an image with gray text (and a white background) and make the text black.

magick convert -level 80%,100%,1 in.png out.png

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1149147 2017-04-25T12:11:34Z 2017-04-25T12:11:34Z 2x2 tables in Jupyter/IPython notebooks

I've written some helper methods for quickly generating 2x2 tables (or contingency tables, cross tabulations, crosstabs) in Jupyter/IPython notebooks. This achieves the same thing, more or less, as Stata's tabulate twoway command.

The notebook below has the helper methods and examples of their output. I've added these to my ipython-setup file because I use them so frequently.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1103156 2016-10-28T18:23:11Z 2016-10-28T18:23:11Z Hide all gifs with CSS
img[src*="gif"] {
    display: none;
Max Masnick
tag:protips.maxmasnick.com,2013:Post/1085541 2016-09-01T04:20:02Z 2016-09-01T04:20:02Z Get SHA1 hash for every file in a folder on OS X

cd path/to/folder
ls * | xargs openssl sha1


Max Masnick
tag:protips.maxmasnick.com,2013:Post/1081438 2016-08-15T20:01:18Z 2016-11-15T11:51:42Z Python: Get git hash for the last commit modifying the current folder
from os import path
p = path.dirname(path.abspath(__file__))
hash = subprocess.check_output(["git", "rev-list", "-1", "HEAD", "./"], cwd=p).strip()
Max Masnick
tag:protips.maxmasnick.com,2013:Post/1078612 2016-08-03T22:39:01Z 2017-12-08T19:54:32Z Querying MySQL from Stata

Step 0: Install the ODBC driver

  1. Download and install the iODBC driver manager. The next step will fail if this isn't installed first.
  2. Download and install the ODBC driver.

Step 1: Set up ODBC driver

See these instructions. My ODBC configuration (~/.odbc.ini) looks like:

[ODBC Data Sources]
mysql = MySQL ODBC 5.3 ANSI Driver

Trace         = 0
TraceAutoStop = 0
TraceFile     = 
TraceLibrary  = 

Driver      = /usr/local/lib/libmyodbc5a.so
Description = desc here
SERVER      = localhost
PORT        = 3306
USER        = root
PASSWORD    = passwordhere
DATABASE    = databasehere

Make sure your driver location is correct. It could also be something like /usr/local/mysql-connector-odbc-5.3.7-macos10.12-x86-64bit/lib/libmyodbc5a.so.

Step 2: Make a ODBC call from Stata

For example:

set odbcdriver ansi
odbc list
// Option 1
odbc load, table("tablename") dsn("mysql") clear noquote
// Option 2
odbc load, exec("select * from tablename") dsn("mysql") clear noquote

Using a plugin is another option, but I haven't tried this.

Update: Loading in SQL from an external file

This allows you to do something like:

cd "/path/to/your/folder"
loadsql using your-sql.sql, dsn(mysql)

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1063375 2016-06-14T17:01:41Z 2018-03-01T17:24:53Z Literate Python setup with pweave and Atom

In the past I’ve used IPython/Jupyter notebooks for literate programming, but writing code in the browser is not a great experience and I was having terrible environment issues. I started looking at alternatives, and settled on trying out pweave. It’s the same idea as IPython, allowing me to intersperse code and output with prose, but rather than using the browser I can use a standard programming editor. (It also solves my environment problem.)

The setup for getting a pweave workflow that still has all the nice parts of an IPython notebook is a little involved, so here’s what I did:

  • Get the Atom editor (I generally use Sublime Text, but it can’t run Python inline)

  • Set up a virtualenv and pip install "ipython[notebook]" Pweave

  • Install the following Atom packages:
  • Make the following configuration changes:
    • Append to styles.less:

      // Hydrogen output - font size is too small  
      .hydrogen.output-bubble pre {  
        font-size: 16px !important;  
      // Hydrogen - hack for 2x images  
      .hydrogen.output-bubble .bubble-result-container img {  
        width: 50% !important  
    • Append to config.cson:

          commands: [  
              command: "expand-region:select-inside-back-ticks"  
              recursive: true  
    • Append to keymap.cson:

      '.platform-darwin atom-text-editor':  
        'cmd-enter': 'hydrogen:run',  
        'cmd-shift-space': 'expand-region:expand'
    • In the settings under Settings > Packages > Hydrogen:
      • Kernel Mappings (this enables support for .pmd files): {"pweave markdown": "Python 2"}

      • Startup Code:

        {"Python 2": "import matplotlib as matplotlib_import_only\nmatplotlib_import_only.use('Agg')\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\npython=None"}

        This does a few hacky things:

        • import matplotlib as matplotlib_im ... rt_only.use('Agg'): fix for this issue with a bouncing rocketship dock icon
        • %matplotlib inline: display figures inside Atom rather than in a separate window
        • %config InlineBackend.figure_format = 'retina': turns on high-resolution figures, which are displayed by Atom as double-sized low-resolution figures without the hack in styles.less above
        • python=None: a hack to avoid an error when automatically selecting and running a block of Python code

Some of this configuration is necessary to just get hydrogen to run Python code.

The rest fixes a major problem with pweave: it’s easy to run one line of code, and it’s easy to run all the code in a file, but how do I run only one block of code? (This is equivalent to being able to running an entire cell in IPython with shift-enter.)

The solution is to use the expand-region plugin to select the current block of code, and the python=None hack to avoid an error when it selects the “python” in ```python.

Here’s what it looks like in action:

To convert the .pmd file to a .html that can be shared, simply run pweave -f md2html test.pmd. Here's what the output from the above example looks like.


  • Remember to open Atom from the command line after activating your virtualenv (see the "Usage" section here).
  • In order to get the pweave command to run with my virtualenv, I manually edited the shebang in /usr/local/bin/pweave to directly point to the Python binary in my virtualenv: #!/Users/max/.virtualenvs/data/bin/python
Max Masnick
tag:protips.maxmasnick.com,2013:Post/1050816 2016-05-13T15:22:48Z 2016-05-13T15:22:48Z Reserved words lists in Ruby/Rails, Python, MySQL, and PostgreSQL ]]> Max Masnick tag:protips.maxmasnick.com,2013:Post/1048946 2016-05-09T17:41:00Z 2016-05-09T17:41:00Z Disable "mirror screen" keyboard shortcut (Command+F1 or Command+Brightness down)

Thanks to this Ask Different post and Karabiner, I've been able to disable the very annoying "mirror screen" keyboard shortcut.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1045660 2016-05-02T18:12:40Z 2016-05-26T18:03:29Z Keyboard Maestro: Convert Markdown to JIRA Markup

JIRA uses its own plain-text markup syntax, which I don't like as much as Markdown.

Fokke Zandbergen has a great online service for converting between JIRA markup and Markdown, but it's too cumbersome to use this when you are living in JIRA comments.

I re-appropriated Fokke's JavaScript into a Keyboard Maestro macro:

This will take the Markdown in the clipboard and paste it as JIRA markup whenever you type ";jira".

You can download the macro here.

Update – May 26, 2016: I have added support for multi-level unordered lists – the updated code is below.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1038871 2016-04-22T15:08:19Z 2016-04-22T15:08:48Z Move newest file in Downloads folder to the frontmost Finder window

Here's what you do:

  1. Open the folder where you want to move your newest download in Finder.
  2. Trigger the shell script below.

The file will magically be moved! You'll even get a Notification Center notification.

The shell script

Triggering the shell script

I use an AppleScript saved as a .app and triggered with LaunchBar. Here's the AppleScript:

do shell script "bash /Users/YOUR_USERNAME/path/to/script.sh"

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1038866 2016-04-22T15:00:45Z 2016-04-22T15:00:45Z Switching from TextExpander to Keyboard Maestro

The makers of TextExpander recently changed their pricing model with the release of v6 from paying once for each version to a subscription. I have no problem paying for software that makes me more productive, as TextExpander certainly does.

However, v6 of TextExpander started inserting non-breaking spaces rather than normal spaces at the beginning of Python code snippets: I would paste code into TextExpander with 4 space characters in a row, and it would come out with 3 NBSPs and one normal space. This effectively broke TextExpander for some of my most-used snippets.

Additionally, I've always had quality and stability issues with TextExpander and Smile's other product, PDFpenPro. For example, in TextExpander v5, it was impossible to tab from the snippet entry field to the abbreviation field. This infuriating problem was left unresolved for all of v5, but was thankfully fixed in v6. And PDFpenPro is simply much less stable than the alternatives (Preview.app and PDF Expert), with fairly frequent beachballs and freezes.

TextExpander v6 requires syncing to their central server. Given the software quality issues with their stand-alone apps, I'm very concerned about snippet loss from sync errors. I'm also not convinced that the QA issues with their native applications will ever be resolved, especially with the added burden of their new sync/subscription business model. And I am skeptical that their new business model will be sustainable long-term, given these other issues and the response of many users to their subscription pricing.

I decided it was time to look for an alternative.

Keyboard Maestro

Keyboard Maestro is general-purpose Mac automation software, which also has the capability to expand text snippets like TextExpander. I manually migrated my snippets over in about an hour (it can be done automatically too).

What I like

  • Keyboard Maestro (KM) seems generally more stable and performant than TextExpander (TE).
  • KM's two column UI for listing snippets is much more effective than TE's single column with collapsable headings.
  • KM allows multiple snippets with the same shortcut: when you type a conflicted shortcut, it shows a pop-up menu where you can select the snippet you want.
  • KM does lots of things besides snippets, like letting you ctrl-tab between multiple windows in the same application!

What I don't like

  • The KM quick search doesn't show the shortcut for the snippet (TE's quick search does).
  • Setting up new snippets in KM is a bit more complicated than with TE. This is because KM is a multi-purpose tool, and there are definitely benefits to specialization. But at least the tab key works as expected.

Other than these minor complaints, I've had zero problems with KM.

Setting up text expansion in Keyboard Maestro

Here's what my text expansion snippets ("macros" in KM parlance) look like – it seems like it's necessary to reset the system clipboard after expanding the snippet if you use the "paste" insert method rather than the "type" method:

Implications for this website

I've posted a number of tips on this site that use TextExpander. So far I have been able to convert these to Keyboard Maestro macros with minimal effort.

From now on, I will be posting KM macros rather than TE snippets.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1023170 2016-04-01T01:18:44Z 2016-04-01T22:43:12Z TextExpander Snippet: Path to Selected Finder Item

Thanks to this post on the Keyboard Maestro forum:


Right click on any Finder item, then hold Option. “Copy” becomes “Copy as Pathname”!!

(Thanks @anatomyofashane - you are a genius.)

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1020549 2016-03-27T19:14:21Z 2016-03-27T19:14:21Z Stata: "clear" results

From Dan Menes on the Stata listserv:

display _newline(200)

It doesn't technically clear the results window, but it does allow you to easily add a visual break in the results. I recommend putting this in a TextExpander snippet for easy access.

Max Masnick
tag:protips.maxmasnick.com,2013:Post/1018131 2016-03-22T20:26:56Z 2016-03-22T20:26:56Z TextExpander: Snippet to Get the URL of the Active Chrome Tab

Max Masnick