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

Showing 31–60 of 770 public snippets

Kotlin
java.time — When You Need JVM Interop
On the JVM, `java.time` is fine — and often necessary for interop with Java APIs. Kotlin's extension methods make it ergonomic enough that you might never reach for kotlinx-datetime.
just now 0
Java
Jackson — Annotations (rename, ignore, etc)
Field-level annotations let you map between snake_case JSON and camelCase Java, skip nulls, never serialize secrets, set defaults on missing fields.
just now 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.
just now 0
Go
log/slog — Structured Logging
`log/slog` (Go 1.21+) is the standard structured logger. Drop-in replacement for `log` with key/value attributes and JSON output for log-pipeline ingestion.
just now 0
Go
database/sql — Transaction Helper
Wrap your transaction in a function that commits on success and rolls back on error or panic. Drop-in: pass any `func(*sql.Tx) error` and forget about manual cleanup.
just now 0
TypeScript
Sleep / Delay
The async/await-friendly version of `setTimeout`. The one-liner everyone re-invents — keep it in a util file. Optional AbortSignal lets you cancel mid-wait.
just now 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.
just now 0
Bash
Array Basics (index + iterate)
Bash 4+ arrays — declare, access by index, get all elements with [@], length with #. The quoting matters: "${arr[@]}" preserves each element; ${arr[@]} word-splits.
just now 0
Python
ThreadPoolExecutor for I/O-Bound Work
Parallelize I/O-bound tasks (HTTP requests, file reads, DB queries) without writing thread management code. The default thread count is min(32, os.cpu_count() + 4) — usually the right call.
just now 0
PHP
Simple cURL GET with Timeout
A no-dependency HTTP GET helper with sensible defaults: short timeout, follow redirects, return body as string, throw on transport error. Pass extra headers as a simple associative array.
just now 0
Go
database/sql — Open + Query
`database/sql` is driver-agnostic — pick a driver (`pgx/stdlib`, `go-sql-driver/mysql`, `mattn/sqlite3`). Always `defer db.Close()` only on app exit; the pool is meant to be long-lived.
just now 0
Kotlin
windowed and chunked
`chunked(n)` splits a list into NON-overlapping pieces of size n. `windowed(n)` slides a fixed-size window across — overlapping. Useful for moving averages, n-grams, batch APIs.
just now 0
Kotlin
JDBC with use { } — Auto-Close Connections
Plain JDBC is fine for simple cases. Wrap connections / statements / result sets in `use { }` for guaranteed cleanup even on exceptions.
just now 0
Rust
axum — Hello World HTTP Server
axum is the tokio-team's web framework — composable, type-safe handlers built on tower middleware. The hello-world is small enough to read in one screen.
just now 0
PHP
Date Range Iterator
Yield each date in a [start, end] interval as a DateTimeImmutable, with a configurable step. Builds on DatePeriod under the hood — but exposes a generator so you can break out early.
just now 0
PHP
Build & Sign a JWT (HS256)
Generate a JWT manually using only base64-url and hash_hmac — no library required. Demonstrates header/payload/signature concatenation and the exp claim.
just now 0
Java
Stream.generate / iterate — Infinite Streams
Build streams from a seed + a function. `generate(supplier)` calls the supplier each time; `iterate(seed, next)` applies a unary op. Always pair with `limit` to bound them.
just now 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.
just now 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.
just now 0
Python
Word-Safe Truncate
Cap a string at `max_len` chars without splitting a word; append an ellipsis when truncated. Backs off to the last space if cutting mid-word would happen.
just now 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.
just now 0
Java
Jackson — Basic ObjectMapper
`com.fasterxml.jackson.databind.ObjectMapper` is the JSON standard for Java. Construct once (it's expensive + thread-safe) and reuse for every serialization in your app.
just now 0
Kotlin
Path Operations with java.nio.file
Modern Kotlin code uses `java.nio.file.Path` over the legacy `File`. Operator overloads + Kotlin extensions make it ergonomic.
just now 0
JavaScript
Unique Array Values
Returns a new array with duplicate values removed. The fast version uses a Set for primitives. The deep version supports deduplicating objects by a specific key, making it suitable for deduplicating API results or merged data sets.
just now 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.
just now 0
PHP
Parse Link Header for Pagination
Parse the standard HTTP Link header (RFC 5988) into a relation → URL map. Lets you follow rel="next" pagination in APIs like GitHub without manually building URLs.
just now 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.
just now 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.
just now 0
TypeScript
Sum / Mean / Median (numeric arrays)
The descriptive-stat trio for number[]. Median sorts a copy so the input is left alone. Empty input returns 0 / 0 / 0 rather than NaN — opinionated, but predictable.
just now 0
Python
asyncio.wait_for — Timeout Wrapper
Cancel a coroutine if it takes longer than `timeout` seconds. Raises asyncio.TimeoutError when fired so the caller can fall back. Python 3.11+ has asyncio.timeout() as a context-manager alternative.
just now 0