Skip to content

Instantly share code, notes, and snippets.

@tallus

tallus/tip_sheet.md

Last active Oct 6, 2020
Embed
What would you like to do?
Tip Sheet

Vim Tips

  • gv redo visual selection
  • :%s/\s\+$// Delete unwanted white space
  • :%s/,([^ ])/, \1/g Add spaces after commas
  • :s/MATCH/&ADD apend ADD after MATCH
  • %s/".{-}", //g .{-} non greedy match e.g. "foo", 1, "bar", 2 -> 1, 2
  • :[RANGE]g/MATCH COMMAND1 | COMMAND2... for lines matching MATCH (in RANGE) execute COMMAND1, COMMAND2 etc.
  • :g/MATCH/d Delete all lines containing MATCH (remove d to show lines)
  • :g/^\s*$/d Delete all blank lines
  • :g!/^\s*H/d Delete all lines that are not comments
  • g/^/t. duplicate lines g/^/ matches all lines t copy and paste on . line below
  • :g/param/ copy . | s//type/g Copy lines matching param add new line below substituting type for param -:[RANGE}t N copy RANGE lines then paste at line N
  • "0p paste last yanked text: the 0 register contains only yanked text not deleted text, and is populated automatically without "0y having to be used
  • '' jump back to previous position at beginning of line
  • `` jump back to previous position
  • Ctrl + o, Ctrl + i Move back and forth in jump list
  • g; / g, move back- and forward in the list of your previous edit locations
  • g_ last non-whitespace char
  • A jump to end of line and append
  • I jump to beginning of line and insert
  • oInsert a new line after the current one and enter insert mode
  • OInsert a new line before the current one and enter insert mode
  • 0 start of line vs ^ first non white space
  • [n]| jump to n column
  • f[x] jump to next occurrence of character x
  • t[x] jump to one character before the character x
  • in normal mode jump to next non space character on the line after
  • - in normal mode jump to next non space character on the line before
  • ) jump to next sentence. In Python files approximately blank line or code block
  • <code( jump to previous sentence
  • } jump to next paragraph (next blank line)
  • <code{ jump to previous paragraph
    • ]] jump between braces? In Python files next line with char at col 1 (so class or def (if function not method)
  • <code[[ as above but up
  • gg=G reindent the whole file
  • q: edit command line(s)
  • q/, q? edit search string(s)
  • Visually select then : sort u Sort lines (Pressing : in visual mode inserts '<,'>)
  • :!python -c "CODE GOES HERE" execute code (also !bash)
  • :%!python -c "CODE GOES HERE" execute code and replace file contents % can also be . for current line, range etc
  • type python code, visually select, then :!python executes python code and replaces it with its own output
  • :[range]pydo {body} execute body for each line in range

Vim folding

  • za toggle fold (1 level)
  • zc close fold (1 level)
  • zo open fold (1 level)
  • zA toggle all nested folds at this level
  • zC close all nested folds at this level
  • zO open all nested folds at this level
  • zr reduce (open) folds one level throughout buffer
  • zR open all folds
  • zm close one more level of folds throughout buffer
  • zM close all folds

Vim mode keyboard shortcuts

work on commandline, inc vims commandline mode

  • Ctrl left/right: move to next word/argument
  • Ctrl u; clear line
  • Ctrl w: delete word before cursor
  • Ctrl k: delete to end of line

Vim Windows keyboard shortcuts

  • ctrl W + r: rotate window down/right
  • ctrl W + R: rotate window up/left
  • ctrl h: move cursor to next window(right)
  • ctrl l: move cursor to previous window(left)

Vim Surround

  • ysiw" Surround text with " when cursor is in word " can be repalced with anything inc tags <em> etc
  • S" Surround selected text with " etc
  • cs"' Replace " with '
  • ds" Delete "
  • cst" replace tag with "
  • yss" wrap entire line with "
  • cs") replace " with ( & )
  • cs"( replace " with ( & ) and space inside ( & )
  • ysl<space><space> surround a single character with spaces S<space><space> in visual mode

Git Tips

  • git add -u . add modified and deleted only, for current directory
  • git add -u /file/path add modified and deleted only, for path :/ is base i.e. all of repo
  • git add -u add modified and deleted only, for all of rep
  • git branch --merged show merged branches
  • git branch -m OLD NEW rename (--move) branch
  • git checkout -- [file] revert an unstaged file to last commit
  • git checkout [branch_name] -- [path to file] checkout file from another branch
  • git commit -a[m] [file]Add and commit
  • git config --global alias.[alias] "[git options]" git alias
  • git config --global push.default simple adopt new push behaviour -- only push branch you are on
  • git diff $start_commit..$end_commit -- [path/to/file] diff between commits
  • git diff --cached compares staged(i.e. files staged with git add) and HEAD
  • git diff --color-words highlight words changed in lines
  • git diff --name-only --diff-filter=U Show files with merge conflicts
  • git diff --staged synonym for --cached
  • git diff HEAD [file] Show the differences between your working directory and the most recent commit, includes files git added
  • git diff HEAD^^ HEAD file.py diff between now and two commits ago
  • git diff mybranch master -- myfile diff between branches
  • git fetch ;git checkout test (git checkout -b test remote-name/test with multiple remotes) checkout remote branch
  • git fetch; git checkout --track origin[branch] checkout remote branch
  • git log --first-parent Roughly exclude commits from merged in branch
  • git log --graph --decorate --pretty=one-line --abbrec-commit --all
  • git log --name-only Show names of files changed
  • git log --patch show patch
  • git log --stat --decorate --graph --decorate --all --oneline
  • git pull --prune prune deleted branches on remote
  • git push -u origin -u : set upstream tracking
  • git reflog log of all places HEAD has been (tracks resets, reverts etc)
  • git reset --hard Reset to last commit remove changes, remove history
  • git reset --soft HEAD~2; git commit --amendGo back two commits and then amend that commit with the changes in later commits.
  • git reset --softReset to last commit keep changes in files and keep them staged, remove history
  • git reset --softReset to last commit keep changes in files and unstaged, remove history
  • git revert [hash] revert commit (add to history)
  • git update-index --assume-unchanged path/to/file ignore local changes to comitted file
  • git update-index --no-assume-unchanged path/tofile strack changes again
  • git update-index --skip-worktree [file] Ignore local changes to tracked file(e.g. config file), takes preference over assume-unchanged

PPA for latest stable git

sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get install git

Python Tips

  • "".join(" \t foo \n bar ".split()) -> 'foobar' Strip all white space characters

Django Tips

  • rename a field with out migrations:

old:

my_field = models.Field()

new:

my_field models.Field(db_column="my_field")

optionally:

@property
def my_field(self):
 return self._my_field

Zsh Tips

  • foo -‹tab›‹tab› Show argument options
  • kill foo‹tab› Suggest process to kill
  • scp foo@bar File completions with scp if public key enabled
  • foo‹up› or ‹down› Type string then press up or down to search history if history-substring-search plugin enabled.
  • <esc> v -- enter editor mode. i.e. edit command line in vi(m) needs: autoload edit-command-line; zle -N edit-command-line; bindkey '\ev' edit-command-line in .zshrc

(Z)Shell Tips

  • ![command] run last version of [command]

  • ![command]:p print last version of [command]

  • !$ arguments from last command

  • !! s/one/two/ run last command substituting two for one

  • ^commnad^command^ search and replace on last command

  • mv /path/to/file.{txt,xml} file.txt -> file.xml

  • cp /etc/rc.conf{,-old} rc.conf -> rc.conf-old

  • mv /etc/rc.conf{-old,} rc.conf-old -> rc.conf

  • mkdir myfolder{1,2,3} folder1, folder2, folder3

Tmux Tips

  • tmux rename-session [-t [old-session]] [session-name]

###tswitch Replace the current session with a detached one. Useful if you autostart tmux, and e.g. want to switch back to a session after your connection dropped.

#!/bin/bash
new_session=$(tmux display-message -p "#S")
tmux switch-client -t $1
tmux kill-session -t $new_session

iterm2

  • move a window in a split plane: Hold CMD-SHIFT-OPT (WINKEY-SHIFT-ALT) and drag the pane

Eslint

  • // eslint-disable-next-line no-use-before-define

Docker

  • docker-compose up --detach --renew-anon-volumes --no-deps --force-recreate --build [service]rebuild and start docker service forcing it to completly rebuid
  • docker-compose up -d [service] (-d, --detach) start and run in background
  • docker ps -a show all containers (not just running)
  • docker ps -a -f status=exited Show exited containers
  • docker rm id_or_name remove container
  • docker images -a show all images including intermediate
  • docker rmi image_id remove image
  • docker images -f "dangling=true" -q) Show dangling images
  • docker image prune Remove dangling images
  • docker rmi $(docker images -f "dangling=true" -q) Delete dangling images
  • docker volume ls -f dangling=true list dangling volumes
  • docker volume rm $(docker volume ls -f dangling=true -q) remove dangling volumes
  • direct download for Mac: https://download.docker.com/mac/stable/Docker.dmg (no registration)

IPython tips

  • object? get help about object: docstrings etc
  • %edit edit in temporary file with editor
  • %edit -p open editor with data from last time it was used in session
  • %run script.py run script and print results
  • %debug activate debugger
  • %save file.py 1-2 4-6 save specified lines to file
  • %recall 1 recall line no (like ! in shell)
  • %history [ 20-22]/[-1/4] print input history [these lines]/[line for from last session]
  • %timeit
  • !shell_cmd run shell cmd
  • ouput = !shell_cmd save output of shell cmd to a python variable

OperationalError: (2006, 'MySQL server has gone away')

import django.db
django.db.close_old_connections()

Auto reload

%load_ext autoreload
%autoreload 2

Reload all modules (except those excluded by %aimport) automatically now.

Command Meaning
%autoreload 0 Disable automatic reloading.
%autoreload 1 Reload all modules imported with %aimport every time before executing the Python code typed.
%autoreload 2 Reload all modules (except those excluded by %aimport) every time before executing the Python code typed.
%aimport List modules which are to be automatically imported or not to be imported.
%aimport foo Import module ‘foo’ and mark it to be autoreloaded for %autoreload 1
%aimport -foo Mark module ‘foo’ to not be autoreloaded.

Vim Keybindings

Install nbextensions:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user

Install Vim Bindings:

mkdir -p $(jupyter --data-dir)/nbextensions
cd $(jupyter --data-dir)/nbextensions
git clone https://github.com/lambdalisue/jupyter-vim-binding vim_binding

Activate:

Permanent

jupyter nbextension enable vim_binding/vim_binding

Activate from a notebook (optional)

%%javascript
Jupyter.notebook.config.update({
  'load_extensions': { 'vim_binding/vim_binding': true },
});

Productivity unlocked!

Usage

  • <f1>: show key bindings
  • Enter Vim mode (a super mode of Vim command mode and Insert mode) (note appears to be automatic when clicking on cell)
    1. (Double) click a cell
    2. <Enter> in a cell
    3. Hit i on a cell
  • Leave Vim mode and re-enter Jupyter mode by hitting <S-Esc> (Shift-Escape)
  • Enter Insert mode or leave Insert mode as like Vim (i, a, etc.)
  • :w save and checkpoint
  • yy yank cell
  • Ctrl + n or Ctrl + p: completion
  • Ctrl + g: tooltip
  • j/k etc next/previous cell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.