Escape HTML Entities for Output
Escape untrusted text before inserting it into HTML so angle brackets and quotes cannot break out of the surrounding context.
Page 42 of 50
Escape untrusted text before inserting it into HTML so angle brackets and quotes cannot break out of the surrounding context.
Build a small publish and subscribe emitter that registers listeners per event name and supports one-shot subscribers and clean removal.
Run child processes with execa to get parsed stdout and stderr, shell-free argument arrays, and non-zero exit codes surfaced as typed errors.
Route async failures into Express error middleware with a wrapper, classify status codes, and mask internal details before responding.
Accept streaming multipart uploads in Fastify with per-file size limits, MIME allowlists, and disk writes that never buffer whole files.
Wire Fastify to Pino for structured request logging with redaction, request ids, sampling, and slow-request warnings under load.
Read a fetch response body as a stream with manual reader control, honoring backpressure so a slow consumer cannot balloon memory.
Fetch JSON from an endpoint, applying a per-attempt timeout and retrying transient failures while treating client errors as final.
Subscribe to Firebase auth state, read the current ID token before each API call, and let the SDK refresh expired tokens transparently.
Flatten arrays nested to an arbitrary depth into a single level, with an optional depth limit so callers can control how far the flattening goes.
Validate a submitted form object against field rules and collect every error at once, so users see all problems instead of one at a time.
Configure the got client to retry transient failures with exponential backoff, status-code allowlists, and per-attempt timeouts for safer polling.
Fetch paginated GraphQL connections with graphql-request, following cursor edges and pageInfo detection until the full dataset is drained.
Group an array of records into a map keyed by one of their fields, a building block for reports, indexes, and bucketed aggregations.
Build interactive CLI flows with Inquirer checkbox prompts, validated input, default selections, and answer-driven branching between steps.
Harden ioredis connections with retry backoff, command timeouts, and sentinel failover so cache clients survive restarts and primary swaps.
Verify tokens against a rotating JWKS endpoint with jose, pinning allowed algorithms and caching the key set with stale fallback on outages.
Sign and verify JWTs with the jose library using an ECDSA P-256 key pair, protected headers, and explicit audience and expiry validation.
Decode the payload of a JSON Web Token and verify that its expiry and not-before claims are respected, without trusting the token's signature blindly.
Compose Koa middleware functions in explicit execution order, tracing the onion model pass-through with early termination and downstream control.
Compute the minimum number of insertions, deletions, and substitutions between two strings, the basis of fuzzy matching and spell suggestions.
Tame high-frequency DOM and scroll events with Lodash debounce and throttle, including leading and trailing edge control and cancelable handles.
Implement a least-recently-used cache that evicts the oldest entry when capacity is exceeded, reusing Map insertion order to track recency.
Combine LRU eviction with TTL expiry and stale-while-revalidate semantics so hot keys stay warm, expired entries serve stale, and refreshes dedupe.
Model calendar-aware time spans with Luxon Interval and Duration, splitting ranges into months, comparing overlaps, and humanizing output.
Cache a function's result by argument key with an expiry, so expensive pure calls are reused briefly and stale values eventually recompute.
Paginate large MongoDB collections with stable cursor queries on indexed compound sort keys, avoiding skipped documents on offset paging.
Group multi-document writes into an atomic MongoDB transaction with a session, abort on validation failure, and retry on transient errors.
Generate compact, URL-safe identifiers with nanoid, sized from collision probability math instead of guesswork, with a custom alphabet option.
Hash passwords with the built-in scrypt using random per-user salts, explicit cost parameters, and timing-safe comparison on verification.
Chain readable, transform, and writable streams with pipeline to process large files in constant memory while propagating backpressure and errors.
Offload CPU-bound work to a pool of worker threads with Piscina-style sizing, transferable buffers, and graceful pool shutdown.
Compare two flat objects field by field and report added, removed, and changed keys, the core of audit logging and change detection.
Cap parallel task execution with p-limit so large batches of promises run at a fixed concurrency instead of exhausting memory or API quotas.
Slice an array into a page and return metadata such as total pages and whether more results follow, the shape most list endpoints expose.
Query PostgreSQL through a pg pool with always-parameterized statements, statement timeouts, idle client recycling, and pool sizing guidance.
Prevent secrets from leaking into logs by configuring Pino redaction paths, nested wildcard censoring, and strict serializer boundaries.
Instrument a service with prom-client counters for totals, histograms for latency buckets, and a default metrics endpoint for scraping.
Run an array of async tasks with a maximum concurrency, so a large batch does not open all connections at once and overwhelm a downstream service.
Find the kth largest element in average linear time with quickselect, avoiding the cost of fully sorting when only one rank is needed.
Build point-free data transformation pipelines with Ramda compose, lens-based updates, and curried predicates that stay testable end to end.
Enforce a distributed rate limit with rate-limiter-flexible backed by Redis points, insurance fallback, and per-key consumption tracking.
Render React server-side to a node stream with Suspense boundaries so fast content flushes first and slow data streams in without blocking.
Build a Redis-backed caching layer with TTL eviction, LRU maxmemory policy, cache-aside reads, and explicit invalidation on writes.
Wrap flaky operations with the retry package using predicate-based retries, exponential factors, randomization, and per-operation abort signals.
Retry a flaky async operation a bounded number of times, doubling the delay between attempts, adding jitter, and only retrying errors that are safe to repeat.
Enforce least-privilege access with composable role middleware that verifies tokens, resolves roles, and gates routes without inline checks.
Limit how many callers may hold a resource at once with a counted semaphore that queues waiters and releases permits fairly.
Track request timestamps in a sliding window to count how many calls happened in the last interval, rejecting requests that exceed the allowed rate.
Build dynamic IN clauses with generated placeholders instead of string interpolation, keeping every user value bound as a statement parameter.
Speed up static site builds by hashing content inputs per page, reusing unchanged build cache entries, and invalidating only affected pages.
Process a text stream line by line with a transform, keeping partial chunks buffered so splitting on newlines does not corrupt records.
Consume newline-delimited JSON streams line by line using async iteration over the response body, parsing each record with error isolation.
Query a Supabase table with typed client filters, range pagination, upsert conflicts, and realtime subscription cleanup in one flow.
Use Superagent to GET and POST with automatic parsing, retries, timeout control, and typed response body access for JSON and form payloads.
Throttle limits how often a function runs by allowing at most one call per interval, useful for scroll and resize handlers that fire continuously.
Order a dependency graph so every node appears after its prerequisites, reporting a cycle when no valid order exists.
Create an undici Agent with per-origin connection limits and pipelining depth, then dispatch pooled HTTP requests with explicit abort timeouts.
Write Vitest unit tests for an Express app with Supertest, covering success paths, validation errors, and HTTP status assertions per case.
Keep a WebSocket client alive through disconnects with exponential backoff reconnect, jitter, heartbeat pings, and a bounded retry budget.
Rotate application logs by day and size with winston-daily-rotate-file, keeping bounded history, zipped archives, and separate error streams.
Parse and validate process.env at boot with a Zod schema so missing or malformed configuration fails fast before any request is served.
Instrument aiohttp with middleware that logs every request with duration, status, and client identity, sampling noisy health probes.
Download large files with aiohttp while iterating response chunks, hashing each block on the fly and keeping memory usage flat.
Run many async coroutines while capping concurrency with a semaphore, avoiding the flood of pending tasks that unbounded gathering creates.
Throttle a fast producer with a bounded asyncio queue, blocking enqueue when consumers fall behind instead of buffering unbounded data.
Fan out concurrent work with asyncio TaskGroup, wrapping the group in wait_for so one timeout cancels every straggler cleanly.
Bulk load millions of rows into PostgreSQL with asyncpg COPY, streaming records from an async generator with a single protocol message.
Use a Bloom filter to rule out absent keys with no false negatives, trading a small false-positive rate for large memory savings.
Schedule recurring Celery tasks with beat crontabs, mixing timezones, staggered offsets, and task-specific routing to dedicated queues.
Retry failing Celery tasks with exponential backoff and jitter, capping max delay, classifying retryable exceptions, and exposing stats.
Build chained Click subcommands where multiple steps run in sequence, sharing a result context and enforcing invocation order.
Wrap a code block in a context manager that measures elapsed time, so timing instrumentation is added without clutter or manual bookkeeping.
Write dictionaries to CSV with a declared header order, ensuring every row has the same columns even when fields are missing.
Paginate a query by comparing against the last seen key instead of a numeric offset, so pages stay stable when rows are inserted.
Scale pandas aggregations with Dask partitions, letting the scheduler parallelize map-side work and tree-reduce the shuffled results.
Validate invariants in a dataclass post-init hook so invalid instances cannot be constructed, keeping bad data out of the rest of the system.
Recursively merge configuration dictionaries so nested sections are combined rather than replaced wholesale by a later override.
Manage containers programmatically with the Docker SDK for Python, configuring health checks and waiting for healthy status before routing.
Read required and optional settings from the environment with typed defaults, raising a clear error when a required value is missing.
Wrap handler functions in a decorator that converts known exceptions into structured error results while letting unexpected errors propagate.
Provide shared settings through a FastAPI dependency so handlers receive a configured object and tests can override it cleanly.
Issue short-lived access tokens plus rotating refresh tokens in FastAPI, detecting reuse of revoked tokens on every exchange.
Expose cursor-based pagination in FastAPI with stable keyset queries, opaque cursor tokens, and total-count-free responses.
Manage shared resources with FastAPI lifespan context, wiring async clients into dependency injection with clean startup and shutdown.
Stream large multipart uploads in FastAPI with per-part size caps, allowed content types, and chunked writes that never buffer fully.
Manage WebSocket connections in FastAPI with a connection registry, broadcasting to all clients and isolating slow consumers.
Accelerate pure lookups with functools.lru_cache, sizing maxsize from hit rates and isolating unhashable arguments.
Consume an iterable in fixed-size batches with a generator, processing large streams without loading everything into memory.
Find the fewest hops between two nodes with breadth-first search, reconstructing the path and reporting when no route exists.
Subclass the HTTPX transport layer to retry idempotent requests with capped backoff, honoring Retry-After and exponential delays.
Add a persistent caching layer to httpx with httpx-cache, replaying stale responses offline and refreshing in the background.
Test HTTP clients without a network by swapping in httpx MockTransport, scripting responses per URL and asserting request payloads.
Sign expiring action tokens with itsdangerous, binding purpose and user context so reset links cannot be replayed cross-endpoint.
Decode newline-delimited JSON records from a file or socket one line at a time, reporting the offending line when a record fails to parse.
Apply a bounded least-recently-used cache to a pure function so repeated calls with the same arguments skip recomputation.
Validate deeply nested payloads with Marshmallow schemas, mapping field errors to their dotted paths and applying load-time defaults.
Run aggregation pipelines with the async Motor driver, streaming large result sets via async iteration and cursor batching.
Trace FastAPI request flows with OpenTelemetry, creating spans for routes and internal steps, then exporting OTLP batches to a collector.
Aggregate CSV files larger than memory with pandas chunksize iteration, accumulating partial sums and merging into a final report.