admin
@admin ADMIN
Member since Apr 2026
770
Public snippets
5
Net score
5
Total upvotes

Showing 151–180 of 770 public snippets

Go
Error Wrapping with %w
`fmt.Errorf` with `%w` wraps an inner error inside an outer one, preserving the chain. Callers can use `errors.Is` / `errors.As` to inspect any level of the chain.
1h ago 0
Go
UUID Generation (google/uuid)
`github.com/google/uuid` is the standard UUID library. v4 (random) for IDs, v7 (time-ordered) when you want UUIDs that sort chronologically and play nicely with B-tree indexes.
1h ago 0
PHP
Compound Interest Calculator
Compute the future value of an investment compounded n times per year for t years. Returns both the final value and the interest earned.
1h ago 0
SQL
INSERT … SELECT — Bulk Copy
Copy/transform rows from a SELECT into another table — the cheapest way to move data within the database. Skip column lists at your peril; positional matching is fragile.
1h ago 0
JavaScript
Calculate Reading Time
Estimates the reading time of a block of text based on an average adult reading speed (default 200 words per minute). Strips HTML tags before counting to handle rich-text content. Returns the result in minutes, rounded up, so a short article always shows at least "1 min read".
1h ago 0
Go
Sentinel Errors (var ErrFoo = errors.New)
Sentinel errors are package-level singletons you can compare against with `errors.Is`. Use sparingly — they're part of your package's API surface and changing them is a breaking change.
1h ago 0
Go
Static File Server
`http.FileServer` serves a directory; combine with `http.StripPrefix` to mount it at a URL path. One line for the most common static-asset use case.
1h ago 0
Go
JSON Marshal / Unmarshal
`encoding/json` is the standard library JSON parser. `Marshal` produces compact JSON; `MarshalIndent` produces pretty-printed. `Unmarshal` decodes into a typed value (struct, map, or any).
1h ago 0
Java
Generic Method + Bounded Type Parameters
A method can have its own type parameter independent of the class. `<T extends Comparable<T>>` constrains T to types that can be compared.
1h ago 0
PHP
Smart Title Case
Convert a string to title case while keeping common short words (a, an, the, of, etc.) lowercase — unless they appear at the start or end of the title.
1h ago 0
PHP
Rotating Log Writer
Append to a single log file but auto-rotate to .1/.2/.3 once the file exceeds a configurable size. No external dependencies — just rename + size check.
1h ago 0
PHP
Tail Last N Lines of File
Efficiently read the last N lines of a (possibly large) file by seeking to the end and walking backwards in fixed-size chunks. Avoids loading the entire file into memory.
1h ago 0
TypeScript
Retry with Exponential Backoff + Jitter
Retry an async operation up to N times, doubling the delay each attempt with random jitter to avoid thundering herd. Decide retryability via an optional predicate so 4xx errors stop immediately.
1h ago 0
Go
HTTP POST JSON Body
Build a request with `http.NewRequestWithContext`, set headers, send via your client. The context plumbing is what lets callers cancel mid-request.
1h ago 0
Bash
Pretty-Print Last Exit Code
A tiny prompt-trick that shows the previous command's exit code in red when it failed. Stops you from missing silent errors in long terminal sessions.
1h ago 0
Java
Stream.reduce — Aggregate to a Single Value
`reduce` collapses a stream to one value: sum, product, max, min, custom accumulation. Two-arg form needs an identity (zero/seed); three-arg form supports parallel streams via a combiner.
1h ago 0
Go
net/url — Build Query Strings Safely
Stop concatenating `?a=1&b=2` by hand. `url.Values` (a `map[string][]string`) escapes correctly, handles repeated keys, and `url.URL.String()` renders the canonical form.
1h ago 0
Rust
Read a File — Whole / Lines / Bytes
Three common patterns: load it all into memory, iterate line-by-line, or stream bytes. Pick by file size — `read_to_string` is convenient but bad for huge files.
1h ago 0
Bash
DNS Lookup (dig / host / getent)
Three options depending on what's installed: dig is most flexible, host is concise, getent uses the system's resolver and respects /etc/hosts.
1h ago 0
Kotlin
Nullable Types — String? and the ? Operator
Kotlin distinguishes `String` (never null) from `String?` (may be null) in the type system. The compiler refuses to compile code that could deref a possibly-null value — the famous "no more NullPointerException" feature.
1h ago 0
SQL
Recursive CTE — Walk a Hierarchy
`WITH RECURSIVE` lets a CTE refer to itself. The standard way to walk parent/child trees (org charts, comment threads, category nestings) in a single query.
1h ago 0
Go
iter.Seq — Range-Over-Func (Go 1.23+)
Go 1.23 added "range over func" — your own functions can produce values that work with `for v := range fn`. Cleaner than channels for in-process iteration without goroutine overhead.
1h ago 0
Kotlin
Safe Call Chain + Elvis Default
`?.` is the safe-call operator — short-circuits to `null` at the first null in a chain. Pair with `?:` (Elvis) for "this or a default". Replaces nested if-not-null ladders.
1h ago 0
HTML
Video Element with Captions
`<video>` with multiple `<source>` formats (MP4 + WebM), `controls`, `poster`, and a captions track via `<track kind="captions">`. All shipped with the browser — no JS player needed.
1h ago 0
Go
base64 Encode / Decode
`encoding/base64` has Standard, URL-safe, and Raw (no padding) variants. URL-safe replaces `+/` with `-_` so the output is safe in query strings and filenames.
1h ago 0
Python
Context Manager via @contextmanager
Build a custom context manager without writing a class — just a generator with one `yield`. The code before yield runs on enter, after yield runs on exit (even on exception).
1h ago 0
Rust
Async/Await with tokio
`async fn` returns a future; `.await` drives it. tokio is the de-facto runtime. The `#[tokio::main]` attribute turns `main` into the runtime entry point.
1h ago 0
SQL
Pivot Without PIVOT (Conditional Aggregation)
Most databases don't have a real `PIVOT` keyword (SQL Server does). The portable answer is conditional aggregation — `SUM(CASE WHEN ...) AS col` for each pivoted value.
1h ago 0
SQL
ROLLUP — Subtotals and Grand Totals
`GROUP BY ROLLUP` adds subtotal rows (with NULL for the rolled-up columns) plus a grand total. Drop into reports without writing UNIONs by hand.
1h ago 0
TypeScript
Environment Variable Validator
Validate process.env at boot-time and exit fast if anything's missing. The returned object is typed so the rest of the code reads `env.DATABASE_URL` instead of `process.env.DATABASE_URL!`.
1h ago 0