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

Showing 481–510 of 770 public snippets

Python
Format Bytes / Duration Human-Readable
Two formatting helpers everyone re-implements: bytes → "1.5 MB", seconds → "1h 23m 45s". Base-1024 IEC units by default for bytes.
5h ago 0
JavaScript
Worker Pool (Web Workers)
Manages a pool of Web Workers for CPU-intensive tasks (image processing, crypto, parsing). Distributes tasks across available workers using a round-robin strategy and returns a Promise per task. Falls back gracefully to inline execution in environments where workers are unavailable.
5h ago 0
JavaScript
Validate URL
Validates whether a string is a well-formed URL using the native URL constructor, which matches browser parsing behaviour exactly. Optionally restricts to specific protocols (defaults to http and https). No regex maintenance required — if the browser can parse it as a URL, this returns true.
5h ago 0
JavaScript
WeakRef Object Cache
A cache backed by WeakRef and FinalizationRegistry. Stored values are held weakly — the garbage collector can reclaim them if memory pressure is high, and the registry automatically cleans up stale entries from the internal map. Ideal for caching large objects (DOM nodes, rendered images) without causing memory leaks.
5h ago 0
Java
Sealed Classes + Pattern Matching (Java 21+)
`sealed` restricts which classes can extend a type — perfect for closed hierarchies that pattern matching can switch over exhaustively. The compiler enforces that you handle every variant.
5h ago 0
Rust
HashMap with the entry() API
The `entry()` API is the idiomatic way to "insert if absent" or "update if present" in a single lookup. Avoids double-lookups that the explicit `contains_key` + `insert` dance would need.
5h ago 0
Go
Crypto-Random Bytes + Hex/Base64
`crypto/rand` is the cryptographic CSPRNG. Use it for tokens, session IDs, API keys, password salts — anywhere `math/rand` would be a security bug.
5h ago 0
SQL
UPDATE with JOIN
Update one table using values from another. Syntax varies by database — PostgreSQL uses `FROM`, MySQL puts the join in the `UPDATE` clause.
5h ago 0
Go
sync.Mutex vs sync.RWMutex
`Mutex` allows one goroutine at a time — for both reads and writes. `RWMutex` allows multiple concurrent readers OR one writer — much better when reads dominate.
5h ago 0
Go
SHA-256 Hash of File or String
`crypto/sha256` is the canonical hash. Use the streaming `Hash` interface for files — never load multi-GB content into memory just to hash it.
5h ago 0
PHP
Human-Readable File Size
Format a byte count as a human-friendly string (KB / MB / GB / TB). Defaults to base-1024 sizes; pass base 1000 for SI units.
5h ago 0
Bash
Generate SSH Keypair Non-Interactively
ssh-keygen normally prompts. Pass -N "" for empty passphrase, -f for the path, -t ed25519 for modern key type. Idempotent — skip if a key already exists.
5h ago 0
Go
select — Multiplex Channel Operations
`select` is like a switch for channels — runs whichever case is ready. Use `default` for non-blocking sends/receives; `case <-time.After(d)` for timeouts.
5h 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.
5h ago 0
Go
context.WithValue — Request-Scoped Values
Attach data to a context that flows down through your call chain — request IDs, authenticated user, trace spans. Use a private key type to avoid collisions across packages.
5h 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.
5h ago 0
PHP
Validate URL (scheme + host)
Beyond filter_var, also require the URL to have an http(s) scheme and a non-empty host. Rejects "javascript:" and other risky pseudo-schemes commonly seen in stored XSS.
5h ago 0
Go
Channels — Basics
Channels are typed pipes between goroutines. Unbuffered = synchronous handoff; buffered = up to N values queued. Close a channel to signal "no more values" — receivers see ok=false.
5h ago 0
Go
Fan-Out / Fan-In
Distribute work across N workers (fan-out), then merge their results back into one channel (fan-in). Used when you can't process items strictly in order but want to retain output as one stream.
5h ago 0
Java
Semaphore — Bounded Concurrency
Limit how many threads can enter a critical section. `acquire()` blocks until a permit is available; `release()` returns one. Use for rate limits, connection pools, or any "max N at a time" pattern.
5h ago 0
TypeScript
Concurrency Limiter (semaphore)
Run an array of async tasks but limit concurrency to N at a time — like p-limit, in 30 lines. Preserves input order in the output array.
5h ago 0
Bash
Idempotent Append to File
Add a line to a file (e.g., a config or PATH export) only if it isn't already present. Common in install/setup scripts that need to be safe to re-run.
5h ago 0
Bash
HMAC-SHA256 with openssl
Sign a payload with a shared secret for webhook verification (Stripe, GitHub, etc.). openssl reads the input from stdin or -in.
5h ago 0
Rust
CSV Read/Write with the csv Crate
`csv` + `serde` lets you read/write CSVs directly into typed structs. No manual field parsing; column order tolerant via headers.
5h ago 0
Go
Goroutine Leak Prevention
A goroutine that's blocked forever on a channel send/receive leaks — it's never garbage-collected. Always pair channels with `select { case <-ctx.Done(): return }` to give them an exit path.
5h ago 0
PHP
Find Files Modified in Last N Days
List every file under a directory that was modified within the last N days. Useful for incremental backups or detecting stale entries.
5h ago 0
PHP
Encrypt / Decrypt with libsodium
Symmetric AEAD encryption using the libsodium "secretbox" (XSalsa20-Poly1305). Built into PHP since 7.2 — no extension needed. Returns base64 ciphertext with the nonce prepended.
5h ago 0
Go
errgroup — Fan-Out with Cancellation
`golang.org/x/sync/errgroup` runs N goroutines, returns the first error, and cancels the others via a shared context. The right pattern for parallel I/O where any failure should abort the rest.
5h ago 0
PHP
Format Money with Currency
Format an amount of cents as a localized currency string using NumberFormatter from intl. Falls back to a basic sprintf if intl isn't available.
5h ago 0
Python
chunked — Split Iterable into Fixed-Size Pieces
Lazy chunker that works on any iterable, not just lists. Common building block for batch APIs — "send 50 rows per request" — without loading the source into memory.
5h ago 0