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

Showing 241–270 of 770 public snippets

Go
sync.Pool — Reuse Allocations
`sync.Pool` keeps a pool of reusable objects to reduce allocator pressure in hot paths. Good for byte buffers, JSON encoders, or anything you allocate frequently and only need briefly.
23m ago 0
Bash
ANSI Color Output Helpers
Wrap printf with ANSI escape codes for color and bold. Auto-disable if stdout isn't a TTY (so piping to a file doesn't pollute it with escape sequences).
23m ago 0
Kotlin
Variance — in vs out
`out T` (covariant) → producer of T; can be assigned to a wider type. `in T` (contravariant) → consumer of T; can be assigned to a narrower type. Without modifiers, generics are invariant (strict match).
23m ago 0
Kotlin
zip and zipWithIndex
`zip` pairs elements positionally; the result is the length of the shorter list. `withIndex()` gives you `(index, value)` pairs without the manual `forEachIndexed`.
23m ago 0
Rust
anyhow for Application Errors
`anyhow::Result<T>` is `Result<T, anyhow::Error>` — a type-erased error that captures any other error AND adds context via `.context()`. The app-author's pick (use thiserror for libraries).
23m ago 0
Bash
Multipart File Upload via cURL
Upload one or more files using -F. Optional extra form fields go through the same flag — quote carefully to preserve spaces.
23m ago 0
PHP
Resize Image to Max Dimension
Shrink an uploaded image so its longest side is no more than $maxDim pixels, preserving aspect ratio. Re-encodes to JPEG at the given quality. Uses the GD extension.
23m ago 0
Go
Empty Struct Sentinel (struct{})
`struct{}` is a zero-size value — no memory cost. Use it as the value type in a Set (`map[T]struct{}`), as a channel signal (`chan struct{}`), or as a marker type.
23m ago 0
Bash
Symlink Force-Update
`ln -s` fails if the target already exists. `ln -sf` is the idempotent variant — useful in deploy scripts that point a "current" symlink to a fresh release directory.
23m ago 0
Python
Slugify (unicodedata, zero deps)
Convert any string to a URL-safe slug using only stdlib. Normalizes Unicode (NFKD), strips combining marks, lowercases, replaces non-alphanumerics with a separator.
23m ago 0
SQL
MERGE — One Statement for INSERT + UPDATE + DELETE
`MERGE` (standard SQL, PostgreSQL 15+, SQL Server, Oracle) is a single statement that combines INSERT/UPDATE/DELETE driven by joining a source against a target. Heavy artillery for reconciliation jobs.
23m ago 0
Bash
Atomic File Write (write then rename)
Write to a temp file in the SAME directory, then `mv` to the final name. mv on the same filesystem is atomic — readers never see a half-written file.
23m ago 0
Go
Worker Pool with Channels
Spawn N worker goroutines, feed them tasks over a jobs channel, collect results on a results channel. Idiomatic Go pattern for bounded concurrency.
23m ago 0
JavaScript
Fetch with Retry
Wraps the native fetch API with automatic retry logic using exponential backoff. Retries on network errors or non-OK HTTP responses up to a configurable number of attempts. Exponential backoff with optional jitter prevents thundering herd problems when many clients retry simultaneously.
23m ago 0
Python
unique_everseen — Order-Preserving Dedupe
Remove duplicates while preserving original order (set() loses order on collisions). Optional key function lets you dedupe by a derived value — e.g., lowercased email.
23m ago 0
Python
Protocol — Structural (Duck) Typing
Define what an object can DO, not what it IS. A class doesn't need to inherit from a Protocol — it just needs to match the shape. Like TypeScript interfaces with `implements` optional.
23m ago 0
Python
group_by — Group Items by a Key
A dict-returning groupby that doesn't require sorted input. Like itertools.groupby but materializes the groups so consumers can iterate them multiple times.
23m ago 0
JavaScript
Parse URL Query String
Parses a URL query string into a plain key-value object. Uses the built-in URLSearchParams API — no regex required. Handles duplicate keys (returns the first value), percent-encoded characters, and works with both full URLs and raw query strings. Pairs nicely with buildQueryString.
24m 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.
24m ago 0
Kotlin
Sorting Collections
`sortedBy { ... }` returns a sorted copy. `sortedWith(compareBy { ... })` chains tie-breakers cleanly. Avoid `sortBy` (in-place) on read-only lists.
24m ago 0
Rust
impl Trait — Static Dispatch Returns
When you want to return a complex iterator chain or closure, you don't need to spell out the type. `impl Trait` lets the compiler infer the concrete type while exposing only the API contract.
24m ago 0
JavaScript
Rate Limiter (Token Bucket)
Implements a token-bucket rate limiter that allows a burst of calls up to a maximum capacity, then replenishes tokens at a steady rate. Useful for throttling outbound API requests, user-facing actions, or any operation where you need to allow occasional bursts without exceeding a sustained rate.
24m ago 0
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.
24m ago 0
Kotlin
Compose Modifier Chain
`Modifier` is how you customize composables — padding, click handlers, background, size, alignment. Order matters: each modifier wraps the previous one.
24m 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.
24m ago 0
JavaScript
Range Generator
Generates an array of numbers from start to end (inclusive) with an optional step. Supports negative steps for counting down. Covers the most common use case of Array.from({ length: n }, (_, i) => i) with a much cleaner API, and handles arbitrary start/end/step combinations.
24m ago 0
Bash
Generate a Random Password
Three approaches: pwgen (purpose-built), openssl (universally available), /dev/urandom + tr (zero deps). Pick by what's installed.
24m ago 0
PHP
Stream Large CSV with Generator
Iterate over a CSV file row-by-row without ever loading the whole file into memory. Uses a generator so consumers can foreach naturally and PHP cleans up the file handle.
24m ago 0
Java
JUnit 5 — Parameterized Tests
`@ParameterizedTest` runs the same test with multiple inputs. Use `@CsvSource`, `@MethodSource`, or `@EnumSource` for data. Eliminates copy-paste in test classes.
24m ago 0
Java
BufferedReader / BufferedWriter
For large files or line-oriented protocols, wrap a Reader/Writer in `Buffered*`. Reduces per-call overhead from many small reads to fewer large ones. Always close with try-with-resources.
24m ago 0