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

Showing 451–480 of 770 public snippets

Rust
Atomic File Write (tempfile + persist)
Write to a temp file in the SAME directory, then atomically `persist` (rename). The `tempfile` crate handles cleanup if you crash before persisting.
5h ago 0
Go
JSON API Endpoint
Decode an incoming JSON body into a typed struct, do work, encode a JSON response. The whole roundtrip is ~20 lines of standard library.
5h ago 0
Java
Atomic File Write (move with ATOMIC_MOVE)
Write to a temp file in the same directory, then `Files.move` with `ATOMIC_MOVE` to the target. Readers never see a half-written file — critical for config / state files.
5h ago 0
PHP
Atomic File Write
Write a file in a way that other processes never see a half-written state. Write to a temp file in the same directory, then rename — rename is atomic on POSIX filesystems.
5h ago 0
Bash
Associative Array (hash map)
Bash 4+ supports key-value associative arrays. Must `declare -A` first — Bash won't infer it. Iterate keys with !arr[@].
5h ago 0
SQL
Recursive CTE — Date Spine Generator
Generate a row per day (or month, year, hour) without a calendar table. Useful for filling gaps when a date has no events but you still want it in your output.
5h ago 0
Bash
SSH to Multiple Hosts in Parallel
Run the same command on a fleet of hosts. Three patterns: serial loop (simplest), GNU parallel (fastest), pssh (purpose-built).
5h ago 0
Rust
axum with Shared State + Extractors
Use `State` to inject shared application state (DB pool, config, etc.) into every handler. `Path` and `Json` extractors deserialize URL params and request bodies for you.
5h ago 0
JavaScript
Memoize Function
Caches the result of a pure function keyed by its serialised arguments. On repeated calls with the same inputs the cached value is returned instantly, skipping expensive computation. Supports single and multi-argument functions via JSON key serialisation.
5h ago 0
JavaScript
Format Relative Time
Returns a human-readable relative time string ("3 days ago", "in 2 hours") using the Intl.RelativeTimeFormat API. Automatically selects the most appropriate unit (seconds, minutes, hours, days, weeks, months, years) based on the elapsed time. Fully localised — pass any BCP 47 locale.
5h 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.
5h ago 0
JavaScript
Random Hex Color
Generates a random 6-digit hex colour string. Useful for seeding avatar backgrounds, chart series colours, placeholder UI elements, and testing colour-dependent components. The crypto version produces a more unpredictable result suitable for generating unique palette tokens.
5h ago 0
PHP
Hash Large File Without Loading It
Compute the SHA-256 of a multi-gigabyte file by streaming it through hash_init / hash_update_stream — no memory blow-up. Useful for backup verification or torrent-style integrity checks.
5h ago 0
Java
Functional Interfaces — Function / Predicate / Consumer / Supplier
The four core single-method interfaces in `java.util.function`. They're the parameter types for streams, Optional methods, CompletableFuture, and countless library APIs.
5h ago 0
PHP
Generate Crypto-Strong Password
Generate a strong random password with configurable length and character sets. Uses rejection sampling to keep the distribution uniform across the chosen alphabet (no biased % alphabetLen).
5h ago 0
PHP
Validate IP Address (v4 + v6)
Distinguish IPv4 from IPv6, optionally reject private/reserved/loopback ranges. Useful for hardening server-side fetchers against SSRF.
5h ago 0
PHP
CSRF Token Generate + Verify
Per-session CSRF token helpers using hash_equals for constant-time comparison. Token is regenerated on logout but persists across requests within a session.
5h ago 0
Rust
Option Combinators (no unwrap!)
`Option<T>` has a rich combinator API that lets you avoid both `unwrap()` and the verbose `match`. Chain `map`, `and_then`, `unwrap_or`, `or_else` to compose fallible operations.
5h ago 0
PHP
Memoize a Function's Result
Cache the result of an expensive pure function by its arguments. Returns a closure with the same call signature that only invokes the inner function once per unique argument set.
5h ago 0
TypeScript
Promisify a Callback Function
Convert a Node-style `(err, result)` callback API into a Promise-returning function. Type-safe via generics — the inferred Promise resolves to the original callback's result type.
5h ago 0
TypeScript
Promise with Timeout
Race a promise against a timeout — if the work takes longer than `ms`, reject with a timeout error. Cancels nothing on its own (use AbortController for that), but unblocks the caller.
5h ago 0
Go
Table-Driven Tests with t.Run
A table of test cases looped through `t.Run` gives every case its own name in the output, makes adding new cases trivial, and lets you run individual cases with `-run TestX/case_name`.
5h ago 0
Go
Pointers — When and Why
Use pointers when you want to mutate the callee's value, share a large struct without copying, or distinguish "no value" via nil. Go has no pointer arithmetic — much safer than C.
5h ago 0
Rust
Fan-Out with try_join_all
Run N async operations concurrently and collect every Result. Fails fast on the first error; `join_all` is the variant that always waits for everyone.
5h ago 0
Rust
Format Strings (println! / write!)
Rust's format macros take an inline format string with `{}` placeholders. Named arguments, alignment, precision, debug formatting — all in the format spec.
5h ago 0
PHP
HMAC Webhook Signature Verify
Verify an inbound webhook (Stripe / GitHub / etc.) is genuine using HMAC-SHA256 and a shared secret. Includes timestamp tolerance to block replay attacks.
5h ago 0
Go
Custom Error Type with Fields
Implement the `error` interface (`Error() string`) on your own type to carry structured data. Pair with `errors.As` so callers can extract the fields.
5h ago 0
Python
asyncio.gather with Errors Tolerated
`gather(*tasks)` cancels everything on the first failure — usually NOT what you want. `return_exceptions=True` lets every task finish, returning the exception in place of a result. Perfect for fan-out HTTP fetches.
5h ago 0
Rust
Async Timeout
Wrap any future in `tokio::time::timeout` to fail it if it takes too long. Returns `Err(Elapsed)` on timeout; you decide what to do next (retry, fall back, propagate).
5h ago 0
TypeScript
Throttle (leading-edge, typed)
Pair to debounce: fire on the first call, then ignore further calls for `interval` ms. Useful for rate-limiting scroll handlers or button clicks.
5h ago 0