Subhajit Paul
>

ref

quick-search reference — copy, paste, move on

428 commands · 101 topics·7 categories·/ search·Ctrl K palette, anywhere on the site

>

click any line to copy it · dashed args are editable in place · ↑↓ + Enter

Find files by name / size / ageLinux

find with the filters you actually use

find . -name '*.log'  # by name (glob)
copy
find . -iname 'readme*'  # case-insensitive
copy
find . -size +100M  # bigger than
copy
find . -mtime -7  # modified in last N days
copy
find . -name '*.tmp' -delete  # find and delete
copy
find . -type f -newer ref_file  # newer than a reference file
copy
Recursive grepLinux

search a tree, show context, filter by file type

grep -rn 'pattern' .  # recursive + line numbers
copy
grep -rn -C 3 'pattern' .  # with N lines of context
copy
grep -rn --include='*.py' 'pattern' src/  # only matching files
copy
grep -rl 'TODO' .  # just list matching files
copy
grep -rv 'pattern' file  # invert: lines NOT matching
copy
grep -c 'pattern' file  # count matches
copy
sed: replace / delete / sliceLinux

in-place edits without opening an editor

sed -i 's/old/new/g' file  # in-place, all occurrences
copy
sed -i.bak 's/old/new/g' file  # keep a .bak backup
copy
sed -n '10,20p' file  # print only lines N–M
copy
sed -i '/^#/d' file  # delete matching lines
copy
sed -i '1i first line' file  # insert at top
copy
find . -name '*.py' -exec sed -i 's/old/new/g' {} +  # replace across a whole tree
copy
awk: columns and sumsLinux

extract columns, sum, filter rows

awk '{print $1, $3}' file  # print columns 1 and 3
copy
awk -F',' '{print $2}' data.csv  # CSV: second column
copy
awk '{sum += $1} END {print sum}' nums.txt  # sum a column
copy
ps aux | awk '$3 > 50 {print $2, $11}'  # rows where CPU % > N
copy
awk 'NR % 10 == 0' file  # every Nth line
copy
awk '!seen[$0]++' file  # dedupe, keep order
copy
tar: create and extractLinux

the flags no one remembers

tar -czvf archive.tar.gz dir/  # create .tar.gz
copy
tar -xzvf archive.tar.gz  # extract .tar.gz
copy
tar -xzvf archive.tar.gz -C /target/  # extract into a directory
copy
tar -tzvf archive.tar.gz  # list contents without extracting
copy
tar -cJvf archive.tar.xz dir/  # xz: smaller, slower
copy
tar --exclude='node_modules' -czvf archive.tar.gz dir/  # skip a directory
copy
rsync: sync directoriesLinux

local ↔ remote sync; trailing slash on src matters

rsync -avh --progress src/ dest/  # local sync
copy
rsync -avz src/ user@host:/path/  # push to remote
copy
rsync -avz user@host:/path/ local/  # pull from remote
copy
rsync -avz --delete src/ dest/  # exact mirror (deletes extras)
copy
rsync -avzn src/ dest/  # -n = dry run first
copy
rsync -avz --exclude '.git' src/ dest/  # skip patterns
copy
SSH tunnels & port forwardingLinux

reach a remote-only service locally, or expose a local one

ssh -L 8080:localhost:80 user@host  # local :8080 → remote :80
copy
ssh -L 5432:db.internal:5432 user@jump  # via jump host to internal service
copy
ssh -R 9000:localhost:3000 user@host  # remote :9000 → your :3000
copy
ssh -N -f -L 8080:localhost:80 user@host  # background, no shell
copy
ssh -J user@jump user@target  # hop through a jump host
copy
ssh-copy-id user@host  # install your key = no more passwords
copy
scp: copy over SSHLinux

files and directories, both directions

scp file.txt user@host:/path/  # push a file
copy
scp user@host:/path/file.txt .  # pull a file
copy
scp -r dir/ user@host:/path/  # recursive
copy
scp -P 2222 file.txt user@host:/path/  # non-default port (capital P)
copy
Disk usage: what is eating spaceLinux

du/df combos for finding the big directories

df -h  # free space per filesystem
copy
du -h --max-depth=1 . | sort -hr  # size of each subdirectory
copy
du -sh */ | sort -hr | head -10  # top N largest dirs
copy
find . -size +500M -exec ls -lh {} \;  # individual huge files
copy
ncdu .  # interactive (if installed)
copy
Kill process on a portLinux

find and kill whatever is holding a port

lsof -i :3000  # who is on the port
copy
kill $(lsof -t -i :3000)  # kill it
copy
fuser -k 3000/tcp  # same, one command
copy
ss -tulpn | grep 3000  # alternative lookup (no lsof)
copy
Processes: find, sort, killLinux

who is eating CPU / memory, and how to stop them

ps aux --sort=-%mem | head -10  # top memory hogs
copy
ps aux --sort=-%cpu | head -10  # top CPU hogs
copy
pgrep -af python  # find PIDs by name (full cmdline)
copy
pkill -f 'train.py'  # kill everything matching
copy
kill -9 PID  # force-kill (last resort)
copy
pstree -p PID  # see its whole process tree
copy
Long jobs: nohup, bg, disownLinux

keep a job alive after you log out

nohup ./train.sh > out.log 2>&1 &  # survives logout, logs to file
copy
jobs -l  # list background jobs of this shell
copy
fg %1  # bring job back to foreground
copy
bg %1  # resume a Ctrl-Z-suspended job in background
copy
disown -h %1  # detach an already-running job from the shell
copy
tail -f out.log  # watch its output live
copy
xargs: pipe into argumentsLinux

turn stdin lines into command arguments, safely and in parallel

find . -name '*.log' | xargs rm  # delete all matches
copy
find . -name '*.log' -print0 | xargs -0 rm  # safe with spaces in names
copy
cat urls.txt | xargs -n1 curl -LO  # one arg per invocation
copy
ls *.png | xargs -I{} convert {} {}.jpg  # {} = placeholder for each item
copy
cat list.txt | xargs -P4 -n1 ./process.sh  # N parallel workers
copy
Shell history tricksLinux

stop retyping commands

sudo !!  # rerun last command with sudo
copy
!$  # last argument of previous command
copy
^old^new  # rerun previous cmd with a substitution
copy
history | grep ssh  # search history
copy
Ctrl-r  # reverse-i-search: type to fuzzy-find past commands
copy
fc  # open last command in $EDITOR, run on save
copy
Permissions: chmod / chownLinux

numeric modes decoded + recursive ownership

chmod 644 file  # rw-r--r-- (files)
copy
chmod 755 dir/  # rwxr-xr-x (dirs, executables)
copy
chmod 600 key  # rw------- (private keys)
copy
chmod +x script.sh  # make executable
copy
chown -R user:group dir/  # recursive ownership
copy
find . -type d -exec chmod 755 {} \; -o -type f -exec chmod 644 {} \;  # sane perms for a whole tree
copy
systemctl: manage servicesLinux

the daily service-management set

systemctl status nginx  # state + recent log lines
copy
sudo systemctl restart nginx
copy
sudo systemctl enable --now nginx  # enable at boot AND start
copy
systemctl list-units --failed  # what is broken
copy
systemctl list-timers  # scheduled jobs
copy
sudo systemctl daemon-reload  # after editing a unit file
copy
journalctl: read logsLinux

follow, filter by unit and time

journalctl -u nginx -f  # follow one service
copy
journalctl -u nginx --since '1 hour ago'
copy
journalctl -p err -b  # errors since boot
copy
journalctl -k  # kernel messages (dmesg equivalent)
copy
journalctl --disk-usage  # how big the journal is
copy
sudo journalctl --vacuum-size=200M  # shrink it
copy
curl: download, headers, JSONLinux

the curl invocations that cover 95% of use

curl -LO https://example.com/file.tar.gz  # download, keep filename
copy
curl -C - -LO https://example.com/big.iso  # resume a download
copy
curl -sI https://example.com  # headers only
copy
curl -s -X POST https://api.example.com/v1 -H 'Content-Type: application/json' -d '{"key": "value"}'  # JSON POST
copy
curl -s -o /dev/null -w '%{http_code}\n' https://example.com  # just the status code
copy
curl -s https://example.com --resolve example.com:443:1.2.3.4  # test against a specific IP
copy
Network debuggingLinux

is it up, is it reachable, who answers DNS

ip a  # my interfaces and IPs
copy
ss -tulpn  # listening ports + owning processes
copy
ping -c 4 host  # reachability
copy
dig +short example.com  # DNS answer only
copy
nc -zv host 5432  # is this port open?
copy
curl -s ifconfig.me  # my public IP
copy
traceroute host  # where packets die
copy
watch & cronLinux

run something repeatedly — now, or on a schedule

watch -n 1 'nvidia-smi'  # rerun every N seconds, fullscreen
copy
watch -d 'df -h'  # -d highlights what changed
copy
crontab -e  # edit your cron jobs
copy
crontab -l  # list them
copy
*/5 * * * * /path/script.sh >> /tmp/log 2>&1  # cron line: every 5 min
copy
0 3 * * 1 /path/backup.sh  # cron line: Mondays at 03:00
copy
Symlinks & file inspectionLinux

link things, then figure out what they really are

Text pipelines: sort, uniq, cutLinux

classic one-liners for logs and CSVs

sort file | uniq -c | sort -nr | head -20  # frequency table (top N)
copy
cut -d',' -f2 data.csv  # extract a CSV column
copy
wc -l file  # count lines
copy
comm -23 <(sort a.txt) <(sort b.txt)  # lines in a but not in b
copy
shuf -n 10 file  # random sample of lines
copy
paste -d',' a.txt b.txt  # join files side by side
copy
tail -n +2 data.csv  # skip the header line
copy
Quick file sharingLinux

move files between machines with zero setup

python3 -m http.server 8000  # serve current dir over HTTP
copy
python3 -m http.server 8000 --directory /path  # serve another dir
copy
tar cz dir/ | ssh user@host 'tar xz -C /dest'  # stream a dir over SSH, no temp file
copy
ssh user@host 'cat /path/file' > file  # pull one file via ssh only
copy
ffmpeg: convert, trim, gifLinux

the five ffmpeg commands worth memorizing

ffmpeg -i in.mov out.mp4  # convert container/codec
copy
ffmpeg -ss 00:01:00 -t 30 -i in.mp4 -c copy out.mp4  # trim 30s from 1:00, no re-encode
copy
ffmpeg -i in.mp4 -vn -acodec libmp3lame out.mp3  # extract audio
copy
ffmpeg -i in.mp4 -vf 'fps=12,scale=480:-1' out.gif  # video → gif
copy
ffmpeg -i in.mp4 -vf scale=1280:-2 out.mp4  # resize, keep aspect
copy
ffmpeg -framerate 10 -i frame_%04d.png out.mp4  # PNG frames → video
copy
jq: query JSONLinux

slice API responses on the command line

jq '.' file.json  # pretty-print
copy
jq -r '.items[].name' file.json  # extract a field from each element
copy
jq '.[] | select(.status == "active")' file.json  # filter objects
copy
jq 'keys' file.json  # what fields exist
copy
curl -s https://api.github.com/repos/torvalds/linux | jq '.stargazers_count'  # pipe from curl
copy
jq -r '[.a, .b] | @csv' file.json  # JSON → CSV
copy
Env vars, PATH, aliasesLinux

where commands come from and how to override them

export PATH="$HOME/bin:$PATH"  # prepend to PATH
copy
printenv | grep -i proxy  # inspect environment
copy
which -a python3  # ALL matches on PATH, in order
copy
type ls  # alias? builtin? binary?
copy
alias ll='ls -alF'  # define an alias (add to ~/.zshrc)
copy
env VAR=value cmd  # set a var for one command only
copy
Undo the last commitGit

keep the changes, or destroy them

git reset --soft HEAD~1  # undo commit, keep changes staged
copy
git reset HEAD~1  # undo commit, keep changes unstaged
copy
git reset --hard HEAD~1  # undo commit, DISCARD changes
copy
git revert HEAD  # safe on pushed commits: new inverse commit
copy
Amend the last commitGit

fix the message or add forgotten files

git commit --amend -m 'better message'  # reword
copy
git add forgotten.txt && git commit --amend --no-edit  # add file, keep message
copy
git push --force-with-lease  # required after amending a pushed commit
copy
Rebase onto mainGit

replay your branch on fresh main; escape hatches included

git fetch origin && git rebase origin/main
copy
git add -A && git rebase --continue  # after fixing conflicts
copy
git rebase --abort  # bail out, back to pre-rebase state
copy
git rebase -i HEAD~3  # interactive: squash/reword/drop
copy
git rebase --onto main old-base branch  # move branch to a new base
copy
Cherry-pick commitsGit

bring specific commits to this branch

git cherry-pick abc1234  # one commit
copy
git cherry-pick abc1234 def5678  # several
copy
git cherry-pick abc1234^..def5678  # inclusive range
copy
git cherry-pick -n abc1234  # stage only, no commit
copy
git cherry-pick --abort  # undo a conflicted pick
copy
Stash (incl. untracked)Git

shelve work-in-progress properly

git stash push -u -m 'wip: refactor'  # -u includes untracked files
copy
git stash list
copy
git stash pop  # apply latest + drop it
copy
git stash apply stash@{2}  # apply a specific one, keep it
copy
git stash show -p stash@{0}  # inspect before applying
copy
git stash branch rescue stash@{0}  # stash → new branch
copy
Bisect: find the breaking commitGit

binary search through history, manual or scripted

git bisect start
copy
git bisect bad  # current commit is broken
copy
git bisect good v1.2.0  # this one was fine
copy
git bisect run npm test  # fully automatic
copy
git bisect reset  # done, back to HEAD
copy
Recover "lost" commitsGit

reflog remembers everything for ~90 days

git reflog  # every HEAD move, newest first
copy
git reset --hard HEAD@{2}  # jump back to where you were
copy
git checkout -b rescue abc1234  # resurrect a deleted branch's commit
copy
git fsck --lost-found  # last resort: dangling objects
copy
reset vs restore: unstage / discardGit

the modern commands for the two everyday undos

git restore --staged file  # unstage (keep edits)
copy
git restore file  # discard edits (careful!)
copy
git restore --source=HEAD~2 file  # file as it was N commits ago
copy
git checkout main -- file  # grab a file from another branch
copy
Rename a branch (incl. remote)Git

local rename + fix the remote in three commands

git branch -m old-name new-name
copy
git push origin -u new-name
copy
git push origin --delete old-name
copy
Squash-merge a branchGit

land a feature as one clean commit

git checkout main && git merge --squash feature  # stage the whole branch as one diff
copy
git commit -m 'Add feature X'
copy
git reset --soft HEAD~3 && git commit -m 'one commit'  # or: squash last N in place
copy
Delete branches & pruneGit

local, remote, and stale tracking refs

git branch -d feature  # local (-D to force)
copy
git push origin --delete feature  # remote
copy
git fetch --prune  # drop stale remote-tracking refs
copy
git branch --merged main  # what is safe to delete
copy
Tags: create, push, deleteGit

annotated tags for releases

git tag -a v1.2.0 -m 'Release 1.2.0'
copy
git push origin v1.2.0  # push one tag
copy
git push origin --tags  # push all tags
copy
git tag -d v1.2.0 && git push origin --delete v1.2.0  # remove local + remote
copy
git describe --tags  # nearest tag from HEAD
copy
git log: search historyGit

find when, where, and by whom something changed

git log --oneline --graph --all  # the branch picture
copy
git log -S 'function_name' --oneline  # pickaxe: commits that add/remove this string
copy
git log -p --follow file  # full history of one file, across renames
copy
git log --author='name' --since='2 weeks ago' --oneline
copy
git log main..feature --oneline  # commits on feature not in main
copy
git shortlog -sn  # commit count per author
copy
git diff: the useful variantsGit

staged, between branches, word-level, names only

git diff --staged  # what you're about to commit
copy
git diff main...feature  # what feature adds (since fork point)
copy
git diff --word-diff  # word-level, great for prose/LaTeX
copy
git diff --name-only HEAD~3  # just the touched files
copy
git diff main -- file  # one file vs another branch
copy
git diff --stat HEAD~5  # change summary per file
copy
Worktrees: two branches at onceGit

check out another branch in a second directory — no stashing

git worktree add ../proj-hotfix hotfix-branch  # existing branch → new dir
copy
git worktree add -b new-branch ../proj-exp  # create branch + dir
copy
git worktree list
copy
git worktree remove ../proj-hotfix
copy
git worktree prune  # clean up deleted dirs
copy
Stop tracking a fileGit

committed something that belongs in .gitignore

echo '.env' >> .gitignore
copy
git rm --cached .env  # untrack, keep the local file
copy
git rm -r --cached dir/  # same for a directory
copy
git update-index --skip-worktree config.local  # keep tracked but ignore local edits
copy
git update-index --no-skip-worktree config.local  # undo that
copy
Clean untracked filesGit

ALWAYS dry-run first

git clean -nd  # dry run: what would be deleted
copy
git clean -fd  # delete untracked files + dirs
copy
git clean -fdx  # also ignored files (build artifacts!)
copy
git clean -fd -- path/  # limit to one directory
copy
Remotes & syncing a forkGit

point at the right server; keep a fork fresh

git remote -v  # what am I talking to
copy
git remote set-url origin git@github.com:user/repo.git  # switch https ↔ ssh
copy
git remote add upstream https://github.com/orig/repo.git
copy
git fetch upstream && git rebase upstream/main  # sync fork with upstream
copy
git push origin main --force-with-lease  # update the fork
copy
Blame: who wrote this lineGit

ignore whitespace and code-moves for honest answers

git blame -w -C file  # -w ignore whitespace, -C detect moves
copy
git blame -L 10,20 file  # only lines N–M
copy
git log -L 10,20:file  # full evolution of those lines
copy
git show abc1234  # inspect the commit blame points at
copy
Patches: share commits as filesGit

move changes without a shared remote

git format-patch -1 HEAD  # last N commits → .patch files
copy
git am 0001-fix.patch  # apply, preserving author + message
copy
git diff > changes.patch  # uncommitted work → patch
copy
git apply --check changes.patch  # would it apply cleanly?
copy
git apply changes.patch
copy
Fast clones for huge reposGit

shallow and partial clones

git clone --depth 1 url  # latest snapshot only
copy
git clone --filter=blob:none url  # full history, lazy file contents
copy
git clone --branch v1.2 --depth 1 url  # one tag/branch only
copy
git fetch --unshallow  # convert to a full clone later
copy
Config & aliases worth havingGit

one-time setup that pays rent daily

git config --global alias.lg 'log --oneline --graph --all'  # git lg
copy
git config --global alias.st 'status -sb'  # git st
copy
git config --global pull.rebase true  # pull = fetch + rebase
copy
git config --global rebase.autostash true  # auto-stash around rebase
copy
git config user.email 'work@email.com'  # per-repo identity (no --global)
copy
git config --list --show-origin  # where every setting comes from
copy
Sessions: start, detach, attachtmux

the core loop — jobs keep running after you disconnect

tmux new -s main  # new named session
copy
tmux new -As main  # attach if it exists, else create
copy
tmux ls  # list sessions
copy
tmux a -t main  # attach
copy
C-b d  # detach (session keeps running)
copy
tmux kill-session -t main
copy
Panes: split and navigatetmux

all prefixed with C-b (Ctrl+b)

C-b %  # split vertically (side by side)
copy
C-b "  # split horizontally (stacked)
copy
C-b <arrow>  # move between panes
copy
C-b z  # zoom pane fullscreen (toggle)
copy
C-b x  # kill pane
copy
C-b C-<arrow>  # resize pane
copy
C-b q  # show pane numbers, press one to jump
copy
Windows: tabs inside a sessiontmux

one window per task, numbered from 0

C-b c  # new window
copy
C-b ,  # rename window
copy
C-b n  # next window · C-b p = previous
copy
C-b 0  # jump to window by number
copy
C-b w  # interactive window/session picker
copy
C-b &  # kill window
copy
Copy mode: scroll & searchtmux

read output that scrolled away

C-b [  # enter copy mode (then arrows / PgUp to scroll)
copy
C-b PgUp  # enter copy mode already scrolled up
copy
q  # quit copy mode
copy
tmux set -g mode-keys vi  # vi keys in copy mode (add to ~/.tmux.conf)
copy
tmux set -g history-limit 50000  # bigger scrollback
copy
Scripting tmuxtmux

launch and control sessions from shell scripts

tmux new -d -s train 'python train.py'  # run a command in a detached session
copy
tmux send-keys -t train 'ls' Enter  # type into a session remotely
copy
tmux capture-pane -t train -p | tail -20  # read its output
copy
tmux source ~/.tmux.conf  # reload config
copy
tmux kill-server  # nuke everything
copy
docker run: the flags that matterDocker

interactive, detached, ports, volumes, GPUs

docker run -it --rm ubuntu bash  # throwaway interactive shell
copy
docker run -d -p 8080:80 --name web nginx  # detached, port mapped
copy
docker run -it --rm -v "$PWD":/app -w /app python:3.12 bash  # mount current dir
copy
docker run --gpus all -it --rm pytorch/pytorch python  # with NVIDIA GPUs
copy
docker run --rm -e VAR=value img  # pass env vars
copy
Inspect running containersDocker

logs, shells, resource usage

docker ps -a  # all containers, incl. stopped
copy
docker logs -f --tail 100 name  # follow logs
copy
docker exec -it name bash  # shell into a running container
copy
docker stats  # live CPU/mem per container
copy
docker inspect name | jq '.[0].NetworkSettings.IPAddress'  # dig out one field
copy
docker top name  # processes inside
copy
Images: build, tag, pushDocker

the build-and-ship cycle

docker build -t user/app:v1 .
copy
docker build --no-cache -t user/app:v1 .  # force clean rebuild
copy
docker images  # what do I have
copy
docker tag user/app:v1 user/app:latest
copy
docker push user/app:v1
copy
docker history user/app:v1  # layer sizes — find the bloat
copy
Cleanup: reclaim diskDocker

docker eats disks; prune regularly

docker system df  # what is using space
copy
docker system prune -f  # stopped containers, dangling images, cache
copy
docker system prune -af --volumes  # EVERYTHING unused (aggressive)
copy
docker rm $(docker ps -aq)  # remove all stopped containers
copy
docker builder prune -f  # just the build cache
copy
docker compose basicsDocker

multi-container dev environments

docker compose up -d  # start stack in background
copy
docker compose up -d --build  # rebuild images first
copy
docker compose logs -f service
copy
docker compose exec service bash
copy
docker compose down  # stop + remove containers
copy
docker compose down -v  # also delete volumes (data!)
copy
Copy files & move imagesDocker

in/out of containers; between machines without a registry

docker cp name:/path/file .  # container → host
copy
docker cp file name:/path/  # host → container
copy
docker save img:tag | gzip > img.tar.gz  # image → file
copy
docker load < img.tar.gz  # file → image
copy
docker commit name img:snapshot  # running container → image
copy
Dockerfile: Python serviceDocker

small, cache-friendly starting point

FROM python:3.12-slim
WORKDIR /app
# deps first: this layer caches until requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "main.py"]
copy
venv: create & activatePython env

stdlib virtual environments

python3 -m venv .venv
copy
source .venv/bin/activate  # deactivate with: deactivate
copy
python -m pip install --upgrade pip
copy
python3 -m venv --system-site-packages .venv  # see system packages too
copy
pip: install & pinPython env

requirements files and editable installs

pip install -r requirements.txt
copy
pip freeze > requirements.txt  # pin exactly what is installed
copy
pip install -e .  # editable install of the current project
copy
pip install 'package==1.2.*'  # version constraint
copy
pip list --outdated
copy
pip show package  # version, deps, install location
copy
pip cache purge  # reclaim disk
copy
conda: environmentsPython env

create, export, recreate

conda create -n env python=3.11 -y
copy
conda activate env  # conda deactivate to leave
copy
conda env list
copy
conda env export --no-builds > environment.yml  # portable export
copy
conda env create -f environment.yml
copy
conda remove -n env --all -y  # delete an environment
copy
uv: fast pip/venv replacementPython env

drop-in, 10–100× faster resolver

uv venv  # create .venv
copy
uv pip install -r requirements.txt  # same flags as pip
copy
uv pip compile requirements.in -o requirements.txt  # lock loose deps
copy
uv run script.py  # run inside the project env
copy
uvx ruff check .  # run a tool without installing it
copy
Jupyter kernels & remote usePython env

make envs visible to Jupyter; run it on a server

pip install ipykernel && python -m ipykernel install --user --name env  # register this env as a kernel
copy
jupyter kernelspec list
copy
jupyter kernelspec uninstall env  # remove a stale kernel
copy
jupyter lab --no-browser --port 8888  # on the server
copy
ssh -N -L 8888:localhost:8888 user@host  # then tunnel from your laptop
copy
jupyter nbconvert --to script nb.ipynb  # notebook → .py
copy
Debug & profilePython env

stdlib only — no installs needed

breakpoint()  # drop into pdb at this line (in code)
copy
python -m pdb script.py  # debug from the start
copy
python -m pdb -c continue script.py  # run until it crashes, then inspect
copy
python -m cProfile -s cumtime script.py | head -30  # where does time go
copy
python -m timeit -s 'import mod' 'mod.f()'  # micro-benchmark
copy
python -X importtime -c 'import package' 2>&1 | tail  # slow-import hunt
copy
PyTorch training-loop skeletonML

the canonical loop: train step, eval step, no surprises

model.train()
for x, y in train_loader:
    x, y = x.to(device), y.to(device)
    optimizer.zero_grad()
    loss = criterion(model(x), y)
    loss.backward()
    optimizer.step()

model.eval()
with torch.no_grad():
    for x, y in val_loader:
        preds = model(x.to(device)).argmax(dim=1)
copy
Device + mixed precision (AMP)ML

modern torch.amp autocast + GradScaler

device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = model.to(device)

scaler = torch.amp.GradScaler('cuda')
with torch.amp.autocast('cuda'):
    loss = criterion(model(x), y)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
copy
Custom Dataset + DataLoaderML

the three methods, then a loader with workers

class MyDataset(torch.utils.data.Dataset):
    def __init__(self, items):
        self.items = items
    def __len__(self):
        return len(self.items)
    def __getitem__(self, idx):
        x, y = self.items[idx]
        return torch.tensor(x), torch.tensor(y)

loader = torch.utils.data.DataLoader(
    MyDataset(data), batch_size=64, shuffle=True,
    num_workers=4, pin_memory=True)
copy
Save / load a checkpointML

model + optimizer + epoch, the resumable way

torch.save({
    'epoch': epoch,
    'model': model.state_dict(),
    'optimizer': optimizer.state_dict(),
}, 'ckpt.pt')

ckpt = torch.load('ckpt.pt', map_location=device)
model.load_state_dict(ckpt['model'])
optimizer.load_state_dict(ckpt['optimizer'])
start_epoch = ckpt['epoch'] + 1
copy
Freeze layers / fine-tune the headML

requires_grad off for the backbone, train only the head

for p in model.parameters():
    p.requires_grad = False
for p in model.fc.parameters():        # unfreeze the head
    p.requires_grad = True

optimizer = torch.optim.AdamW(
    (p for p in model.parameters() if p.requires_grad), lr=1e-4)
copy
Count model parametersML

total vs trainable, in one line each

total = sum(p.numel() for p in model.parameters())
copy
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
copy
print(f'{total:,} total | {trainable:,} trainable')
copy
LR schedulersML

the ones you actually reach for; call .step() per epoch

sched = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
sched = torch.optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)
sched = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=5)

for epoch in range(epochs):
    train_one_epoch()
    sched.step()          # ReduceLROnPlateau: sched.step(val_loss)
copy
Seed everything (reproducibility)ML

python, numpy, torch, cuda + determinism flags

import random, numpy as np, torch

def seed_everything(seed=42):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
copy
Tensor reshaping cheatsML

view vs permute vs einsum — and when view fails

x.view(B, -1)  # flatten (needs contiguous memory)
copy
x.reshape(B, -1)  # like view, copies if it must
copy
x.permute(0, 2, 1)  # swap dims (BLC → BCL); then .contiguous()
copy
x.unsqueeze(1)  # add dim: (B, D) → (B, 1, D)
copy
x.squeeze(-1)  # drop size-1 dim
copy
torch.einsum('bld,bmd->blm', q, k)  # batched attention scores
copy
x.flatten(start_dim=1)  # flatten all but batch
copy
pandas / numpy one-linersML

the daily data-wrangling set

df['col'].value_counts(normalize=True)  # class balance
copy
df.groupby('key').agg(mean_x=('x', 'mean'), n=('x', 'size'))
copy
df[df['x'].between(0, 10)]
copy
df.merge(other, on='id', how='left')
copy
df.isna().mean().sort_values(ascending=False)  # missing-value fractions
copy
np.where(arr > 0, 1, -1)
copy
np.percentile(arr, [5, 50, 95])
copy
pd.set_option('display.max_columns', None)  # stop truncating columns
copy
GPU: monitor & free memoryML

nvidia-smi + torch memory tools

watch -n 1 nvidia-smi  # live GPU usage
copy
nvidia-smi --query-gpu=memory.used,memory.total,utilization.gpu --format=csv  # script-friendly
copy
CUDA_VISIBLE_DEVICES=0 python train.py  # pin to one GPU
copy
print(torch.cuda.memory_allocated() / 1e9, 'GB')  # tensors currently held
copy
torch.cuda.empty_cache()  # release cached blocks to the driver
copy
print(torch.cuda.memory_summary())  # full allocator report (OOM debugging)
copy
Gradient clipping + accumulationML

train with a big effective batch on a small GPU

accum = 4                                # effective batch = 4 × loader batch
optimizer.zero_grad()
for i, (x, y) in enumerate(train_loader):
    loss = criterion(model(x), y) / accum
    loss.backward()
    if (i + 1) % accum == 0:
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimizer.step()
        optimizer.zero_grad()
copy
Early stoppingML

patience counter — no library needed

best, patience, bad_epochs = float('inf'), 10, 0
for epoch in range(max_epochs):
    val_loss = validate(model)
    if val_loss < best - 1e-4:
        best, bad_epochs = val_loss, 0
        torch.save(model.state_dict(), 'best.pt')
    else:
        bad_epochs += 1
        if bad_epochs >= patience:
            print(f'stopping at epoch {epoch}')
            break
model.load_state_dict(torch.load('best.pt'))
copy
HuggingFace: load & run a modelML

pipeline for quick use, Auto* classes for control

from transformers import pipeline
pipe = pipeline('text-generation', model='Qwen/Qwen2.5-0.5B-Instruct')
print(pipe('Hello', max_new_tokens=50)[0]['generated_text'])

# manual control:
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(
    name, torch_dtype='auto', device_map='auto')
out = model.generate(**tok(prompt, return_tensors='pt').to(model.device),
                     max_new_tokens=100)
print(tok.decode(out[0], skip_special_tokens=True))
copy
Matplotlib: paper-quality figureML

vector PDF, right size for a column, readable fonts

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 9, 'pdf.fonttype': 42})  # 42 = editable text

fig, axes = plt.subplots(1, 2, figsize=(6.8, 2.4))  # ~2-column width
for ax, (xs, ys, label) in zip(axes, runs):
    ax.plot(xs, ys, label=label)
    ax.set_xlabel('Epoch'); ax.grid(alpha=0.3)
axes[0].set_ylabel('Loss'); axes[0].legend(frameon=False)
fig.tight_layout()
fig.savefig('fig/loss.pdf', bbox_inches='tight')  # PDF, not PNG
copy
sklearn: split, fit, reportML

the 30-second baseline before anything fancy

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix

Xtr, Xte, ytr, yte = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
clf = RandomForestClassifier(n_estimators=300, n_jobs=-1).fit(Xtr, ytr)
print(classification_report(yte, clf.predict(Xte)))
print(confusion_matrix(yte, clf.predict(Xte)))
copy
Time GPU code correctlyML

CUDA is async — time.time() lies without a sync

start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)

start.record()
out = model(x)
end.record()
torch.cuda.synchronize()
print(f'{start.elapsed_time(end):.2f} ms')

# one-line speedup while you're here (PyTorch 2.x):
model = torch.compile(model)
copy
Multi-GPU: torchrun + DDPML

minimal DistributedDataParallel setup

# launch:  torchrun --nproc_per_node=4 train.py
import torch.distributed as dist
dist.init_process_group('nccl')
rank = dist.get_rank()
torch.cuda.set_device(rank)

model = torch.nn.parallel.DistributedDataParallel(
    model.cuda(rank), device_ids=[rank])
sampler = torch.utils.data.DistributedSampler(dataset)
loader = torch.utils.data.DataLoader(dataset, sampler=sampler, batch_size=64)

for epoch in range(epochs):
    sampler.set_epoch(epoch)   # reshuffle per epoch
    ...
dist.destroy_process_group()
copy
Experiment logging (TB / wandb)ML

minimal metric logging, both flavors

# TensorBoard (stdlib-adjacent):
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('runs/exp1')
writer.add_scalar('loss/train', loss.item(), step)
# view:  tensorboard --logdir runs

# wandb:
import wandb
wandb.init(project='myproj', config={'lr': 1e-4})
wandb.log({'loss': loss.item(), 'epoch': epoch})
copy
Table (booktabs)LaTeX

the clean three-rule table every paper uses

% \usepackage{booktabs}
\begin{table}[t]
  \centering
  \caption{Results on the benchmark.}
  \label{tab:results}
  \begin{tabular}{lcc}
    \toprule
    Method & Accuracy & F1 \\
    \midrule
    Baseline & 84.2 & 0.81 \\
    \textbf{Ours} & \textbf{91.7} & \textbf{0.90} \\
    \bottomrule
  \end{tabular}
\end{table}
copy
Algorithm blockLaTeX

algpseudocode: the standard pseudo-code environment

% \usepackage{algorithm} \usepackage{algpseudocode}
\begin{algorithm}[t]
  \caption{Assertion refinement}\label{alg:refine}
  \begin{algorithmic}[1]
    \Require design $D$, spec $S$
    \State $A \gets \Call{Generate}{D, S}$
    \While{$\lnot$ \Call{Verified}{$A, D$}}
      \State $A \gets \Call{Refine}{A, \text{counterexample}}$
    \EndWhile
    \State \Return $A$
  \end{algorithmic}
\end{algorithm}
copy
Figure + subfiguresLaTeX

single figure and side-by-side subfigures

% \usepackage{graphicx} \usepackage{subcaption}
\begin{figure}[t]
  \centering
  \begin{subfigure}{0.48\linewidth}
    \includegraphics[width=\linewidth]{fig/a.pdf}
    \caption{Before}
  \end{subfigure}
  \hfill
  \begin{subfigure}{0.48\linewidth}
    \includegraphics[width=\linewidth]{fig/b.pdf}
    \caption{After}
  \end{subfigure}
  \caption{Overall comparison.}\label{fig:comparison}
\end{figure}
copy
Aligned equationsLaTeX

align at =, number one line, reference it

\begin{align}
  \mathcal{L}(\theta) &= \mathbb{E}_{x \sim p}\left[ \log f_\theta(x) \right] \label{eq:loss} \\
  \hat{\theta} &= \arg\max_\theta \mathcal{L}(\theta) \nonumber
\end{align}
% inline: as shown in Eq.~\eqref{eq:loss}
copy
Piecewise (cases)LaTeX

piecewise definitions with the cases environment

f(x) =
\begin{cases}
  1      & \text{if } x \geq 0 \\
  -1     & \text{otherwise}
\end{cases}
copy
MatricesLaTeX

pmatrix (parens), bmatrix (brackets), with dots

A =
\begin{bmatrix}
  a_{11} & \cdots & a_{1n} \\
  \vdots & \ddots & \vdots \\
  a_{m1} & \cdots & a_{mn}
\end{bmatrix},
\quad
v = \begin{pmatrix} x \\ y \end{pmatrix}
copy
Theorem environmentsLaTeX

amsthm setup + theorem/lemma/proof

% preamble:
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}
\newtheorem{lemma}[theorem]{Lemma}

\begin{theorem}\label{thm:main}
  Every reachable state satisfies $\varphi$.
\end{theorem}
\begin{proof}
  By induction on the trace length. \qedhere
\end{proof}
copy
BibTeX entry skeletonsLaTeX

the two entry types papers need + citing

@inproceedings{paul2025lisa,
  author    = {Paul, Subhajit and Banerjee, Ansuman},
  title     = {Title of the Paper},
  booktitle = {Proc.\ of CONF},
  year      = {2025}
}
@article{key2024,
  author  = {Last, First},
  title   = {Article Title},
  journal = {Journal Name},
  year    = {2024}
}
% in text: \cite{paul2025lisa}   % with natbib: \citep{} \citet{}
copy
Beamer frame skeletonLaTeX

a slide with columns and pause-based reveals

\begin{frame}{Frame title}
  \begin{columns}
    \begin{column}{0.5\textwidth}
      \begin{itemize}
        \item First point \pause
        \item Second point
      \end{itemize}
    \end{column}
    \begin{column}{0.5\textwidth}
      \includegraphics[width=\linewidth]{fig/plot.pdf}
    \end{column}
  \end{columns}
\end{frame}
copy
Minimal TikZ diagramLaTeX

two nodes and an arrow — the seed of every figure

% \usepackage{tikz}
\begin{tikzpicture}[node distance=2.5cm, every node/.style={draw, rounded corners}]
  \node (a) {LLM Agent};
  \node (b) [right of=a] {Verifier};
  \draw[->] (a) -- node[above, draw=none] {\small SVA} (b);
  \draw[->] (b) to[bend left] node[below, draw=none] {\small CEX} (a);
\end{tikzpicture}
copy
Quick compile loopLaTeX

latexmk: auto-recompile on save, correct bib passes

latexmk -pdf main.tex  # compile with the right number of passes
copy
latexmk -pdf -pvc main.tex  # watch mode: recompile on every save
copy
latexmk -c  # clean aux files (keep pdf)
copy
latexmk -pdf -interaction=nonstopmode -halt-on-error main.tex  # CI-friendly
copy
texcount -inc main.tex  # word count
copy
Math symbols cheatLaTeX

the notation every ML/verification paper needs

\mathbb{R} \; \mathbb{E} \; \mathcal{L} \; \mathcal{D}  # reals, expectation, loss, dataset
copy
\mathbf{x} \; \boldsymbol{\theta}  # bold vectors / bold greek
copy
\hat{y} \; \tilde{x} \; \bar{x} \; \dot{x}  # hat, tilde, bar, dot
copy
\operatorname*{arg\,max}_{\theta} \; f(\theta)  # argmax with subscript below
copy
\lVert x \rVert_2 \quad \lvert x \rvert  # norm and absolute value
copy
\mathbb{E}_{x \sim p}\left[ f(x) \right]  # expectation with distribution
copy
x \sim \mathcal{N}(\mu, \sigma^2)  # sampled from a Gaussian
copy
\forall \; \exists \; \implies \; \iff \; \land \; \lor \; \lnot  # logic (verification papers)
copy
References & cleverefLaTeX

stop typing "Figure~\ref{...}" by hand

\usepackage[capitalize]{cleveref}  # load LAST in the preamble
copy
\cref{fig:arch}  # → "Fig. 1", type-aware
copy
\cref{eq:loss,eq:reg}  # → "Eqs. (2) and (3)"
copy
Fig.~\ref{fig:arch}  # manual: ~ = non-breaking space
copy
\eqref{eq:loss}  # equation with parens: (2)
copy
\label{sec:method}  # label AFTER \section{...}
copy
Spacing & page squeezingLaTeX

legal(ish) tricks for the page limit

\vspace{-2mm}  # shave space around figures/sections
copy
\quad \; \, \!  # math spaces: big, medium, thin, negative
copy
\setlength{\textfloatsep}{6pt}  # gap between floats and text
copy
\begin{itemize}[noitemsep,topsep=2pt]  # tight lists (enumitem)
copy
\resizebox{\linewidth}{!}{...}  # shrink an overflowing table
copy
\small  # inside table/algorithm envs before content
copy
Table tricks: multirow, multicolLaTeX

cells spanning rows/columns

\multicolumn{2}{c}{Header}  # cell spanning 2 columns
copy
\multirow{2}{*}{Method}  # cell spanning 2 rows (\usepackage{multirow})
copy
\cmidrule(lr){2-3}  # partial rule under cols 2–3 (booktabs)
copy
p{3cm}  # fixed-width wrapping column in tabular spec
copy
\begin{tabular}{@{}lcc@{}}  # @{} trims outer padding
copy
IEEE conference skeletonLaTeX

IEEEtran: the start of every submission

\documentclass[conference]{IEEEtran}
\usepackage{graphicx,booktabs,amsmath,amssymb}
\usepackage[capitalize]{cleveref}

\title{Paper Title}
\author{\IEEEauthorblockN{Subhajit Paul}
\IEEEauthorblockA{Indian Statistical Institute, Kolkata \\
paul@isical.ac.in}}

\begin{document}
\maketitle
\begin{abstract}...\end{abstract}
\section{Introduction}
\bibliographystyle{IEEEtran}
\bibliography{refs}
\end{document}
copy
Buy Me A Coffee Icon