Snippet Library

Curated production reference snippets and your personal local code vault.

GitCurated
bash

Undo Last Commit (Keep Changes)

Rewind HEAD by 1 commit while preserving all modified files as staged changes in your working tree.

bash5 lines
# Undo commit, keep changes staged
git reset --soft HEAD~1

# Or undo commit and leave changes unstaged:
git reset HEAD~1
GitCurated
bash

Interactive Rebase Last N Commits

Squash, reword, reorder, or drop intermediate commits before merging your branch.

bash7 lines
# Open interactive rebase editor for last 3 commits
git rebase -i HEAD~3

# In the editor:
# p, pick = use commit
# s, squash = meld into previous commit
# r, reword = edit commit message
JavaScriptCurated
typescript

TypeScript Generic Debounce

Delays function execution until a specified delay has elapsed since the last invocation.

typescript10 lines
function debounce<T extends (...args: any[]) => void>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timer: ReturnType<typeof setTimeout>;
  return (...args: Parameters<T>) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}
JavaScriptCurated
typescript

Deep Object Clone with Fallback

Safely creates a deep copy of complex nested objects using structuredClone with JSON fallback.

typescript6 lines
export const deepClone = <T>(obj: T): T => {
  if (typeof structuredClone === "function") {
    return structuredClone(obj);
  }
  return JSON.parse(JSON.stringify(obj));
};
PythonCurated
python

Execution Timer Context Manager

Measure exact execution time of any code block using Python's contextlib and time.perf_counter.

python15 lines
import time
from contextlib import contextmanager

@contextmanager
def execution_timer(label: str = "Task"):
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = (time.perf_counter() - start) * 1000
        print(f"⏱️ [{label}] completed in: {elapsed:.2f} ms")

# Usage:
# with execution_timer("Data Processing"):
#     process_large_dataset()
PythonCurated
python

Retry with Exponential Backoff

Robust decorator for resilient network or database operations with configurable retry intervals.

python19 lines
import time
from functools import wraps

def retry_backoff(max_retries: int = 3, base_delay: float = 1.0):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            delay = base_delay
            for attempt in range(max_retries):
                try:
                    return func(*args, **kwargs)
                except Exception as err:
                    if attempt == max_retries - 1:
                        raise err
                    print(f"Attempt {attempt + 1} failed: {err}. Retrying in {delay}s...")
                    time.sleep(delay)
                    delay *= 2
        return wrapper
    return decorator
RegexCurated
regex

Standard Email Address Validator (RFC 5322 / W3C Subset)

Validates standard user email addresses with domains and top-level domains matching the W3C/HTML5 specification subset of RFC 5322.

regex1 line
^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$
RegexCurated
regex

Semantic Versioning (SemVer 2.0)

Official SemVer 2.0 specification regex matching Major, Minor, Patch, Pre-release, and Build metadata identifiers.

regex1 line
^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$
DockerCurated
bash

Clean Dangling System Resources

Reclaim host disk space by purging stopped containers, dangling images, build caches, and unused volumes.

bash5 lines
# Clean stopped containers, dangling images, and default networks
docker system prune -f

# Thorough cleanup including all unused images and unused volumes:
docker system prune -a --volumes -f
DockerCurated
dockerfile

Multi-Stage Dockerfile (Compiled TypeScript / Node.js API)

Production multi-stage build tailored for compiled Node.js backend services (TypeScript/Express/Fastify) targeting dist/index.js, with non-root security and pruned dependencies.

dockerfile45 lines
# ==============================================================================
# Multi-Stage Production Dockerfile for Compiled Node.js / TypeScript Services
#
# Clarified Architecture & Explicit Assumptions:
# 1. Target: Compiled backend API service (Express, Fastify, NestJS, TypeScript).
#    (NOTE: For Next.js App Router, use Next.js official "output: standalone" Dockerfile).
# 2. Build Pipeline: "npm run build" compiling TypeScript into "./dist".
# 3. Entrypoint: "node dist/index.js" (adjust if using dist/main.js or server.js).
# 4. Reproducibility: Requires package.json & package-lock.json for "npm ci".
# 5. Build Context: Requires a .dockerignore excluding "node_modules", "dist", and ".git".
# 6. Networking & Security: Defaults to port 3000, runs as non-root user (appuser).
# ==============================================================================
FROM node:20-alpine AS builder
WORKDIR /app

# Install dependencies (requires package.json & package-lock.json)
COPY package*.json ./
RUN npm ci

# Copy source and compile to ./dist (ensure .dockerignore excludes host node_modules)
COPY . .
RUN npm run build

# Prune devDependencies to keep production image lightweight
RUN npm prune --production

# Production Runner Stage
FROM node:20-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production

# Security: Run as dedicated non-root user (alpine)
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Copy pruned production dependencies and build artifacts
COPY --from=builder --chown=appuser:appgroup /app/package*.json ./
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist

USER appuser
EXPOSE 3000

# Entrypoint assumes compiled index at dist/index.js (adjust if using dist/main.js or server.js)
CMD ["node", "dist/index.js"]
SQLCurated
sql

Running Total & 7-Day Moving Average

Standard ANSI SQL window functions to calculate cumulative revenue and rolling weekly trends.

sql12 lines
SELECT 
    order_date,
    daily_sales,
    SUM(daily_sales) OVER (
        ORDER BY order_date 
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_total,
    AVG(daily_sales) OVER (
        ORDER BY order_date 
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS rolling_7d_average
FROM revenue_ledger;
SQLCurated
sql

Recursive CTE for Hierarchical Trees

Traverse self-referencing employee managers or nested category hierarchies using recursive CTEs.

sql14 lines
WITH RECURSIVE CategoryTree AS (
    -- Anchor: root categories (no parent)
    SELECT id, name, parent_id, 1 AS depth
    FROM categories
    WHERE parent_id IS NULL

    UNION ALL

    -- Recursive step: subcategories
    SELECT c.id, c.name, c.parent_id, ct.depth + 1
    FROM categories c
    INNER JOIN CategoryTree ct ON c.parent_id = ct.id
)
SELECT * FROM CategoryTree ORDER BY depth, name;