twitter github linkedin email

Álvaro Ramírez

02 December 2016 # Singapore notes

  • Supertree Grove (go at dusk, see lights turn on).
  • Singapore Botanic garden.
    • Ginger Garden.
    • Palms valley.
    • Orchid garden.
  • Sri Mariamman Temple.
  • Kusu Island?
  • Chilly crab (“Jumbo” Chilli Crab Restaurant in Clarke Quay or Harvest Seafood Restaurant)?
  • Afternoon tea?
    • www.tea-chapter.com.sg
  • Bumboats (£2.50 return) leave Changi Point between 6am and 9.30pm for the 10-minute crossing to Palau Ubin. Hire a bicycle in the village where the boats dock.
  • Haji Lane (colorful road).
  • Tiong Bahru 1930s public housing estate (**)
    • old-fashioned treats at Tiong Bahru Galicier (55 Tiong Bahru Rd).
  • Chinatown
    • Strangelets: quirky stuff from around the world.
    • 40 Hands: Allegedly one of most popular coffee joints.
    • BooksActually: Coolest book shop.
  • Keong Saik (next to Chinatown)
  • Everton park (old housing estate), new meets old
    • Coffee
    • Sweets
      • Grin Affair (grinaffair.com): natural ingredients into glass jar creations.
      • Batterworks (batter-works.com): pastries.
      • http://cozycornercoffee.com.
      • Seriously ice scream (facebook.com/seriouslyicecream).
      • Ji Xiang Confectionery (jixiangconfectionery.com): Traditional glutinous sweets. (**)
    • Food
      • The Provision Shop (Blk 3 Everton Park): for a classic and affordable meal.
      • Chew the Fat (Blk 6 Everton Park): comfort food.
      • Eden's Kitchen (http://edenskitchen.sg): healthy, green tea, coconut oil, etc.
  • Jalan Besar
  • Geylang (preserved shophouses and rich in Malay history)

02 December 2016 # Email provider bookmarks

01 December 2016 # Go snippets

Command-line flags

import (
  "flag"
)

type args struct {
  flag1  string
  flag2  string
}

func parseArgs() args {
  args := args{}
  flag.StringVar(&args.flag1, "flag1", "", "some flag 1")
  flag.StringVar(&args.flag2, "flag2", "", "some flag 2")

  flag.Parse()

  if flag.NFlag() != 2 {
    flag.Usage()
    os.Exit(1)
  }
  return args
}

27 November 2016 # Sydney travel bookmarks

16 October 2016 # Laos travel bookmark

08 October 2016 # Singapore travel bookmarks

01 October 2016 # Cambodia travel bookmarks

  • Pub Street (Siem Reap, Cambodia).

01 October 2016 # New York travel bookmarks

18 September 2016 # API design bookmarks

18 September 2016 # Handy pdf utilities

Straight out of How (and why) I made a zine, some handy utilities for generating pdfs…

Convert pngs to pdfs

# start with a bunch of PNG images of your zine pages
# convert them all to PDF
for i in *.png
   do
      # imagemagick is the best thing in the world
      convert $i $i.pdf
   done

Combine pdfs

# pdftk is awesome for combining pdfs into a single pdf
pdftk *.pdf cat output zine.pdf

Reorder pdf pages

# pdfmod is a GUI that lets you reorder pages
pdfmod zine.pdf

Add margins to pdf

# pdfcrop lets you add margins to the pdf. this is good because otherwise the
# printer will cut off stuff at the edges
pdfcrop --margin '29 29 29 29' zine.pdf zine-intermediate.pdf

Turn pdf into booklet

# pdfjam is this wizard tool that lets you take a normal ordered pdf and turn
# it into something you can print as a booklet on a regular printer.
# no more worrying about photocopying machines
pdfjam --booklet true --landscape --suffix book --letterpaper --signature 12 --booklet true --landscape zine-intermediate.pdf -o zine-booklet.pdf

15 September 2016 # Fuzzy search Emacs compile history

I wrote about searching bash history with Emacs Helm some time ago. Since then, I've learned about completing-read to generically handle simple Emacs completions (very handy for supporting Helm, Ivy, and Ido completions).

Here's a simple way to combine completing-read and the compile command to enable fuzzy searching your compile history:

fuzzy_compile.gif

(defun ar/compile-completing ()
  "Compile with completing options."
  (interactive)
  (let ((compile-command (completing-read "Compile command: " compile-history)))
    (compile compile-command)
    (add-to-list 'compile-history compile-command)))

05 September 2016 # Jumping on the Emacs 25 bandwagon

Can't miss out on all the new fun. Emacs 25 RC2 is out and lots of people already using it. Since I'm mostly on MacOS these days, installing via homebrew with –devel, gets you RC2:

brew install emacs --devel --with-cocoa --with-gnutls --with-librsvg --with-imagemagick

emacs25.png

The only hiccup so far's been org mode failing to export, which was fixed by re-installing it (follow this thread).

31 July 2016 # San Francisco's Mission District travel bookmarks

  • Atlas Cafe.
  • Blue Bottle Coffee.
  • Cafe la Boheme.
  • Clarion Alley.
  • Coffee Bar.
  • Dynamo donut & coffee.
  • Four Barrel Coffee.
  • Grand Coffee.
  • Haus Coffee.
  • Kafe 99.
  • Linea cafe.
  • Mission skateboards.
  • Nakamoto's Bitcoin shop.
  • Philz Coffee.
  • Ritual Coffee roasters.
  • Rodger's coffee & tea.
  • Sightglass Coffee.
  • Stable Cafe.
  • Sugar lump coffee lounge.

25 July 2016 # Moscow travel bookmarks

24 July 2016 # Vietnam travel bookmarks

19 July 2016 # Pokémon Go bookmarks

03 July 2016 # Coffee bookmarks

03 July 2016 # Machine learning bookmarks

17 June 2016 # Emacs and emotional vocab

Having read Are You in Despair? That’s Good, I was encouraged to expand my emotional vocabulary. As a zone.el fan (checkout nyan, sl, and rainbow), I looked into writing a zone program. When zone-when-idle is set, zone acts as a screensaver of sorts. We can use this to display random emotional vocab whenever Emacs is idle for a period of time. Let's get to it…

Zone keeps a list of programs to choose from when kicked off. Below is a basic zone-hello program, along with an interactive command for previewing. Not much to these. The tiny program prepares the screen for zoning and inserts text while no input is pending.

(defun zone-hello ()
  (delete-other-windows)
  (setq mode-line-format nil)
  (zone-fill-out-screen (window-width) (window-height))
  (delete-region (point-min) (point-max))
  (goto-char (point-min))
  (while (not (input-pending-p))
    (insert "hello zone\n")
    (zone-park/sit-for (point-min) 0.2)))

(defun zone-hello-preview ()
  (interactive)
  (let ((zone-programs [zone-hello]))
    (zone)))

Here's what zone-hello looks like:

minimal-zone.gif

Back to improving our emotional vocabulary, we'll need a dictionary for our goal. A quick search yields a potential list of words. We can use WordNet to define them while offline. These two sources will do for now. We tie it all together in zone-words.el and the resulting zone program looks as follow:

emotions.gif

UPDATE: Just came across Animations With Emacs. A post with awesome zone examples.

10 May 2016 # Emacs: Find number of days between dates

Needed to find the number of days between two dates. Emacs calendar must know this…

  • Fire up the manual (M-x info-emacs-manual or C-h r).
  • Info-goto-node (or g).
  • Type "counting days" and voilá:

To determine the number of days in a range, set the mark on one date using `C-<SPC>', move point to another date, and type `M-=' (`calendar-count-days-region'). The numbers of days shown is inclusive; that is, it includes the days specified by mark and point.

emacs-days-between-dates.gif

Note: you can use the mouse to jump to another date, or "g d" (calendar-goto-date).

08 May 2016 # RoutingHTTPServer snippet

RoutingHTTPServer snippet:

RoutingHTTPServer *routingHTTPServer = [[RoutingHTTPServer alloc] init];
[routingHTTPServer setPort:8000];
[routingHTTPServer setDefaultHeader:@"Server" value:@"YourAwesomeApp/1.0"];
[routingHTTPServer handleMethod:@"GET"
                       withPath:@"/hello"
                          block:^(RouteRequest *request, RouteResponse *response) {
    [response setHeader:@"Content-Type" value:@"text/plain"];
    [response respondWithString:@"Hello!"];
  }];
NSError *error = nil;
if (![routingHTTPServer start:&error]) {
  NSLog(@"Error starting HTTP Server: %@", error);
 }

06 May 2016 # Alaska travel bookmarks

  • Anchorage.
  • Denali NP.
  • Exit Glacier / Kenai Fjord NP.
  • Ice Falls Hike.
  • Iditarod race husky camp.
  • Seward: Kenai Fjord Wildlife cruise (Major Marine cruises).
  • Talkeetna fishing.

06 May 2016 # On UIViewController madness (reading backlog)

03 May 2016 # When OOO impulse kicks in…

  • You start moving trivial bits of code into classes, with the anticipation that you might use it one day. Stop.
  • On naming, semantic clarity trumps brevity. Yup, the verbosity may be worth it.

02 May 2016 # Pakistan travel bookmarks

  • Lahore.
  • Karachi.
  • Rabelpindi.

02 May 2016 # Money bookmarks

02 May 2016 # Scotland travel bookmarks

02 May 2016 # Mac OS X software bookmarks

02 May 2016 # St. Petersburg travel bookmarks

02 May 2016 # iOS github bookmarks

02 May 2016 # 8 week half-marathon training

An 8-week training schedule:

WEEK MON TUE WED THU FRI SAT SUN
1 Rest 5 Km 5 Km Cycle Rest 5 Km 8 Km 9 Km
    29:56 29:54     29:45 1:00:55
2 Rest 7 Km 5 Km Cycle Rest 5 Km 10 Km
    41:36 27:52     28:23 59:17
3 Rest 8 Km 8.1 Km 5 Km Cycle Rest 5 Km 12 Km
    49:29 29:33     27:50 1:06
4 Rest 8 Km Rest 8 Km Rest 5 Km 14 Km
    46:39   49:28   29:40  
5 Rest 8 Km Rest 8 Km Rest 6 Km 16 Km 10 Km
    48:50         53:38
6 Rest 8 Km 8 Km 8 Km Rest 8 Km 19 Km
        51:39   37:09 2:02
7 Rest 8 Km Rest 12 Km Rest 8 Km 16 Km
    52:55          
8 Rest 8 Km Rest 5 Km 5 K Rest Race
               

02 May 2016 # Haskell bookmarks

17 April 2016 # Haskell notes

Referential transparency

An expression consistently evaluating to the same result, regardless of context.

28 March 2016 # Emacs Objective-C tagging with RTags

Install libclang on Mac

brew install llvm --with-clang

Install RTags

git clone --recursive https://github.com/Andersbakken/rtags.git
cd rtags
cmake -DCMAKE_PREFIX_PATH=/Users/your-user-name/homebrew/opt/llvm -DCMAKE_EXPORT_COMPILE_COMMANDS=1 .
make

Start RTags daemon

path/to/rtags/bin/rdm 2> /tmp/rdm.log

Compilation database

Install xctool

brew install xctool

Generate a compilation database

cd path/to/your/objc-project
xctool -sdk iphonesimulator -arch x86_64 -scheme SomeScheme -reporter pretty -reporter json-compilation-database:compile_commands.json clean build

Load compilation database

path/to/rtags/bin/rc -J path/to/your/objc-project/compile_commands.json

Install RTags Emacs package

(use-package rtags :ensure t
  :config
  (setq rtags-use-helm t) ;; Optional. Enable if helm fan (I am!).
  (setq rtags-path "path/to/rtags/bin/"))

Ready to go

Use any of the rtags interactive commands. For example:

M-x rtags-find-symbol

10 March 2016 # Database bookmarks

06 March 2016 # Python tips backlog

05 March 2016 # Bruges travel bookmarks

02 March 2016 # Emacs lisp snippets

Find file upwards, up parents, up hierarchy

(locate-dominating-file FILE NAME)

Find executable in PATH

(executable-find COMMAND)

Read string with completion (helm/ido/ivy friendly)

(completing-read PROMPT COLLECTION &optional PREDICATE REQUIRE-MATCH INITIAL-INPUT HIST DEF INHERIT-INPUT-METHOD)

Execute command/process and return list

(process-lines PROGRAM &rest ARGS)

Iterating org buffer

(org-element-map (org-element-parse-buffer) '(headline link)
  (lambda (element)
    (cond
     ((and (eq (org-element-type element) 'headline)
           (= (org-element-property :level element) 1))
      (print "headline"))
     ((eq (org-element-type element) 'link)
      (print "link")))
    nil))

29 February 2016 # iOS development books bookmarks

20 February 2016 # React/flux iOS implementation bookmarks

18 February 2016 # Some modern Objective-C idioms

NSNumber literals

NSNumber *number1 = @1024;
NSNumber *number2 = @1024.123f;
NSNumber *number3 = @'A';
NSNumber *number4 = @YES;
NSNumber *number5 = @24ul; // Unsigned long.
NSNumber *number6 = @123456ll; // Long Long.
NSNumber *number7 = @5050.50; // Float.
NSNumber *number8 = @1543; // Integer
NSNumber *number9 = @111.456; // Double

Array literals

NSArray *names = @[@"John", @"Peter", @"Jaye", @"George", @"Max"];
NSArray *mutableNames = [@[@"John", @"Peter", @"Jaye", @"George", @"Max"] mutableCopy];

16 February 2016 # Cross-platform development bookmarks

15 February 2016 # Generating a random MAC address

As some point I had to generate a random MAC address. This is the snippet I used:

import random

def randomMAC():
  mac = [0x00, 0x16, 0x3e,
         random.randint(0x00, 0x7f),
         random.randint(0x00, 0xff),
         random.randint(0x00, 0xff),
  ]
  return ':'.join(map(lambda x: "%02x" % x, mac))

print 'MAC => %s' % randomMAC()
MAC => 00:16:3e:7e:f7:fa

14 February 2016 # Defined elisp variables matching regexp

You can use "M-x apropos-variable" to get documentation for variables matching a pattern. For more flexibility, some elisp can help with getting a list of all variables matching a regexp:

(defun ar/variables-matching-pattern (pattern)
  "Get a list of all variables matching PATTERN."
  (let ((matched-variables '()))
    (mapatoms
     (lambda (symbol)
       ;; Symbol is variable?
       (when (and (boundp symbol)
                  (string-match pattern (symbol-name symbol)))
         (add-to-list 'matched-variables symbol))))
    matched-variables))

(let ((variables ""))
  (mapc (lambda (variable-symbol)
          (setq variables
                (concat variables
                        (format "%s => %s\n"
                                (symbol-name variable-symbol)
                                (symbol-value variable-symbol)))))
        (ar/variables-matching-pattern "^tern-.*"))
  variables)
tern-mode-keymap => (keymap (3 keymap (4 . tern-get-docs) (3 . tern-get-type) (18 . tern-rename-variable)) (27 keymap (44 . tern-pop-find-definition) (67108910 . tern-find-definition-by-name) (46 . tern-find-definition)))
tern-update-argument-hints-async => nil
tern-known-port => nil
tern-mode => nil
tern-activity-since-command => -1
tern-project-dir => nil
tern-last-point-pos => nil
tern-last-completions => nil
tern-explicit-port => nil
tern-idle-time => 2.5
tern-find-definition-stack => nil
tern-last-argument-hints => nil
tern-idle-timer => nil
tern-server => nil
tern-last-docs-url => nil
tern-buffer-is-dirty => nil
tern-command-generation => 0
tern-flash-timeout => 0.5
tern-update-argument-hints-timer => 500
tern-mode-hook => nil
tern-command => (tern)

13 February 2016 # Proselint via Emacs flycheck

Based on Linting Prose in Emacs

Needs proselint installed:

pip install proselint

Also needs a flycheck checker defined:

(flycheck-define-checker proselint
  "A linter for prose."
  :command ("proselint" source-inplace)
  :error-patterns
  ((warning line-start (file-name) ":" line ":" column ": "
            (id (one-or-more (not (any " "))))
            (message) line-end))
  :modes (gfm-mode
          markdown-mode
          org-mode
          text-mode))

(add-to-list 'flycheck-checkers 'proselint)

11 February 2016 # Generate go struct definition from json file

From Generate go struct definition from json file, and before I forget:

curl http://url.tld/file.json | gojson -name=Repository

11 February 2016 # Doh! undo last commit (Magit edition)

I previously noted how to undo your last git commit (ie. soft reset). Using Magit:

  1. M-x magit-log-current.
  2. Move point to prior revision.
  3. M-x magit-reset-soft (defaults to revision at point).

Or if you want a single function:

(require 'magit)

(defun ar/magit-soft-reset-head~1 ()
  "Soft reset current git repo to HEAD~1."
  (interactive)
  (magit-reset-soft "HEAD~1"))

06 February 2016 # Redux bookmarks

06 February 2016 # Javascript tips backlog

updated: 13 February 2016

06 February 2016 # Emacs lisp tips backlog

updated: 25 April 2016

04 February 2016 # Entering accents in Emacs

Via Irreal's Entering Accented Characters in Emacs, a reminder on how to enter accents using C-x 8. For example:

C-x 8 ' A -> Á

04 February 2016 # Really delete iPhone photos

After deleting photos, go to:

Albums -> Recently Deleted -> Select -> Delete All

03 February 2016 # Vancouver travel bookmarks

03 February 2016 # Schnitzel recipe

Since eating at Fischers's, I've been inclined to make Schnitzel. This is my attempt.

Ingredients

  • Salt and ground black pepper.
  • All-purpose flour.
  • Eggs (beaten).
  • Bread crumbs (natural).
  • Oil.

Preparation

  • Flatten the pork/chicken/veal.
  • Season (salt and pepper).
  • Heat pan with a generous amount of oil.
  • Dip into flour -> egg -> bread crumbs.

Garnish

  • Anchovies.
  • Capers.

Photo

schnitzel.jpg

03 February 2016 # Hot reloading with react and redux

By Robert Knight (@robknight_).

Checkout

03 February 2016 # Converting Unix epoc time to human readable date

GNU

date -d @192179700
Tue Feb  3 07:15:00 GMT 1976

BSD/OS X

date -r 192179700
Tue Feb  3 07:15:00 GMT 1976

03 February 2016 # Objective-C bookmarks

02 February 2016 # Timesink bookmarks

02 February 2016 # Suspend and reattach processes

Via climagic's Suspend and reattach a process to screen:

longcmd ; [Ctrl-Z] ; bg ; disown ; screen ; reptyr $( pidof longcmd )

02 February 2016 # Czech Republic travel bookmarks

02 February 2016 # Meditation tips backlog

02 February 2016 # Append jpegs in a video sequence

Via climagic's make slideshow from *.jpg:

for p in *.jpg; do
    ffmpeg -loop_input -f image2 -i $p -t 3 -r 4 -s 1080x720 -f avi - >> slides.avi;
done

02 February 2016 # Regular expressions bookmarks

02 February 2016 # Typescript bookmarks

02 February 2016 # Hiding HTML elements

Hide with display:none (exclude from layout) and visibility:hidden (include in layout).

01 February 2016 # Echo Emacs keybiding from function name

Picked up via Emacs Redux's Display the Keybinding for a Command With Substitute-command-keys, with my own example:

(message (substitute-command-keys "Press \\[ar/ox-html-export] to export org file"))
Press <f6> to export org file

01 February 2016 # Emacs dired for batch byte compilation

Recently updated org-mode and started seeing an invalid function error:

Error (use-package): ob :config: Invalid function: org-babel-header-args-safe-fn

Just learned dired enables you to mark files and byte compile via M-x dired-do-byte-compile.

29 January 2016 # Serializing to JSON on iOS

NSDictionary *dictionary = @{
  @"key1" : @"val1",
  @"key2" : @"val2",
  @"key3" : @"val3",
  @"key4" : @"val4",
  @"key5" : @"val5",
  @"key6" : @"val6",
};
NSError *error;
NSData *jsonData =
    [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
if (error) {
  // noooooooooo!
}
NSString *json =
    [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

25 January 2016 # Fischer's London: yes, but…

Yes

Step into a Viennese blast from the past. Beautiful setting and pleasant vibe. Ordered a dirty martini on the rocks, a bottle of Merlot, Käsespätzle (with bacon), and Wiener Schnitzel (with anchovy/capers/egg). All very tasty.

But…

Surprisingly, desserts (Topfenstrudel, Berggasse and coffee) were nothing spectacular. Also not a cheap eat (£50 per person).

Photos

fischers-03.JPG fischers-04.JPG fischers-05.JPG fischers-06.JPG fischers-07.JPG fischers-08.JPG fischers-09.JPG fischers-10.JPG fischers-11.JPG fischers-12.JPG

25 January 2016 # Polar travel bookmarks

24 January 2016 # Sweden travel bookmarks

20 January 2016 # Handwriting bookmarks

20 January 2016 # Chocolate fondant recipe

My girlfriend recently made a delicious chocolate fondant. Saving the The Guardian's recipe:

Ingredients (2 servings)

  • 60g unsalted butter, cut into dice, plus extra to grease
  • 1 tbsp cocoa powder
  • 60g dark chocolate, broken into pieces
  • 1 egg and 1 egg yolk
  • 60g caster sugar
  • 1 tbsp plain flour

Preparation

  1. Pre-heat the oven to 200C if cooking immediately, and put a baking tray on the middle shelf. Butter the inside of 2 small ramekins or pudding moulds, and then put the cocoa in one and turn it to coat the inside, holding it over the second mould to catch any that escapes. Do the same with the other mould.
  2. Put the butter and chocolate into a heatproof bowl set over, but not touching, a pan of simmering water and stir occasionally until melted. Allow to cool slightly.
  3. Vigorously whisk together the egg, yolk, sugar and a pinch of salt until pale and fluffy. Gently fold in the melted chocolate and butter, and then the flour. Spoon into the prepared moulds, stopping just shy of the top – at this point the mixture can be refrigerated until needed, or even frozen, as the puddings will not wait around once cooked.
  4. Put on to a hot baking tray and cook for 12 minutes (14 if from cold, 16 if frozen) until the tops are set and coming away from the sides of the moulds. Leave to rest for 30 seconds and then serve in the ramekins or turn out on to plates if you're feeling confident – they're great with clotted cream or plain ice cream.

20 January 2016 # Parenting bookmarks

19 January 2016 # Ippudo London: yes, but…

Yes

Central St. Giles location. Ordered a Kirin Ichiban beer and a Spicy Tonkotsu with a seasoned boiled egg. Awesome medium-spice broth, tasty egg and firm noodles. Got additional noodles for £1.50.

But…

The space feels soulless. Think generic, chain, Pizza Express…

Photos

ipuddo_00.JPG ipuddo_01.JPG ipuddo_02.JPG ipuddo_03.JPG ipuddo_04.JPG ipuddo_05.JPG ipuddo_06.JPG ipuddo_07.JPG

19 January 2016 # Added Emacs zone-rainbow

kawabata's zone-rainbow popped up on melpa today. Added to zone-programs. Just because :)

(use-package zone-rainbow :ensure t
  :after zone
  :config
  (setq zone-programs (vconcat [zone-rainbow] zone-programs)))

zone-rainbow.gif

19 January 2016 # Safari's Web Inspector keyboard shortcuts

Via WebKit's blog, Web Inspector Keyboard Shortcuts:

  • ⌃⌘Y or ⌘\ continue.
  • F8 or ⇧⌘; step out.
  • F7 or ⌘; step in.
  • F6 or ⌘’ step over.

14 January 2016 # Copenhagen travel bookmarks

updated: 14 January 2016

12 January 2016 # Import UIKit for simpler debugging

I bookmarked An @import-ant Change in Xcode and immediately forgot about it. The gist is to import UIKit to simplify inspecting objects during an lldb session:

(lldb) expr @import UIKit

Shorten typing by creating aliases in ~/.lldbinit:

command alias uikit expr @import UIKit
command alias foundation expr @import Foundation

12 January 2016 # iOS development tips backlog

updated: 12 January 2016

11 January 2016 # Basic Emacs keybindings on Linux desktop

Miss C-a, C-e in your browser and other Linux apps? You can enable the GTK Emacs key theme:

$ gsettings set org.gnome.desktop.interface gtk-key-theme "Emacs"

or if on Cinnamon:

$ gsettings set org.cinnamon.desktop.interface gtk-key-theme Emacs

If your desktop environment is not running gnome-settings-daemon, start it with:

$ gnome-settings-daemon

More at Emacs Keybindings in Chrome Without Gnome and How to get Emacs key bindings in Ubuntu.

08 January 2016 # Emacs Objective-C completion with Irony

Install libclang on Mac

brew install llvm --with-clang

Configure Emacs

(use-package irony :ensure t
  :config
  (add-hook 'objc-mode-hook 'irony-mode)
  (add-hook 'irony-mode-hook 'irony-cdb-autosetup-compile-options))

(use-package company-irony :ensure t
  :config
  (add-hook  'objc-mode-hook (lambda ()
                               (setq-local company-backends '((company-irony)))))
  (add-hook 'irony-mode-hook 'company-irony-setup-begin-commands))

install irony server

Run:

M-x irony-install-server

NOTE: Needs libclang: Install with "brew install llvm –with-clang" By default, irony-install-server did not find libclang on Mac OS. irony-install-server invokes cmake for you. Work around by adding:

-DCMAKE_PREFIX_PATH=/Users/your-user-name/homebrew/opt/llvm

For example:

cmake -DCMAKE_PREFIX_PATH=/Users/your-user-name/homebrew/opt/llvm -DCMAKE_INSTALL_PREFIX\=/Users/your-user-name/.emacs.d/irony/ /Users/your-user-name/.emacs.d/elpa/irony-20160106.1223/server && cmake --build . --use-stderr --config Release --target install

Compilation database

Install xctool

brew install xctool

Generate compilation database

xctool -sdk iphonesimulator -arch x86_64 -scheme SomeScheme -reporter pretty -reporter json-compilation-database:compile_commands.json clean build

Set Irony's database path

M-x irony-cdb-json-add-compile-commands-path

07 January 2016 # Finland travel bookmarks

updated: 13 July 2016
  • 36 Hours in Helsinki.
  • Boat to the Baltics; Tallinn (Estonia).
  • Helsinki - Suomenlinna (former maritime fortress).
  • Lapland (husky sledding, reindeer, Santa Claus village).
  • Rovaniemi for reindeer, dog sled, santaland, artic circle photos.

07 January 2016 # Northern lights travel bookmarks

updated: 07 January 2016

06 January 2016 # Mexico travel bookmarks

03 January 2016 # Emacs highlight-symbol-mode

Been a fan of highlight-thing-mode. It automatically highlights all instances of symbol at point. Today, I gave highlight-symbol a try. Similar concept, but also adds the ability to jump to next/previous instances of symbol at point.

(use-package highlight-symbol :ensure t
  :config
  (set-face-attribute 'highlight-symbol-face nil
                      :background "default"
                      :foreground "#FA009A")
  (setq highlight-symbol-idle-delay 0)
  (setq highlight-symbol-on-navigation-p t)
  (add-hook 'prog-mode-hook #'highlight-symbol-mode)
  (add-hook 'prog-mode-hook #'highlight-symbol-nav-mode))

highlight-symbol.gif

03 January 2016 # Gandhi's ever-contemporary wisdom

Anger

"I do get angry, but I feel angry with myself for it. Full conquest of anger is possible only through self-realization. We should love even those who have the worst opinion of us. This is ahimsa, the rest is only ignorance."

Bad handwriting

"I am now of opinion that children should first be taught the art of drawing before learning how to write. Let the child learn his letters by observation as he does different objectives, such as flowers, birds, etc., and let him learn handwriting only after he has learned to draw objects."

Conduct of the Ashram

"Service without humility is selfishness and egotism."

Eating

"There is a great deal of truth in the saying that man becomes what he eats. The grosser the food, the grosser the body."

Heart

"There are chords in every human heart. If we only know how to strike the right chord, we bring out the music."

Moral law

The law of truth and love.

Renouncing or forgoing

Nishkulanand sings: "Renunciation of objects, without the renunciation of desires, is short-lived, however hard you may try."

Silence

"Man spoils matters much more by speech than by silence."

Time

"Every minute that runs to waste never returns. Yet, knowing this, how much time do we waste?"

The palate

"Turn to the birds and beasts, and what do you find? They never eat merely to please the palate, they never go on eating till their inside is full to overflowing. And yet, we regard ourselves as superior to the animal creation!"

Vow of Swadeshi

"The person who has taken the vow of swadeshi will never use articles which conceivably involve violation of truth in their manufature or on the part of their manufacturers."

02 January 2016 # Functional programming bookmarks

02 January 2016 # 9 Productivity tips

From HBR's 9 Productivity Tips from People Who Write About Productivity:

  1. Block time away from reactive tasks (email).
  2. Business = wasted energy.
  3. Exercise, sleep, and 90 minute work bursts.
  4. Incomplete tasks prompt healthy thinking out of context.
  5. Time off or stepping back is invaluable.
  6. Genuinely help were most successful/enjoyable.
  7. Plan for saying no while highlighting priority and seeking feedback.
  8. Measure important behavior change.
  9. Make time now (automate, simplify, etc.).

01 January 2016 # First meal of 2016

Pancakes

  • 1 teaspoon of salt.
  • 1.5 cups of milk.
  • 2 cups of flour.
  • 2 eggs.
  • 2 tablespoons sugar.
  • 4 tablespoons of melted butter.
  • 6 teaspoons of baking powder.

Makes 10/11 pancakes.

shortstack.jpg

01 January 2016 # Last meal of 2015

For our last meal of 2015, I contributed dal and rotis. This is my first attempt at making either one of these. Both recipes based on Anupy Singla's Indian for Everyone.

Dal Makhani (Buttered black lentils)

dal-grid.png dal.jpg

Roti-Chapati-Phulka

roti-grid.png roti.jpg

30 December 2015 # Find in $PATH with type and which

I typically use which to figure out the first binary found in $PATH:

which -a emacsclient
/Users/user/homebrew/bin/emacsclient
/usr/bin/emacsclient

I always forget about type though:

type -a emacsclient
emacsclient is /Users/user/homebrew/bin/emacsclient
emacsclient is /usr/bin/emacsclient

30 December 2015 # npm basics

Global vs local package installation location

{prefix}/lib/node_modules

vs

path/to/project/node_modules

View npm config

npm config list
; cli configs
user-agent = "npm/2.14.2 node/v4.0.0 darwin x64"

; node bin location = /Users/user/.nvm/versions/node/v4.0.0/bin/node
; cwd = /Users/user/stuff/active/blog
; HOME = /Users/user
; 'npm config ls -l' to show all defaults.

Get config value

npm config get prefix
/Users/user/.nvm/versions/node/v4.0.0

Set config value

npm config set prefix=$HOME/some/location

Install package globally

node install --global <package-name>

or

node install -g <package-name>

List global packages

npm list --global

You can also use –depth=0 to make less verbose.

/Users/user/.nvm/versions/node/v4.0.0/lib
├─┬ babel-eslint@4.1.3
│ ├── acorn-to-esprima@1.0.4
│ ├─┬ babel-core@5.8.25
│ │ ├── babel-plugin-constant-folding@1.0.1
│ │ ├── babel-plugin-dead-code-elimination@1.0.2
...

Install local package

npm install <package-name> --save

–save will add <package-name> dependency to your package.json.

package.json

Uninstall package

npm uninstall <package-name>

Install package at version

npm install <package-name>@1.7.0

Search packages

npm search linter

Online documentation

Online documentation is great so far. More at docs.npmjs.com.

25 December 2015 # Clojure bookmarks

21 December 2015 # Mac OS X tips backlog

updated: 06 March 2016

20 December 2015 # Search bash history with Emacs helm

Following up from changing CWD with helm projectile, here's a way to search your bash history with helm:

helm-bash-history.gif

(defun ar/helm-helm (title candidates on-select-function)
  "Helm with TITLE CANDIDATES and ON-SELECT-FUNCTION."
  (helm :sources `((name . ,title)
                   (candidates . ,candidates)
                   (action . ,on-select-function))
        :buffer "*helm-exec*"
        :candidate-number-limit 10000))

(defun ar/shell-send-command (command)
  "Send COMMAND to shell mode."
  (assert (string-equal mode-name "Shell") nil "Not in Shell mode")
  (goto-char (point-max))
  (comint-kill-input)
  (insert command)
  (comint-send-input))

(defun ar/helm-shell-search-history ()
  "Narrow down bash history with helm."
  (interactive)
  (assert (string-equal mode-name "Shell") nil "Not in Shell mode")
  (ar/helm-helm "bash history"
                (with-temp-buffer
                  (insert-file-contents "~/.bash_history")
                  (reverse
                   (delete-dups
                    (split-string (buffer-string) "\n"))))
                #'ar/shell-send-command))

Bonus: Replace existing M-r binding to use ar/helm-shell-search-history.

(bind-key "M-r" #'ar/helm-shell-search-history shell-mode-map)

19 December 2015 # View DICOM files from your X-ray

Got a CD with my chest X-ray from the hospital. Was expecting a pdf or an image of sorts, but the CD content was rather different. For starters, it was targeted at Windows users (AUTORUN.INF, MediaViewerLauncher.EXE and a bunch of DLLs):

$ find . -exec file --mime-type '{}' \;

./AUTORUN.INF: text/plain
./DICOMDIR: application/dicom
./MediaViewerLauncher.EXE: application/octet-stream
...
./Libraries/BASEPRINTER.DLL: application/octet-stream
./Libraries/CDDATABURNER.DLL: application/octet-stream
./Libraries/COM.DLL: application/octet-stream
...
./Libraries/ACE.DLL: application/octet-stream
./Libraries/ACE_SSL.DLL: application/octet-stream
./Libraries/ATL90.DLL: application/octet-stream
...
./DICOM/PAT_0000: application/x-directory
./DICOM/PAT_0000/STD_0000/SER_0000/OBJ_0001/IM_0001: application/dicom
./DICOM/PAT_0000/STD_0000/SER_0001/OBJ_0001/ED_0001: application/dicom
./DICOM/PAT_0000/STD_0000/SER_0002/OBJ_0001/ED_0001: application/dicom
./Worklist/ClinicalInfo/067eccde-b299-e511-9114-005056ad3afe.mht: text/html
./Worklist/Report/067eccde-b299-e511-9114-005056ad3afe.mht: text/html
./Worklist/Worklist.wl: application/octet-stream

I'm on a Mac, so most of these files were not useful to me. The more interesting files were IM_0001 and ED_0001 with "application/dicom" MIME type. DICOM files stand for Digital Imaging and Communications in Medicine. How to view these on a Mac? OsiriX viewer is an option. OsiriX, though on the heavy side (100.7MB download), it rendered the X-ray successfully.

2015-12-03-osirix-x-ray-small.png

Unsurprisingly, ImageMagick's convert utility also handles DICOM files. Converting to PNG worked well.

$ convert ./DICOM/PAT_0000/STD_0000/SER_0001/OBJ_0001/ED_0001 ED_0001.png

2015-12-03-imagemagick-x-ray-small.png

DICOM files also hold patient's metadata and optional reports. The file format is well known. OsiriX gives you access to it, but a few lines of python can also extract it for you. First install the pydicom package:

$ sudo pip install pydicom

Running the python interpreter is enough to peak at the metadata:

>>> import dicom
>>> ds = dicom.read_file("./DICOM/PAT_0000/STD_0000/SER_0000/OBJ_0001/IM_0001")
>>> ds
(0008, 0000) Group Length                        UL: 400
(0008, 0005) Specific Character Set              CS: 'ISO_IR 100'
(0008, 0016) SOP Class UID                       UI: Computed Radiography Image Storage
(0008, 0020) Study Date                          DA: '20151203'
(0008, 0021) Series Date                         DA: '20151203'
(0008, 0023) Content Date                        DA: '20151203'
(0008, 0030) Study Time                          TM: '120519.000000'
(0008, 0031) Series Time                         TM: '120520.000000'
(0008, 0033) Content Time                        TM: '120643.000000'
(0008, 0060) Modality                            CS: 'CR'
(0008, 0070) Manufacturer                        LO: 'Canon Inc.'
...

There were other DICOM files with a report:

>>> import dicom
>>> ds = dicom.read_file("./DICOM/PAT_0000/STD_0000/SER_0001/OBJ_0001/ED_0001")
>>> ds
(0008, 0005) Specific Character Set              CS: 'ISO_IR 100'
(0008, 0016) SOP Class UID                       UI: Encapsulated PDF Storage
...
(0042, 0012) MIME Type of Encapsulated Document  LO: 'application/pdf'

DCMTK is another alternative tool to extract DICOM metadata. The source is available and can be built:

$ tar xf dcmtk-3.6.0.tar.gz
$ cd dcmtk-3.6.0
$ cmake .
$ make

Or installed via homebrew:

$ brew install dcmtk

DCMTK includes dcmdump. You can use it to dump DICOM files:

$ dcmdata/apps/dcmdump DICOM/PAT_0000/STD_0000/SER_0000/OBJ_0001/IM_0001
# Dicom-File-Format

# Dicom-Meta-Information-Header
# Used TransferSyntax: Little Endian Explicit
(0002,0000) UL 192                                      #   4, 1 FileMetaInformationGroupLength
(0002,0001) OB 01\00                                    #   2, 1 FileMetaInformationVersion
(0002,0002) UI =ComputedRadiographyImageStorage         #  26, 1 MediaStorageSOPClassUID
(0002,0003) UI [1.2.392.200046.100.2.1.1.42667.20151203120519.1.1.1] #  52, 1 MediaStorageSOPInstanceUID
(0002,0010) UI =LittleEndianExplicit                    #  20, 1 TransferSyntaxUID
(0002,0012) UI [1.3.46.670589.42.1.4.4.5]               #  24, 1 ImplementationClassUID
(0002,0013) SH [PhilipsISPACS445]                       #  16, 1 ImplementationVersionName
...

Of interest, David Clunie's Medical Image Format Site.

18 December 2015 # Tip: GOOGLETRANSLATE your Spreadsheet

Examples from reference:

=GOOGLETRANSLATE("Hello World","en","es")
=GOOGLETRANSLATE(A2,B2,C2)
=GOOGLETRANSLATE(A2)

18 December 2015 # Organize your data with camlistore

Checking out camlistore to organize all sorts of data. Scaleway enables you to deploy camlistore servers.

17 December 2015 # Maps dev bookmarks

17 December 2015 # Use ImageMagick to convert image to grayscale

Another ImageMagick one-liner I'll likely forget.

mogrify -type Grayscale image.png

14 December 2015 # Drill down Emacs dired with dired-subtree

JCS, from Irreal, recently highlighted fuco's dired-hacks. dired-subtree is super handy for drilling subdirectories down. Bound <tab> and <backtab> to toggle and cycle subtrees.

(use-package dired-subtree :ensure t
  :after dired
  :config
  (bind-key "<tab>" #'dired-subtree-toggle dired-mode-map)
  (bind-key "<backtab>" #'dired-subtree-cycle dired-mode-map))

dired-subtree.gif

14 December 2015 # CSS bookmarks

12 December 2015 # Resume partial downloads with ssh and rsync

rsync --rsync-path=/usr/local/bin/rsync \
      --partial \
      --progress \
      --rsh=ssh \
      john@host:/path/to/file \
      path/to/partial/file

12 December 2015 # Emacs text faces

  • Text faces = Text styles.
  • Face attributes: font, height, weight, slant, foreground/background color, and underlining or overlining.
  • Font lock mode automatically assigns faces to text.
  • M-x list-faces-display: Shows faces defined.
  • M-x helm-colors: Also handy.
  • Unspecified attributes are taken from 'default' face.

08 December 2015 # Preview HTML pages on github

07 December 2015 # Flutter setup

Based on Getting Started with Flutter.

$ curl -O https://storage.googleapis.com/dart-archive/channels/stable/release/1.13.0/sdk/dartsdk-macos-x64-release.zip
$ unzip dartsdk-macos-x64-release.zip
$ export PATH=`pwd`/dart-sdk/bin:$PATH

Verify with:

$ pub --version

07 December 2015 # Playing with Dart's analysis server

Dart SDK ships with an analysis server. Very handy if you'd like to write a completion plugin for your favorite editor. The API is well documented. Of interest, there's LocalDartServer.java, part of dartedit.

$ dart path/to/bin/snapshots/analysis_server.dart.snapshot  --sdk=path/to/dart-sdk

NOTE: The server reads requests from standard input. Either escape or execute the following as one-liner json requests.

{
  "id": "1",
  "method": "analysis.setAnalysisRoots",
  "params": {
    "included": [
      "path/to/your/dart/project"
    ],
    "excluded": []
  }
}
{
  "id": "3",
  "method": "completion.getSuggestions",
  "params": {
    "file": "path/to/some/file.dart",
    "offset": 673
  }
}

07 December 2015 # Dart bookmarks

07 December 2015 # iOS app awesome libs bookmarks

06 December 2015 # Flutter bookmarks

06 December 2015 # Swift bookmarks

30 November 2015 # Installing Emacs spaceline

Gave Spaceline a try. Spacemacs's powerline theme. Setup was super simple (Thanks Eivind Fonn and Sylvain Benner):

(use-package spaceline :ensure t
  :config
  (use-package spaceline-config
    :config
    (spaceline-toggle-minor-modes-off)
    (spaceline-toggle-buffer-encoding-off)
    (spaceline-toggle-buffer-encoding-abbrev-off)
    (setq powerline-default-separator 'rounded)
    (setq spaceline-highlight-face-func 'spaceline-highlight-face-evil-state)
    (spaceline-define-segment line-column
      "The current line and column numbers."
      "l:%l c:%2c")
    (spaceline-define-segment time
      "The current time."
      (format-time-string "%H:%M"))
    (spaceline-define-segment date
      "The current date."
      (format-time-string "%h %d"))
    (spaceline-toggle-time-on)
    (spaceline-emacs-theme 'date 'time))

spaceline.png

29 November 2015 # package.el incomprehensible buffer

Came across "incomprehensible buffer" error in package.el. Workaround patch:

--- a/lisp/emacs-lisp/package.el
+++ b/lisp/emacs-lisp/package.el
@@ -1161,6 +1161,7 @@ package--with-work-buffer
(let* ((url (concat ,url-1 ,file))
       (callback (lambda (status)
                   (let ((b (current-buffer)))
+                    (goto-char (point-min))
                     (unwind-protect (wrap-errors
                                      (when-let ((er (plist-get
                                                      status :error)))
                                        (error "Error retrieving: %s %S" url er))

29 November 2015 # Leading bookmarks

29 November 2015 # Online reading backlog

updated: 21 May 2016

28 November 2015 # Travel lifestyle bookmarks

26 November 2015 # SQL bookmarks

26 November 2015 # Unix/Linux tools bookmarks

26 November 2015 # Couchbase React Native bookmarks

26 November 2015 # Installing Emacs 25 devel on Mac OS X

Stable

brew update
brew install emacs --HEAD --use-git-head --with-cocoa --with-srgb --with-gnutls
brew linkapps emacs

Development

  brew update
  brew install emacs --devel --with-cocoa --with-srgb --with-gnutls
  brew linkapps emacs
then

Had problems loading seq. Removed byte-compiled packages:

$ find ~/.emacs.d/elpa -iname *.elc -exec rm '{}' \;

25 November 2015 # Diagram tools bookmarks

24 November 2015 # Licensing bookmarks

22 November 2015 # Backup bookmarks

22 November 2015 # Making hummus

22 November 2015 # Nara travel bookmarks

21 November 2015 # Docker bookmarks

21 November 2015 # Angular bookmarks

21 November 2015 # Mac OS bookmarks

21 November 2015 # easy_install->pip->conda

Spotted Conda package manager. It handles python installations, in addition to package management. There's also a package index provided by Binstar. Installed Miniconda, the bare bones Conda environment.

Can't find a python package in Binstar? Here's a post on Using PyPi Packages with Conda. If that fails, you can try pip from your Conda python environment.

16 November 2015 # Traditional music bookmarks

04 November 2015 # Recover from an unresponsive Emacs

Wilfred Hughes has a handy tip to bail you out of a hung Emacs instance:

pkill -SIGUSR2 emacs

ps. Not had a chance to try it, but next time it happens…

25 October 2015 # Training for under 50 min 10k run

Not much training time for an under 50 minute 10k run, but here's an attempt (based on time-to-run's sub-50):

Mon Tue Wed Thu Fri Sat Sun
Oct 26 Oct 27 Oct 28 Oct 29 Oct 30 Oct 31 Nov 1
    60 min 30 min 2k @ 4.55/k rest 105 min
        2 min rest    
      (repeat x 3)    
Nov 2 Nov 3 Nov 4 Nov 5 Nov 6 Nov 7 Nov 8
30 min 30 min 1k @ 4.50/k 30 min 30 min rest 5k @ 4.55/k
    90 sec rest        
    (repeat x 5)        
Nov 9 Nov 10 Nov 11 Nov 12 Nov 13 Nov 14 Nov 15
10k easy 30 min 1k @ 4.55/k 30 min 30 min rest race day
    1 min easy        
    (repeat x 3)        

25 October 2015 # Reading a running training plan

A sample from Kona Part 2's comments:

2.5 w/u to 4x(1.25@11.5 w/0.25R@7) to 3x(3.75@10.5 w/0.5R@7) to 2.5 c/d.

Is read from left to right as:

2.5 mile warm up to four times through 1.25 miles at 11.5 miles per hour with 0.25 miles recovery at 7 miles per hour to three times through 3.75 miles at 10.5 miles per hour with 0.5 miles recovery at 7 miles per hour to 2.5 miles cool down.

23 October 2015 # Find binary in PATH using python

import distutils.spawn
print distutils.spawn.find_executable('git')
/usr/bin/git

22 October 2015 # Indonesia travel bookmarks

updated: 06 December 2015

22 October 2015 # Malaysia travel bookmarks

updated: 06 December 2015

22 October 2015 # Mongolia travel bookmarks

22 October 2015 # Running bookmarks

22 October 2015 # Media player bookmarks

16 October 2015 # UX toolbox bookmarks

08 October 2015 # Change Emacs shell's CWD with helm projectile

If using Emacs shell and helm projectile, you can wire these up to quickly change your current working directory.

change-cwd-with-helm-projectile.gif

(require 'helm-projectile)

(defun ar/shell-cd (dir-path)
"Like shell-pop--cd-to-cwd-shell, but without recentering."
  (unless (string-equal mode-name "Shell")
    (error "Not in Shell mode"))
  (message mode-name)
  (goto-char (point-max))
  (comint-kill-input)
  (insert (concat "cd " (shell-quote-argument dir-path)))
  (let ((comint-process-echoes t))
    (comint-send-input)))

(defun ar/helm-projectile-shell-cd ()
  "Change shell current working directory using helm projectile."
  (interactive)
  (unless (string-equal mode-name "Shell")
    (error "Not in Shell mode"))
  (let ((helm-dir-source (copy-tree  helm-source-projectile-directories-list)))
    (add-to-list 'helm-dir-source '(action . ar/shell-cd))
    (add-to-list 'helm-dir-source '(keymap . nil))
    (add-to-list 'helm-dir-source '(header-line . "cd to directory..."))
    (helm :sources helm-dir-source
          :buffer "*helm-dirs*"
          :candidate-number-limit 10000)))

07 October 2015 # Thermostat reset on Bosch WKD28350GB

My Bosch washer/dryer (WKD28350GB) stopped drying recently. Resetting the dryer's thermostat red breaker did the trick.

WKD28350GB-01.jpg WKD28350GB-02.jpg WKD28350GB-03.jpg WKD28350GB-04.jpg

05 October 2015 # Javascript fetch node sample

Playing with node and fetch:

// Requisite: npm install node-fetch --save
// Save to fetch-demo.js
// Run: node fetch-demo.js

var fetch = require('node-fetch');

fetch("http://xenodium.com/data/javascript-fetch-node-sample/message.json", {
  method: 'GET',
  timeout: 5000
}).then(function(response) {
  return response.json();
}).then(function(response) {
  console.log('subject: ' + response.subject);
  console.log('body: ' + response.body);
}).catch(function(reason) {
  console.log(reason);
});

01 October 2015 # Extract dominant colors in images

There's a handy HN post pointing to Javier López's Using imagemagick, awk and kmeans to find dominant colors in images. A comment also highlights color-extract, written in Go.

28 September 2015 # Find a word with regex and WordNet

Recently wanted to come up with a random keyword. Querying WordNet and a regular expression did the job.

Installed WordNet on Mac:

$ brew install wordnet

Want a word ending in "esome"?

$ wn esome -grepn -grepv -grepa -grepr | egrep -o -e "\w*esome\b" | sort | uniq

adventuresome
awesome
blithesome
bunglesome
cuddlesome
esome
fivesome
gruesome
lithesome
lonesome
lovesome
meddlesome
mettlesome
nettlesome
threesome
tiresome
torturesome
troublesome
unwholesome
venturesome
wholesome

26 September 2015 # Soundcloud's Go best practices (GopherCon 2014)

Having watched the video, some takeaways:

Single GOPATH

$GOPATH/src/github.com/soundcloud/foo

Repo structure

github.com/soundcloud/whatever

  • README.md
  • Makefile
  • main.go
  • support.go
  • foo
    • foo.go
    • bar.go
  • whatever-server
    • main.go
  • wharever-worker
    • main.go

Formatting and style

Use gofmt.

Google's codereview guidelines.

Avoid named return parameters.

Avoid make and new (unless you know sizes).

Use struct{} for sentinel values: sets, signal chans.

  • Conveys no information in it this part.
  • Instead of empty interface.
  • instead of boolean.

Break long lines at parameters

  • No need to compact.
  • Keep trailing coma in last argument.

Flags

func main() {
  var (
    foo = flags.String("foo", "doch", "...")
    bar = flat.Int("bar", 34, "...")
  )
  flag.Parse()
  // ...
}

Logging

  • package log
  • Telemetry
  • Push model (gets expensive over time)
    • Graphite
    • Statsd
    • AirBrake
  • Pull model (chosen)
    • expvar
    • Prometheus

Testing

  • package testing
    • Unit tests
    • reflect.DeepEqual
  • Integration
    • Use flags for starting services
    • // +build integration

Code validation

  • On Save
    • Go fmt
    • Go import (go fmt++)
  • On Build
    • Go vet
    • Golint
    • Go test
  • On Deploy
    • go test -tags=integration
  • GoCov?

Dependency management

  • Unimportant projects
    • go get -d (and hope)
  • Important
    • VENDOR (ie. copy into your repo)
      • Git submodules (no!).
      • Git subtrees (seem OK).
      • Tool (godep?).
      • Build
        • For binaries (use _vendor subdir)

23 September 2015 # Sync pip with Mac OS updates

My pip installation recently broke after a Mac OS update.

$ pip
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2793, in <module>
    working_set.require(__requires__)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 673, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 576, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: pip==1.1

Updating my pip installation fixes the break:

$ sudo easy_install -U pip

20 September 2015 # Chinatown treats review

Recommended? yep

There's a corner in Chinatown hosting some truly superb treats. If you get caught in the rush between Newport court and Newport place, you'd likely fail to notice some the awesome street food stands.

chinatown.jpg newport-court.jpg

Chilly squid

I've walked past this place many times and never noticed it. They serve a handful of items, but the grilled chilly squid skewers caught my attention. They're grilled, brushed with chilly sauce and finished with sprinkled sesame and cumin seeds. Super tasty.

squid-stand.jpg

chilly-squid-1.jpg chilly-squid-2.jpg

Pancake + Crisp + Egg + Hot chillies = Jiān Bǐng 煎餅

I first had these delicious breakfast savory pancakes at a Beijing street food stall. Never expected to randomly find Jiān Bǐng in London. It's a crepe with an additional egg spread, hoisin sauce, chilly sauce, hot chillies, topped with spring onions and coriander, all wrapping a wonderfully crispy bread cracker. And.. it's awesome.

pancake-3.jpg

Tai Yaki

Chinatown Bakery is hard to miss. Pedestrian traffic slows down as we all fall under the spell of the Tai Yaki machine. This wonderful assembly line produces fish-shaped sweet waffles filled with custard. They are the perfect dessert after some savory street snacks. You can get a bag of 4 for £2.

fish-1.jpg fish-4.jpg

All near each other

All these delights are within a stone's throw away from each other.

pano.png

Useful?

Was this post useful to you? do reply!

Better suggestion?

London is full of overhyped, gimmicky, and unnecessarily expensive restaurants. Very few deliver truly awesome food (even those expensive ones). Got suggestions? I'd love to hear from you @xenodium.

18 September 2015 # React bookmarks

updated: 18 September 2016

16 September 2015 # Chinese rice vinegar

Note to self to buy Gold Plum Chinkiang Vinegar. Awesome with dim sum.

chinkiang-vinegar.jpg

13 September 2015 # Use ImageMagick to batch-resize images

Using percentage:

$ mogrify -resize 10% *.png

Using dimensions:

$ mogrify -resize 120x120 *.png

Lots of other alternatives from ImageMagick's documentation:

-resize scale%
-resize scale-x%xscale-y%
-resize width
-resize xheight
-resize widthxheight
-resize widthxheight^
-resize widthxheight!
-resize widthxheight>
-resize widthxheight<
-resize area@

08 September 2015 # Lucky 7 review

Recommended? yep

Lucky 7 is a small nostalgic American diner on Westbourne Park road. I like the vibe, the space, and the unpretentious waiting staff. I go to Lucky 7 often enough, originally for the buttermilk pancakes, but the list of favorites on the menu keeps growing.

lucky-7-menu-board.jpg lucky-7-staff.jpg

Smileys by w.dyer.

Buttermilk Banana pancakes

These are my favorite pancakes in London by far. Banana buttermilk pancakes and a few free coffee refills usually sort me out until dinner time. Add a side of bacon if extra hungry. You probably don't need it though.

lucky-7-coffee.jpg lucky-7-pancakes.jpg

Reuben sandwich

The reuben has been on Lucky 7's specials menu for months now. Not had many of these in London, but compared to The Brass Rail's, this reuben was a clear winner. The sandwich is huge and comes with fries. My girlfriend and I struggled to finish one between the two of us.

lucky-7-reuben-fries.jpg

lucky-7-reuben-cross-section.jpg

Vanilla milkshake (add malt!)

This milkshake hits the spot every time, but it's filling. You almost have to decide between the shake and an actual meal. If you must have it, add malt. Sorry, no picture.

Huevos Rancheros

This is a breakfast dish I can equally make (better?) at home, but Lucky 7 wins hands down every time I'm feeling particularly lazy. Sorry, no picture.

Useful?

Was this post useful to you? do reply!

Better suggestion?

London is full of overhyped, gimmicky, and unnecessarily expensive restaurants. Very few deliver truly awesome food (even those expensive ones). Got suggestions? I'd love to hear from you @xenodium.

02 September 2015 # Sierra Leone travel bookmarks

02 September 2015 # London travel bookmarks

23 August 2015 # Use ImageMagick to auto-orient images

Recently needed to rotate images based on EXIF metadata. ImageMagick to the rescue:

$ for i in *.png; do convert -auto-orient "$i" "$i"; done

23 August 2015 # Bengali Macher Jhol

My friend Sakhya brought me the wonderful Cookbook of Regional Cuisines of India. After improvisations and substitutions, here's my attempt at making Bengali Machcher Jhol:

bengali-machcher-jhol-00.png bengali-machcher-jhol-01.png bengali-machcher-jhol-02.png bengali-machcher-jhol-03.png bengali-machcher-jhol-04.png bengali-machcher-jhol-05.png

22 August 2015 # New habits for 2015

  • 20 min morning meditations.
  • A better way to tie your shoes.
  • Cold showers (all of them!).
  • Keys, wallet, phone, badge, and headphones live together.
  • Listen to audio books.
  • Morning runs.
  • Nightly flossing.

22 August 2015 # Meditation retreats bookmarks

22 August 2015 # Meditation bookmarks

22 August 2015 # Learning bookmarks

22 August 2015 # Bundi travel bookmarks

  • Bundi Haveli (accomodation).
  • Hadoti Palace (accomodation).
  • Haveli Braj Bhushan Ji ki (accomodation).
  • Haveli Katkoun Guest House (accomodation).
  • Kasera Paradise (accomodation).

14 August 2015 # Upgrading PL30 headphones

I've loved my Soundmagic PL30 in-ear headphones. They're relatively inexpensive, comfortable, and great for exercising (they stay in). Audio quality and bass have been good enough (I don't need much). Unfortunately, I've had two pairs of PL30's and both stopped working after a year or two. I'm replacing the last pair with RHA's MA750 (an upgrade, me hopes).

Other contenders considered: Etymotic Research HF5, and Shure SE215. Also considered bluetooth alternatives like JayBird BlueBuds X and Plantronics BackBeat GO 2.

I'm somewhat nervous to pay more for a pair of headphones. Let's hope they don't meet the same unfortunate fate. We'll see.

13 August 2015 # Quotes

13 August 2015 # Bhutan travel bookmarks

12 August 2015 # Cooking bookmarks

11 August 2015 # 9 week half-marathon training

While reading Zen Habits: Mastering the Art of Change, I comitted to running half marathon in mid-October. That's roughly two months from now. Here's a 9 week training schedule:

WEEK MON TUE WED THU FRI SAT SUN
1 Rest 5 Km 5 Km Cycle Rest 5 Km 7 Km
2 Rest 5 Km 5 Km Cycle Rest 5 Km 8 Km
3 Rest 7 Km 5 Km Cycle Rest 5 Km 10 Km
4 Rest 8 Km 5 Km Cycle Rest 5 Km 12 Km
5 Rest 8 Km Rest 8 Km Rest 5 Km 14 Km
6 Rest 8 Km Rest 8 Km Rest 6 Km 16 Km
7 Rest 8 Km 8 Km 8 Km Rest 8 Km 19 Km
8 Rest 8 Km Rest 12 Km Rest 8 Km 16 Km
9 Rest 8 Km Rest 5 Km 5 Km Rest Race

My times:

WEEK MON TUE WED THU FRI SAT SUN
1 Rest 29:04 Rest 26:36 38:40
2 Rest 29:11 28:50 Rest 27:07 44:55
3 Rest 40:46 26:29 Rest 57:01
4 Rest 46:46 Rest 30:08 1:12:10
5 Rest 46:59 Rest 44:46 Rest 24:50 1:25:24
6 Rest 50:02 Rest 46:24 Rest 1:37:39
7 Rest 46:54 46:41 46:42 Rest 1:57:57
8 Rest 45:28 Rest 48:13 (8km) Rest 43:56
9 Rest 44:24 Rest 27:12 26:09 Rest 1:58:28

11 August 2015 # Shanghai travel bookmarks

updated: 29 November 2015

10 August 2015 # Singapore job board bookmarks

08 August 2015 # Germany travel bookmarks

08 August 2015 # Menorca travel bookmarks

08 August 2015 # Travel tools bookmarks

08 August 2015 # Philippines travel bookmarks

23 July 2015 # Add site-specific browsers to your workflow

There are three browser tabs continously used in my workflow: GMail, Google Calendar, and Google Play Music. I normally have many more tabs open, but these three I access periodically. As the number of open tabs increases, and I fail to cleanup, getting back to my usual three gets a little trickier.

So far, I've kept each of these services open in separate windows. But that doesn't always work. Click on any link in your inbox and you're back to playing cleanup. This is where site-specific browsers (SSB) can help.

Epichrome enables you to build Chrome-based SSBs (on Mac OSX). Build an SSB for the usual suspects and easily jump to them using the app switcher.

switcher-small.png

More at OSX Chrome SSB and Quora thread

22 July 2015 # iOS camera bookmarks

20 July 2015 # Sardinia travel bookmarks

  • Alghero.
  • Baja Sardinia.
  • Budoni.
  • Cala Goloritze, Sardinia.
  • Castelsardo (gifts maybe?).
  • Food: Maialetto sardo (Pig), Sebadas, Pardula, Papassinas, Pani e sapa.
  • L'Asinara boat trip (abandoned penitentiary).
  • La Pelosa beach.
  • Nuraghe.
  • Porto Cervo.
  • Porto Torres.
  • San Teodoro.
  • Stintino (fishing port).
  • Zedda e Piras vinyards (Alghero).

17 July 2015 # Open closest build file in Emacs

Whether it's Makefile, SConstruct, BUILD, or your favorite build file, chances are you have to tweak it from time to time. ar/open-build-file searches your current and parent directories to find a build file.

(defvar ar/project-file-names '("Makefile" "SConstruct" "BUILD"))

(defun ar/parent-directory (path)
  "Get parent directory for PATH."
  (unless (equal "/" path)
    (file-name-directory (directory-file-name path))))

(defun ar/find-upwards (path filename)
  "Search upwards from PATH for a file named FILENAME."
  (let ((file (concat path filename))
        (parent (ar/parent-directory (expand-file-name path))))
    (if (file-exists-p file)
        file
      (when parent
        (ar/find-upwards parent filename)))))

(defun ar/open-closest (filename)
  "Open the closest FILENAME in current or parent dirs (handy for finding Makefiles)."
  (let ((closest-file-path (ar/find-upwards (buffer-file-name)
                                                 filename)))
    (when closest-file-path
      (message closest-file-path)
      (switch-to-buffer (find-file-noselect closest-file-path)))
    closest-file-path))

(defun ar/open-build-file ()
  "Open the closest project file in current or parent directory.
For example: Makefile, SConstruct, BUILD, etc.
Append `ar/project-file-names' to search for other file names."
  (interactive)
  (catch 'found
    (mapc (lambda (filename)
            (when (ar/open-closest filename)
              (throw 'found t)))
          ar/project-file-names)
    (error "No project file found")))

15 July 2015 # Create iOS static fat libraries

Have separate static libraries for different iOS architectures? Stitch 'em up into a single fat library using with lipo:

$ lipo -create libOne_i386.a libOne_x86_64.a libOne_armv7.a libOne_arm64.a -output libOne.a

15 July 2015 # Settling scores with an org table

Recently kept track of expenses between a group of us. To settle the scores, I emailed an exported HTML table from an org file. This was simple enough and required no external viewer from recepients. The org table, in all its textful glory, looked as follows…

| Date             | Item           |   Charge |
|------------------+----------------+----------|
| [2015-06-18 Thu] | Cash           |    20.00 |
| [2015-07-11 Sat] | Lucky 7        |    42.97 |
| [2015-07-13 Mon] | Santa Maria    |    32.00 |
| [2015-07-12 Sun] | Tayyabs        |    46.00 |
| [2015-07-13 Mon] | The Brass Rail |    39.00 |
| [2015-07-13 Mon] | Underground    |    10.00 |
| [2015-07-10 Fri] | Cash           |    20.00 |
| [2015-07-13 Mon] | Cash           |    20.00 |
| [2015-07-14 Tue] | Cash           |    20.00 |
|------------------+----------------+----------|
|                  | total          | £ 249.97 |
#+TBLFM: @11$3=vsum(@2..@10);£ %.2f

…while the exported HTML below could be easily pasted on to an email.

Date Item Charge
18 June 2015 Cash 20.00
11 July 2015 Lucky 7 42.97
13 July 2015 Santa Maria 32.00
12 July 2015 Tayyabs 46.00
13 July 2015 The Brass Rail 39.00
13 July 2015 Underground 10.00
10 July 2015 Cash 20.00
13 July 2015 Cash 20.00
14 July 2015 Cash 20.00
  total £ 249.97

13 July 2015 # Recognize new password prompts in Emacs shell

At some point, you may come across a trusted command-line utility prompting you for a password, and Emacs shell happily displaying each typed character to the nearby-world to see. Luckily, you can train Emacs to recognize new password prompts and hide the typed characters in modes deriving from comint. Append the password prompt REGEXP:

(setq comint-password-prompt-regexp (concat comint-password-prompt-regexp
                                            "\\|"
                                            "Password for red alert:"))

11 July 2015 # Bosnia and Hercegovina travel bookmarks

11 July 2015 # Ireland travel bookmarks

  • Skellig Michael.
  • Fishy Fishy in Kinsale: beautiful town on the water.
  • Belfast.
  • Giant's Causeway.
  • Greyhound dog races at Shelbourne Park.

09 July 2015 # Pizza in London

Not tried these yet. Taking note:

  • Bravi Ragazzi (Streatham).
  • Homeslice (Covent Garden).
  • Lord Morpeth (Hackney).
  • Santa Maria (Ealing).
  • Voodoo Ray's (Dalston).
  • Well Kneaded Wagon (Date-dependent location).

09 July 2015 # mp4 to gif

Converting mp4 to gif is handy for posting short screencasts. You can convert to gif using ffmpeg and optimize with imagemagick. To install:

apt-get install ffmpeg imagemagick (linux)
brew install ffmpeg imagemagick (Mac)

Convert to gif:

ffmpeg -i my.mp4 -pix_fmt rgb24 -r 5 my.gif

Optimize with:

convert -dither none -layers Optimize my.gif my_optimized.gif

UPDATE: There's also licecap and subsequently optimize with:

cat source.gif | gifsicle --colors 256 --optimize=3 --delay=15 > target.gif

UPDATE: Also consider for .mov:

ffmpeg -i in.mov -pix_fmt rgb24 -r 10 -f gif - | gifsicle --optimize=3 --delay=3 > out.gif

06 July 2015 # Keyboards bookmarks

05 July 2015 # United States travel bookmarks

05 July 2015 # Lebanon travel bookmarks

05 July 2015 # Slovenia travel bookmarks

05 July 2015 # Belgium travel bookmarks

03 July 2015 # Fishing with Emacs

OK not quite, but having recently learned about C-M-w (append-next-kill), I used it in a keyboard macro to fish out matching lines. This is similar to flush-lines, except the kill ring is also populated. This is handy, if you need the flushed lines. Here's an example.

fishing.gif

Here's the equivalent in Emacs lisp:

(defun flush-kill-lines (regex)
  "Flush lines matching REGEX and append to kill ring.  Restrict to \
region if active."
  (interactive "sFlush kill regex: ")
  (save-excursion
    (save-restriction
      (when (use-region-p)
        (narrow-to-region (point) (mark))
        (goto-char 0))
      (while (search-forward-regexp regex nil t)
        (move-beginning-of-line nil)
        (kill-whole-line)))))

03 July 2015 # California travel bookmarks

01 July 2015 # Rebind caps lock to control key on Mac OS X

Let's see if this one sticks. I'll give caps lock as control a try. Rebinding the keys on Mac OS X is easy enough: caps-lock-to-control.png

System Preferences -> Keyboard -> Keyboard Tab -> Modifier Keys…

30 June 2015 # Searchable ebooks in Emacs

If you haven't bought Mastering Emacs by Mickey Petersen, you should. It's a wonderful source of Emacs tips. Having just finished the ebook on my Kindle, I was keen to go back and fish out some of that newly found wisdom. My immediate reaction was to figure out a way to make the ebook searchable from Emacs.

The ebook is available in epub and pdf format. Though Emacs's docview is super handy for viewing pdf's, searching didn't feel as comfortable as searching in org mode. The epub, on the other hand, proved useful. Pandoc can easily convert from epub to org.

pandoc  --from=epub --to=org mastering-emacs.epub > mastering-emacs.org

After a some tidying (mostly removing BEGIN_HTML/END_HTML blocks and adding TITLE/AUTHOR), the resulting org file is surprisingly clean and easy to search/navigate. helm-swoop and helm-org-in-buffer-headings are great for that. mastering-emacs-org-00.png mastering-emacs-org-01.png mastering-emacs-org-02.png

21 June 2015 # Portugal travel bookmarks

updated: 05 July 2015

21 June 2015 # Bulgaria travel bookmarks

updated: 21 June 2015

21 June 2015 # Presenting bookmarks

21 June 2015 # Bali travel bookmarks

  • Pura Lempuyang, Bali.

17 June 2015 # WWDC app for OS X

Guilherme Rambo created a great OS X OS X app for viewing WWDC content. Just installed it. Super handy. Thanks. Installing as simple as:

$ brew cask install wwdc

15 June 2015 # Debugging Objective-C reference cycles

Overriding retain/release/autorelease may be handy while debugging:

- (instancetype)retain {
  NSLog(@"%p, retain", self);
  return [super retain];
}

- (oneway void)release {
  NSLog(@"%p, release", self);
  [super release];
}

- (instancetype)autorelease {
  NSLog(@"%p, autorelease", self);
  return [super autorelease];
}

13 June 2015 # London grub

Beyond the hype, buzz, and pricey gimmicks… Places to eat in London:

  • Antipode.
  • Arang.
  • Bone Daddies.
  • Gelupo.
  • Grind.
  • Holy Cow.
  • Kerbisher and Malt.
  • Kulu Kulu (South Ken).
  • Le Relais de Venise.
  • Lucky 7's.
  • Royal China.
  • Shree Krishna Vada Pav.
  • Sri Suwoon.
  • Tayyabs.
  • The Cow.
  • Tonkotsu.

08 June 2015 # My working playlist

02 June 2015 # Xcode bookmarks

02 June 2015 # Costa Rica travel bookmarks

02 June 2015 # Australia travel bookmarks

02 June 2015 # Samoa travel bookmarks

02 June 2015 # Norway travel bookmarks

updated: 08 October 2016

02 June 2015 # Los Angeles travel bookmarks

28 May 2015 # Mastering Emacs is out

Emacs is amazingly alive. New packages are regularly listed on melpa and a new book just came out: Mastering Emacs by Mickey Petersen.

cover.png

25 May 2015 # South Carolina travel bookmarks

25 May 2015 # Colorado travel bookmarks

25 May 2015 # Bash bookmarks

25 May 2015 # restclient.el

Installed Pashky's restclient.el Emacs package. Super helpful when trying out REST APIs.

restclient.png

25 May 2015 # Seatle travel bookmarks

25 May 2015 # Berlin travel bookmarks

25 May 2015 # Skeuomorph

From Wikipedia, skeuomorph ˈskjuːəmɔrf is a derivative object that retains ornamental design cues from structures that were necessary in the original. Examples include pottery embellished with imitation rivets reminiscent of similar pots made of metal and a software calendar that imitates the appearance of binding on a paper desk calendar.

25 May 2015 # define-word

Installed Abo Abo's define-word Emacs package. A handy package to define words at point.

define-word.png

22 May 2015 # Flushing empty lines in Emacs

Via masteringemacs.org, removing blank lines in a buffer:

M-x flush-lines RET ^$ RET

22 May 2015 # Regex bookmarks

06 May 2015 # Write to temp iOS snippet

NSString *tempDir = NSTemporaryDirectory();
NSLog(@"%@", tempDir);
NSString *dataFilePath = [tempDir stringByAppendingPathComponent:@"my.file"];
[data writeToFile:dataFilePath atomically:YES];

04 May 2015 # Greece travel bookmarks

04 May 2015 # Sri Lanka travel bookmarks

04 May 2015 # Switzerland travel bookmarks

04 May 2015 # Thailand travel bookmarks

04 May 2015 # Madagascar travel bookmarks

04 May 2015 # Hong Kong travel bookmarks

04 May 2015 # Barcelona travel bookmarks

updated: 26 August 2015

04 May 2015 # Iceland travel bookmarks

updated: 09 February 2016

30 April 2015 # Building clang-format

Based on instructions from Building clang-format and friends on OSX Mountain Lion.

#!/bin/bash
set -o nounset
set -o errexit

# Based on instructions from:
# http://blog.hardcodes.de/articles/63/building-clang-format-and-friends-on-osx-mountain-lion

readonly LLVM_DIR_PATH='/tmp/llvm'

update_repo() {
  if [[ ! -d $1 ]]; then
    git clone $2
  else
    cd $1
    git pull
    cd ..
  fi
  cd ..
}

update_all_repos() {
  update_repo "llvm" "http://llvm.org/git/llvm.git"
  pushd "${LLVM_DIR_PATH}/llvm/tools"
  update_repo "clang" "http://llvm.org/git/clang.git"
  popd
  cd "../../${LLVM_DIR_PATH}/llvm/tools/clang/tools"
  update_repo "clang-tools-extra" "http://llvm.org/git/clang-tools-extra.git"
  cd "../../.."
}

build_clang() {
  mkdir -p clang
  mkdir -p build
  cd clang
  ../llvm/configure --enable-libcpp --enable-cxx11 --enable-debug-symbols=no --enable-optimized --prefix="${LLVM_DIR_PATH}/build"
  make install
}

mkdir -p $LLVM_DIR_PATH
cd ${LLVM_DIR_PATH}
update_all_repos
build_clang

Bonus: use clang-format-configurator.

16 October 2015 # iOS Auto Layout bookmarks

30 April 2015 # Programmatic iOS Auto Layout

Basic iOS auto layout usage. See Adopting Auto Layout and Visual Format language for reference.

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    // Disable autoresizing mask translation for parent.
    self.translatesAutoresizingMaskIntoConstraints = NO;

    _subview1 = [[UIView alloc] init];
    // Disable autoresizing mask translation for subview.
    _subview1.translatesAutoresizingMaskIntoConstraints = NO;

    _subview1.backgroundColor = [UIColor redColor];
    [self addSubview:_subview1];

    // Creates a dictionary of bindings to be used in visual format.
    NSDictionary *viewBindings = NSDictionaryOfVariableBindings(_subview1);

    // H: horizontal layout
    // |-50- spacing in relation to superview
    // [_subview1(==50)] subview1's width
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-50-[_subview1(==50)]"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:viewBindings]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_subview1(==50)]"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:viewBindings]];
  }
  return self;
}

Also consider:

  • A UIView Subclass should implement intrinsicContentSize.
  • A UIView Subclass should never add constraints on neither itself (ie. self) nor superview.

23 April 2015 # Japan travel bookmarks

21 October 2015 # Kyoto travel bookmarks

updated: 16 October 2016

19 April 2015 # Tokyo travel bookmarks

updated: 16 October 2016

19 April 2015 # UK travel bookmarks

19 April 2015 # Development quotes

19 April 2015 # Spain travel bookmarks

19 April 2015 # Meet up bookmarks

17 April 2015 # Plantuml example

Played with Plantuml. Convenient for generating UML diagrams from text. Here's the Language Reference Guide. Here's an example:

@startuml
  abstract class Singer {
    abstract void sing()
    void Dance()
  }

  skinparam monochrome true
  Singer <|-- PopSinger
  Singer <|-- SalsaSinger

  class PopSinger {
    void sing()
  }

  class SalsaSinger {
    void sing()
  }

@enduml

plantuml-singer.png

Install plantuml on Mac OS X:

brew install plantum

Generating diagram:

$GRAPHVIZ_DOT=~/homebrew/bin/dot java -jar path/to/plantuml.8018.jar diagram.plantuml

ps. Installation and verification gist.

14 April 2015 # Helm-describe-helm-attribute

Writing A Spotify Client in 16 Minutes is fantastic for picking up helm and Emacs lisp tips. Of interest helm-describe-helm-attribute, second to the awesomeness of helm-spotify integration.

<iframe width='420' height='315' src='https://www.youtube.com/embed/XjKtkEMUYGc' frameborder='0' allowfullscreen> </iframe>

12 April 2015 # Youtube videos in your org html export

Sacha Chua and John Wiegley posted a wonderful video on Emacs lisp development tips. Embedding the following raw HTML using #+BEGIN_HTML/#+END_HTML:

<iframe width="420"
        height="315"
        src="https://www.youtube.com/embed/QRBcm6jFJ3Q"
        frameborder="0"
        allowfullscreen>
</iframe>

results in an embedded video when exporting your org file:

<iframe width="420" height="315" src="https://www.youtube.com/embed/QRBcm6jFJ3Q" frameborder="0" allowfullscreen> </iframe>

12 April 2015 # .net bookmarks

10 April 2015 # UK property bookmarks

09 April 2015 # Git commit message style

Adopted Tim Pope's Git commit message style. Also enabled Emacs's git-commit-training-wheels-mode:

(use-package git-commit-training-wheels-mode :ensure t
  :commands (git-commit-training-wheels-mode))

(use-package git-commit-mode :ensure t
  :config
  (add-hook 'git-commit-mode-hook 'git-commit-training-wheels-mode)
  :commands (git-commit-mode))

Another great post by Chris Beams.

06 April 2015 # fci-mode and org-html-export-to-html bug

Having enabled fci-mode in most programing modes, org-html-export-to-html now exports an additional unicode character in source blocks. This thread has a workaround:

(defun org-html-fontify-code (code lang)
  ;; ...
  (funcall lang-mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  (when (require 'fill-column-indicator nil 'noerror)
    (fci-mode -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  (insert code)
  ;; ...

03 April 2015 # Try cocoapods out

Cocapods try:

$ pod try POD_NAME

03 April 2015 # Cornwall travel bookmarks

03 April 2015 # Austria travel bookmarks

02 April 2015 # Cinnamon desktop run dialog

Note to self. Open with Alt-f2.

29 March 2015 # Books for 2015

29 March 2015 # Ayahuasca bookmarks

28 March 2015 # Emacs init.el bookmarks

28 March 2015 # CSS vertical align using flex

Codepen snippet:

div{
  height: 200px;
  background: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}

p{
  margin: auto
}

26 March 2015 # London diving schools

26 March 2015 # Helm buffer URLs

Venturing into Emacs lisp and Helm. Here's a go at listing all URLs in current buffer.

(require 'goto-addr)

(defun ar/helm-buffer-url-candidates ()
  "Generate helm candidates for all URLs in buffer."
  (save-excursion
    (goto-char (point-min))
    (let ((helm-candidates '())
          (url))
      (while (re-search-forward goto-address-url-regexp
                                nil t)
        (setq url
              (buffer-substring-no-properties (match-beginning 0)
                                              (match-end 0)))
        (add-to-list 'helm-candidates
                     (cons url
                           url)))
      helm-candidates)))

(defun ar/helm-buffer-urls ()
  "Narrow down and open a URL in buffer."
  (interactive)
  (helm :sources `(((name . "Buffer URLs")
                    (candidates . ,(ar/helm-buffer-url-candidates))
                    (action . (lambda (url)
                                (browse-url url)))))))

23 March 2015 # Doh! undo last git commit

$ git reset --soft HEAD~1

22 March 2015 # Resetting variables using defvar

Want to re-evaluate defvars and modify variables? eval-defun (bound to C-M-x) can help. From the manual:

If the current defun is actually a call to `defvar', then reset the variable using its initial value expression even if the variable already has some other value. (Normally `defvar' does not change the variable's value if it already has a value.) Treat `defcustom' similarly.

22 March 2015 # Broken Xcode plugins?

Some Xcode plugins stopped loading after updating Xcode. Ensure the latest DVTPlugInCompatibilityUUIDs is added to the plugin's Info.plist. Get from:

$ defaults read \
    /Applications/Xcode.app/Contents/Info DVTPlugInCompatibilityUUID

Additional suggestions as Stack Overflow.

22 March 2015 # Born to Run references

updated: 23 March 2015

References from reading Christopher McDougall's Born to Run:

Recipe by Megan Mignot, based on book references:

Mama Tita’s Pancakes

  • 1 ½ cups cooked brown rice
  • 1 cup coconut milk
  • 2 ripe bananas
  • 1 tablespoon honey
  • ½ cup white cornmeal
  • 2 teaspoons baking powder

19 March 2015 # Org tips from 2015-03-18 Emacs hangout

updated: 22 March 2015

Lots of great tips in Emacs Hangout 2015-03-18. Favorites:

  • Private org drawer to prevent export:
:PRIVATE:
My super duper secret text I don't want to export.
:END:
  • C-c C-p/C-c C-n Jump over sections.
  • (setq org-hide-leading-stars t).
  • (org-bullets-mode).
  • (org-refile).
  • C-u (org-refile) jumps, no refile.
  • (helm-org-in-buffer-headings).

19 March 2015 # Food bookmarks

19 March 2015 # Ethiopia travel bookmarks

19 March 2015 # China travel bookmarks

18 March 2015 # South Korea travel bookmarks

18 March 2015 # Sharing on iOS

NSString *title = @"Sharing on iOS bookmarks.";
NSURL *url = [NSURL URLWithString:@"http://xenodium.com/#sharing-on-ios"];
UIImage *image = [UIImage imageNamed:@"beautiful-image"];

UIActivityViewController *controller =
  [[UIActivityViewController alloc]
    initWithActivityItems:@[title, url, image]
    applicationActivities:nil];

// self being a UIViewController.
[self presentViewController:controller animated:YES completion:nil];
  • Sharing through Mail app on simulator isn't supported.

viewServiceDidTerminateWithError: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "The operation couldn’t be completed. (_UIViewServiceInterfaceErrorDomain error 3.)" UserInfo=… {Message=Service Connection Interrupted}

18 March 2015 # San Francisco travel bookmarks

18 March 2015 # Istanbul travel bookmarks

18 March 2015 # Rome travel bookmarks

17 March 2015 # Italy travel bookmarks

17 March 2015 # Emacs lisp debug on entry

Wanted to track down which package was enabling ido-mode on my behalf. debug-on-entry to the rescue. Pass the method name in question and you're good to go.

(debug-on-entry 'ido-mode)

When done, use cancel.

(cancel-debug-on-entry 'ido-mode)

17 March 2015 # Burma travel bookmarks

updated: 19 June 2016

16 March 2015 # OS X Screencasts to animated GIF

15 March 2015 # Writing Xcode plugins

defaults read \
    /Applications/Xcode.app/Contents/Info DVTPlugInCompatibilityUUID

15 March 2015 # Uninstalling Alcatraz from Xcode

$ rm -rf ~/Library/Application\ Support/Developer/Shared/Xcode/Plug-ins/Alcatraz.xcplugin
$ rm -rf ~/Library/Application\ Support/Alcatraz

ps. Removing all plugins:

$ rm -rf ~/Library/Application\ Support/Developer/Shared/Xcode/Plug-ins/*

14 March 2015 # Prefill Emacs swiper with current region

The new swiper Emacs package is proving to be a great alternative to helm-swoop. Here's how to prefill with current region:

(defun ar/prefilled-swiper ()
  "Pre-fill swiper input with region."
  (interactive)
  (if (region-active-p)
      (let ((region-text (buffer-substring (region-beginning)
                                           (region-end))))
        (swiper region-text))
    (swiper)))

(global-set-key (kbd "C-s")
                #'ar/prefilled-swiper)

14 March 2015 # Change Mac OS app icon

  • Open the new icon (.icns) in Preview.
  • Select all (⌘-a).
  • Copy (⌘-c).
  • Ctrl-click on app icon.
  • Select Get Info.
  • Click on app icon (top-left).
  • Paste (⌘-v).
  • Done!

overriding.png

after.png

11 March 2015 # Hack on Emacs London meetup bookmarks

09 March 2015 # Working with OS X and Emacs tips

From M-x all-things-emacs, Ryan McGeary's OS X/Emacs workflow.

Dotfiles

09 March 2015 # Building ycmd

Build

$ git clone https://github.com/Valloric/ycmd.git
$ cd ycmd
$ git submodule update --init --recursive
$ ./build.sh --clang-completer

Test

$ python ycmd
  serving on http://127.0.0.1:54265

08 March 2015 # Regular bookmarks

08 March 2015 # Photography bookmarks

08 March 2015 # Paris travel bookmarks

updated: 13 July 2016

08 March 2015 # Org mode bookmarks

08 March 2015 # London food backlog

Barnsbury

  • TODO Sunday (breakfast, cafe, working).

Brick Lane

Bermondsey

  • TODO Druid Street market
    • FAT London (Kimchee ).
    • & Cultured butter.

Brixton

  • TODO Nanban (Japanese soul food).

Borough

Broadway Market

  • TODO Poco (Tapas bar).

Camberwell

Canada Water

Covent Garden

Clapham

Crouch end

Ealing

  • TODO Kiraku (Sushi).

Edware road

  • DONE GOGI (korean): Average. Also, they lied to me and apologized with £10 credit.

Euston

  • TODO Roti King (Indian/Pakistani/Singaporean): 40, Doric Way, Euston, NW1 1LH.

Farringdon

  • TODO Quality Chop House.
  • TODO Daddy Donkey (Mexican).
  • TODO J+A (coffe, working).

Fitzrovia

Golders Green

  • TODO Cafe Japan (Sushi).

Hackney

Hammersmith

Hamstead

Harrow

Hatch End

Holborn

Holloway Road

  • TODO Xi'an impression (Xi'an)

Islington

Kensington

  • TODO Clarke's, try the burger.

Kensal Green

Kentish town

Liverpool street

Marylebone

  • DONE Fischer's (Austrian). Great atmosphere and schnitzel. Not cheap.
  • TODO Nambutei (Sushi).
  • TODO Lurra (Basque).

Mayfair

Notting Hill

  • TODO Blend (coffee, working).

Old Street

Oxford street

  • TODO Roti Chai (Indian).

Peckham

Shoreditch

Sloane Square

Soho

Southhall

TODO Brilliant restaurant (healthier Indian).

South Kensington

  • TODO Hour Glass (Pub restaurant).

Smithfield

Stoke Newingtom

Tottenham Court Road.

Tower Hill

Tufnell Park

  • TODO Monsoon (Indian), try lamb naga.

Walthamstow

Waterloo

West Hamstead

Whitechapel

  • TODO Lahore Kebab House, try seekh kebabs with roti.
  • TODO Sushinoen.

Wimbledon

  • TODO Dalchini (Indian), try spicy cocunut fish curry.

07 March 2015 # UX bookmarks

07 March 2015 # Unix/Linux tips backlog

updated: 27 January 2016

07 March 2015 # Recipes

Tom Kha Gai soup

  • Chicken or Prawns
  • 2 kaffir lime leaves
  • 1 lemongrass stalk
  • 1 1/2 cocunut milk
  • 3/4 sliced fresh galaghal
  • 1 1/2 chicken stock or water
  • 1/2 cup mushrooms
  • 3 1/2 tbsp sugar
  • 1/2 cup of cilantro
  • 1-4 thai chillies
  • 1-2 tbsp chili oil
  • 1 green onion

Veg-Fruit juice

  • Lime
  • Ginger
  • Apple
  • Chilly
  • Celery
  • Fig
  • Blueberries

Berry Hempster

  • Hemp milk
  • Hemp protein
  • Strawberry
  • Blueberry
  • Date

How to cook Beef Chow Fun.

07 March 2015 # Music backlog

06 March 2015 # UX scrapbook bookmarks

09 October 2015 # Travel blog bookmarks

06 March 2015 # Travel bookmarks

06 March 2015 # Startup bookmarks

updated: 27 November 2016

06 March 2015 # Romania travel bookmarks

06 March 2015 # Productivity tips backlog

updated: 11 January 2016

06 March 2015 # Productivity bookmarks

updated: 06 December 2015

06 March 2015 # Privacy bookmarks

06 March 2015 # Mindfulness bookmarks

06 March 2015 # Lifestyle bookmarks

06 March 2015 # iOS imaging bookmarks

06 March 2015 # Graphics bookmarks

06 March 2015 # Nexus Q bookmarks

06 March 2015 # Go bookmarks

updated: 29 November 2016

06 March 2015 # GitHub

06 March 2015 # Courses bookmarks

05 March 2015 # Reload inputrc

Reload .iputrc from bash prompt: C-x C-r. More at bashref manual.

05 March 2015 # Learning Emacs lisp

updated: 13 April 2015
  • Use nreverse and nconc to operate on lists in-place.
  • Set buffer local variables:
(setq-local my-clever-var)
  • Execute before saving buffer:
(add-hook 'write-file-hooks
          (lambda ()
            (message "about to save!")))
  • Possibly use to start processes and send file content:
(make-comint NAME PROGRAM &optional STARTFILE &rest SWITCHES)
  • Creating markers:
(setq my-marker (copy-marker (point)))
  #<marker at 10251 in *ielm*>

(marker-buffer my-marker)
  #<buffer *ielm*>

(marker-position my-marker)
  10251 (#o24013, #x280b, ?⠋)
  • Get org heading at point:
(org-get-heading 'no-tags 'no-todo)
  • Remove string text properties. From manual:

(substring-no-properties STRING &optional FROM TO)

Return a substring of STRING, without text properties. It starts at index FROM and ends before TO. TO may be nil or omitted; then the substring runs to the end of STRING. If FROM is nil or omitted, the substring starts at the beginning of STRING. If FROM or TO is negative, it counts from the end.

  • Skip org entry metadata/drawers:
(org-end-of-meta-data-and-drawers)
  • Random access to org entry using id (or CUSTOM_ID):
(org-open-link-from-string "[[#%exciting-custom-id]]")
  • Go to where the function is defined.
  • Press C-u C-M-x. Edebug breakpoint for function.
  • Invoke function in question.
  • n/c will get you around.
  • q when done.
  • Pretty printing objects:
(let ((my-var (list "val1"
                    "val2"
                    "val3")))
  (pp-to-string my-var))
  • Search and/or replace in curent buffer:
(re-search-forward "needle"
                   nil t)
(match-beginning 0) ;; Start location of match from last search.
(match-end 0) ;; End location of match from last search.
(replace-match "love")

;; needle-in-haystack
  • Restrict buffer editing to a region:
(narrow-to-region (point)
                  (point-max))
  • Restore restriction:
(save-restriction (narrow-to-region (point)
                                    (point-max))
  • Restore point, mark, and current buffer:
(save-excursion (goto-char (point-max))
                (insert "Hello elisp."))
  • Concatenating strings:
(concat "Hello " "elisp " "world.")
  • Grabbing thing at point:
(thing-at-point 'word)
(thing-at-point 'symbol)
(thing-at-point 'line)
  • Unit test with ert.
  • Basic iteration with dolist:
(dolist (v '("a" "b" "c"))
  (print v))
  • Output to other buffer:
(with-current-buffer (get-buffer-create "*some buffer*")
  (princ '(some list to print)
         (current-buffer)))
  • For a temporary buffer, use with-temp-buffer:
(with-temp-buffer
  (insert "abc")
  (point))
  • Cons cells bookmark.
  • Check for substring:
(string-match-p REGEXP STRING &optional START)
  • Matching substrings and accessing groups:
(setq haystack "Always click [[http://reddit.com/r/emacs][here]].")
(setq needle-re "\\[\\[\\(.*\\)]\\[\\(.*\\)]]")
  "\\[\\[\\(.*\\)]\\[\\(.*\\)]]"

(string-match needle-re haystack)
  13 (#o15, #xd, ?\C-m)

(match-string 0 haystack)
  "[[http://reddit.com/r/emacs][here]]"

(match-string 1 haystack)
  "http://reddit.com/r/emacs"

(match-string 2 haystack)
  "here"
  • Return argument unchanged (noop):
(identity ARG)
  • Org insert today's timestamp
(org-insert-time-stamp (current-time))
(car LIST)
  • All but first element
(cdr LIST)
  • Add NEWELT to front of PLACE
(push NEWELT PLACE)
  • Invoke 'FUNCTION for each in SEQUENCE
(mapcar FUNCTION SEQUENCE)
  • Search/replace
(while (search-forward "Hello")
  (replace-match "Bonjour"))
  • Save to kill ring = copy.
  • Point = cursor position.
  • Mark = a buffer position.
  • Kill = cut text.
  • Yank = paste.
  • Buffer:File = 1:1.
  • Window:Buffer = 1:1.
  • Frame:Window = 1:many.
  • Font lock = syntax highlighting.

06 March 2015 # Apple Watch bookmarks

05 March 2015 # iOS bookmarks

updated: 18 September 2016

05 March 2015 # Kerala travel bookmarks

  • Bagel Shop, 30 Pali Mala Road, off Carter Road, Bandra (W) (+91 22 2605-0178). Daily 9.00AM-10.00PM. Meal for two R500-R800.
  • Hotel Natraj, 22-24 City Station Road, Udaipur (near Bapu Bazaar), +91-294-2487488, +91-94147-57893,
  • Kala Ghoda Café,10 Ropewalk Lane, Kala Ghoda (+91 22 2263-3866). Daily 8.30AM-11.30PM. Meal for two R600.
  • Kochin (Fort Kochin) - old port town with Chinese, Portuguese, Dutch, British and Jewish heritage.
  • Munnar - hill station and centre of tea, coffee and spice growing. Great hiking and spectacular views.
  • Periyar Wildlife Sanctuary.
  • Suzette, Atlanta Building, Nariman Point (+91 22 2288-0055). Daily 9.00AM-11.00PM. Also at Bandra. Meal for two R600-R1,000.
  • Varkala - chilled out beach resort.
  • Yoga House, 53 Chimbai Road, behind St Andrew's Church, off Hill Road, Bandra (W)(+91 22 6554- 5001). Daily 7.00AM-10.30PM.

05 March 2015 # India travel bookmarks

updated: 13 November 2016

05 March 2015 # Git bookmarks

04 March 2015 # Language learning bookmarks

18 February 2015 # Git conflict resolution déjà vu?

use git rerere. here's a post.

17 January 2015 # Graphics design tools bookmarks

23 April 2015 # Emacs key bindings and maps

based on masteringemacs.org.

bonus tip

prefix key, followed by c-h, lists keys in prefix.

keymap

maps key to action.

keymap found in buffer and most major modes.

keys

  • undefined: self explanatory.
  • prefix key: ie. c-x (part of complete key).
  • complete key: complete input executes associated command.

mapping

  • (define-key keymap key def): add to current buffer map.
  • (local-set-key key command): add to active buffer (no map option).
  • (local-unset-key key)
  • (global-set-key key command): add to global keymap (all buffers).
  • (global-unset-key key)

key codes

  • kbd: macro transaltes human-readable key to emacs readable.
  • function and navigation keys must be surrounded by <>.
  • example: (kbd "c-c p") or (kbd "<f8>") of (kbd "<down>").

remapping

  • use remap to replace mapping (ie. kill-line with my/kill-line).
  • (define-key keymap [remap original-function] 'my-own-function).

reserved keys

  • "c-c ?" generally reserved for you, but third party packages use it.
  • function keys (ie. f1-f12).
  • hyper and super (ancient).

lookup order

  • in a nutshell: minor mode keys, local keys, global keys.
  • full order:
    1. overriding-terminal-local-map: terminal-specific key binds.
    2. overriding-local-map: override all other local keymaps (avoid if possible).
    3. char property at point: useful for yasnippet.
    4. emulation-mode-map-alists: advanced multi-mode keymap.
    5. minor-mode-overriding-map-alist: minor modes in major modes.
    6. minor-mode-map-alist: as previous (preferred for minor modes) <–—
    7. current-local-map: buffers current local map.
    8. current-global-map: last place to look (ie. global).

mode hooks

  • (local-set-key (kbd "c-c q") 'my-awesome-method)) in hook-method.
  • for key-chord-define, use current-local-map.

30 December 2014 # Video backlog

updated: 02 October 2016

18 September 2014 # Origami bookmarks

30 December 2014 # Movie backlog

updated: 01 October 2016

29 December 2014 # Microservices bookmarks

30 December 2014 # Books backlog

updated: 12 November 2016

29 December 2014 # Gardening bookmarks

03 December 2014 # Emacs tips backlog

updated: 16 October 2016

09 July 2014 # Installing Emacs 24.4 on Linux

sudo apt-get install texinfo build-essential xorg-dev libgtk-3-dev libjpeg-dev libncurses5-dev libgif-dev libtiff-dev libm17n-dev libpng12-dev librsvg2-dev libotf-dev

09 July 2014 # Installing Emacs 24.4 on Mac OS X

See Yamamoto's Mac OS X port. To install:

$ brew tap railwaycat/emacsmacport
$ brew install emacs-mac

02 November 2014 # Xcode6 tips

Shortcuts

  • ⌘⇧o Fuzzy file search.
  • ⌘⌥j Fuzzy file search (showing in Xcode project hierarchy).
  • ⌘⇧j Show file in Xcode project hierarchy.
  • ⌘⌥0 Show/hide utility area (right panel).
  • ⌘0 Show/hide navigation area (left panel).
  • ⇧⌘Y Show/hide debug area (bottom panel).
  • Ctrli Indent selection.
  • ⌘\ Toggle breakpoint on line.
  • ⌘/ Toggle comment.
  • ⌘[1-8] Select tabs on left panel.
  • Ctrl[1-x] Select top file navigation menu items.

Xcode features

  • Snippets.
  • Templates.
  • View debugging.
  • Simctl (send files to simulator).

Plugins of interest

  • Fuzzy autocomplete.
  • Uncrustify for indentation.
  • xcs code switch expansion.
  • Org and order (for properties).

12 December 2015 # Simple ssh tunnel

Via @climagic, connections to tcp localhost:9909 will be made to 192.168.1.1:80 via SSH tunnel to home.

ssh -L 9909:192.168.1.1:80 home

20 September 2014 # Emacs lisp bookmarks

19 September 2014 # Emacs bookmarks

updated: 12 November 2016

11 September 2014 # Resetting gnome-terminal preferences

Resetting preferences

gconftool --recursive-unset /apps/gnome-terminal

Want 256 colors?

Edit .bash_profile

export TERM="screen-256color"

Ensure .bash_profile is loaded

From gnome-terminal window:

gnome-terminal Edit Profiles… Edit Title and Command X Run command as login shell

Solarized

Bonus: See post to get solarized on gnome-terminal.

09 October 2014 # C++ bookmarks

14 July 2014 # Java bookmarks

updated: 16 November 2015

14 July 2014 # Browser bookmarks

14 July 2014 # Node bookmarks

14 July 2014 # JavaScript bookmarks

updated: 29 November 2016

14 July 2014 # HTML5 bookmarks

14 July 2014 # Networking bookmarks

13 July 2014 # Python bookmarks

13 July 2014 # Development bookmarks

updated: 16 October 2016

04 November 2013 # Some python idioms

  • Prefer double quotes if escaping single quotes.
  • Prefer string interpolation over join. Eg. "'%s'" % member_default.
  • Prefer double underscore for privates.
  • Prefer with statement to implicitly close file.
with open(path, 'r') as text_file:
    text = text_file.read()
  • Prefer list comprehensions to filter.
  • Prefer using separate modules over classes if only using for separation.
  • Keep in mind: "eafp vs lbyl" (ie. just let it throw).
  • Prefer exceptions over assertions.
  • Throw ValueError for wrong input.
  • Return explicit False if remaining case is always false.