toWellFormed Replaces Lone Surrogates
Repair lone surrogates with toWellFormed before persistence: isWellFormed detects them, U+FFFD replaces them, and matched pairs stay untouched.
Page 30 of 50
Repair lone surrogates with toWellFormed before persistence: isWellFormed detects them, U+FFFD replaces them, and matched pairs stay untouched.
static Symbol.hasInstance lets a class decide what instanceof returns, so duck-typed objects matching the expected shape pass without inheriting.
Symbol property keys stay invisible to Object.keys, for..in and JSON.stringify, and only getOwnPropertySymbols or Reflect.ownKeys can enumerate them.
Object-to-primitive conversion asks Symbol.toPrimitive first, then valueOf or toString depending on the hint, so numeric and string contexts can disagree.
A template element stores one row once; content.cloneNode(true) stamps out an independent row per record without building innerHTML strings.
Await any object with a then method: Promise.resolve and await unwrap thenables, and repeated resolve calls only take the first one.
timers/promises turns timers into awaitable promises: sleep reads linearly, setImmediate yields one macrotask turn, and setInterval iterates ticks that abort.
See why toFixed output follows the stored binary float instead of decimal rounding, then round money amounts predictably with Number.EPSILON.
trimStart removes leading whitespace, trimEnd removes trailing whitespace, trim does both; repeated calls stay idempotent on trimmed strings.
subarray returns a view over the same ArrayBuffer so writes land in the source array, while slice copies bytes into independent memory.
Guard untrusted JSON values with typeof plus a null check, then separate arrays from plain objects with Array.isArray because typeof reports both as object.
Validate URLs before constructing: canParse rejects bare protocol-relative strings, accepts opaque mailto schemes, and takes a base for relatives.
Scope resources with using declarations: [Symbol.dispose] runs in reverse declaration order on block exit, on both normal and throwing paths.
util.parseArgs validates declared flags: booleans default to false, string options can repeat into arrays, and positionals come back separately.
Hold objects weakly with WeakRef and observe collection via FinalizationRegistry: deref may still return the object until GC actually reclaims it.
Enforce interface contracts with abc: abstract methods raise TypeError at instantiation time when a subclass leaves one unimplemented.
array.array stores numbers in raw machine width by typecode, enforces element types with TypeError, and converts through tobytes and frombytes.
operator.attrgetter builds attribute accessors, supports dotted paths and multiple names as tuple keys, and plugs directly into sorted, min and max.
urlsafe_b64encode with the '=' padding stripped produces JWT-style segments, and decode restores the missing padding before decoding.
hashlib.blake2b takes a key parameter, turning an ordinary digest into a keyed MAC whose digest_size you can shorten to fit tight headers.
bytes.decode picks an error strategy: strict raises UnicodeDecodeError, replace marks bad bytes, ignore drops them, backslashreplace keeps the evidence.
bytes.hex encodes binary as hex text with optional separators, and bytes.fromhex restores it, rejecting odd-length input instead of guessing.
calendar.isleap, monthrange, and monthdatescalendar answer leap-year, month-length, and grid questions with locale-aware weekday names in one import.
str.casefold folds locale-specific letters like German ß to their base form, so case-insensitive matching outlives what str.lower() gets wrong.
cmp_to_key wraps a two-element comparator for sorted when directions conflict, like ascending departments with a descending string field that cannot be negated.
Capture print output in tests by redirecting sys.stdout into a StringIO inside redirect_stdout; the with block restores the real stdout automatically.
contextlib.suppress swallows only the listed exception types while anything else still propagates, replacing bare except blocks with stated intent.
slots=True, frozen=True, and kw_only=True turn a dataclass into an immutable config record: keyword-only construction and no per-instance __dict__.
Produce updated frozen dataclass instances with dataclasses.replace: overridden keywords, untouched remainder, and a chain of traceable copies.
datetime.strptime maps format directives onto a fixed string layout and raises ValueError on any mismatch, giving strict parsing for inbound date fields.
Shift dates with timedelta instead of hand-rolled month tables: cross-month adds, multiplied buffers, and negative steps keep calendar semantics.
Assignment aliases and shallow copy shares nested containers; copy.deepcopy alone detaches every level so mutations stop leaking across names.
Swapping keys and values with a dict comprehension gives O(1) reverse lookups; duplicate values need setdefault grouping or the inversion loses rows.
The dict union operator merges flat keys with the right side winning, while nested dicts are replaced wholesale — deep merging still needs recursion.
Loop with index and item together using enumerate: start shifts the numbering for human ranks, and list materializes index-item tuples.
Render templates whose keys may be missing by pairing format_map with a __missing__ fallback instead of letting KeyError abort the whole render.
The = specifier prints each expression beside its repr for self-documenting debug output, and the !r !s !a conversions pick the shape before formatting.
re.fullmatch requires the pattern to cover the entire string; match and search only anchor the start, so trailing garbage slips past validation.
Cache expensive per-instance results with cached_property: the first access computes, later reads reuse the stored value without recomputation.
functools.partial binds leading positional and keyword arguments ahead of time, and the resulting object exposes func and keywords for introspection.
functools.reduce folds a binary function left to right; without an initializer empty sequences raise TypeError, with one the initial value is returned.
The graphlib module computes a dependency order and, with prepare plus get_ready, hands out batches of nodes that can run in parallel right now.
gzip.compress and gzip.decompress roundtrip bytes through the gzip container format: repeated payloads shrink and restore byte-for-byte.
heapq.merge k-way merges already-sorted iterables lazily, honoring reverse and key, so multiple ordered sources yield one ordered sequence.
heapq.nlargest and nsmallest return the top or bottom k items without sorting everything, the stdlib shortcut when k is small next to the collection length.
Push (priority, seq, task) tuples with heapq so equal priorities pop in insertion order and non-comparable task objects never enter the comparison.
Hold deferred callbacks in a min-heap keyed by monotonic deadlines: pop everything due now, then report the next task still waiting.
int.to_bytes serializes integers at a fixed width and byte order, from_bytes parses them back, and widths too small raise OverflowError instead of truncating.
isdigit accepts superscripts and other non-decimal digits, so input validation that feeds int() must gate on isdecimal instead of isdigit.
itertools.accumulate streams running totals, products, and maxima in one lazy pass, with an optional initial seed and any two-argument function.
chain and chain.from_iterable stream elements from several iterables lazily, flattening one nesting level without materializing intermediate lists.
Slice iterators lazily with islice: consecutive batches continue where the last slice stopped, while windows over a list leave the sequence untouched.
Turn a series into adjacent pairs with itertools.pairwise, then feed deltas, peak steps, tee branching, and starmap calls from those windows.
itertools.product expands several iterables into the cartesian product, combinations picks unordered subsets, permutations keeps order.
dropwhile skips a leading run that satisfies the predicate and takewhile keeps only that run; both stop at the first mismatch, unlike filter.
Keep uneven sequences aligned with zip_longest: fillvalue marks the missing side explicitly instead of letting zip truncate silently.
object_pairs_hook receives every JSON object as a list of pairs, so duplicate keys can be rejected or collected instead of silently overwriting.
types.MappingProxyType wraps a dict in a dynamic read-only view: reads stay live, writes raise TypeError, and frozenset values freeze the inner levels too.
Structural pattern matching unwraps dicts and sequences in one case ladder: literal keys bind capture variables and guards reject values the shape alone cannot.
math.fsum tracks every intermediate bit so the total matches exact decimal intent, while builtin sum accumulates binary float error on repeated additions.
math.gcd reduces ratios, math.lcm finds the shared cadence of periodic jobs, and math.prod multiplies a list without an explicit reduce loop.
math.sqrt converts to float first and loses precision past 2**53, while math.isqrt stays exact on arbitrarily large integers and detects perfect squares.
namedtuple turns plain tuples into records with named fields: _make builds from sequences, _replace copies with edits, _asdict exports a dict.
Track most-recently-used keys with OrderedDict: move_to_end on touch, popitem(last=False) evicts from the oldest end, iteration order stays observable.
pprint prints nested dicts and lists with stable indentation and line width, and pformat returns the same layout as a string for logs and golden assertions.
A @property setter turns ordinary assignment into a validation point, so out-of-range values are rejected even during construction.
queue.Queue moves tasks between threads without manual locks; task_done and join form a completion barrier, and a sentinel stops the worker.
random.Random(seed) produces the same draws, shuffles, and samples on every replay, so tests and demos stay reproducible; unseeded instances differ.
Scan a line into structured records with re.finditer: named groups, one-pass iterators that drain, and span positions for surgical edits.
Each lookahead assertion inspects one requirement without consuming characters, so a single combined pattern can enforce several password rules at once.
re.split returns capture groups alongside the fields, so delimiters stay in the result list and the original line can be rebuilt byte for byte with join.
str.removeprefix and str.removesuffix strip a known affix and return the string untouched when it is absent, replacing fragile slicing.
shlex.split applies POSIX shell quoting rules to a command string, so quoted spaces, literal hashes and escapes arrive as one argv list ready for subprocess.
Stage a release directory with shutil: copy2 preserves metadata, move relocates the source away, copytree clones whole trees, disk_usage reports bytes.
splitlines recognizes every Unicode line boundary — CRLF, NEL, and line separators included — while a plain split on newline leaves carriage returns behind.
ljust and rjust pad strings to a fixed width for aligned report columns, while zfill zero-fills numeric codes so 7 becomes 000007.
str.partition cuts at the first separator, rpartition at the last, and a missing separator returns the whole string with two empty halves instead of raising.
Build a codepoint translation table for smart quotes and dashes, compose with NFC normalization first, and delete whole character classes on the fly.
Use string.capwords when str.title breaks words at apostrophes and hyphens: whitespace is the split unit, so contractions render correctly.
traceback.format_exc captures the full interpreter traceback inside except blocks, format_exception_only keeps just the error line, idle calls stay safe.
TypedDict records which config keys are required versus optional, and __required_keys__ plus __optional_keys__ let runtime code inspect that contract.
Use SimpleNamespace for lightweight attribute records: fields read as attributes, vars() exposes the same dict, and equality compares field values.
Describe dict payloads at the type level with TypedDict: required keys stay mandatory, NotRequired keys are consumed behind membership checks.
unicodedata.normalize with NFD splits accented letters into base plus combining marks; dropping category Mn code points turns Zoë into Zoe for search keys.
WeakValueDictionary holds values weakly: entries disappear when the last strong reference dies, while live entries keep normal dict semantics like get.
zip(*rows) unpacks a list of rows so every column becomes one tuple: transpose tables, align headers with values, then zip(*columns) reverses it.
Store datetimes in UTC and convert with ZoneInfo: one meeting renders as different wall clocks, and New York moves between UTC-5 and UTC-4 with DST.
Take impl IntoIterator at function boundaries so callers pass vectors, arrays, or ranges directly, and the function only needs into_iter and sum.
Write read-only helpers against &[T] and mutating helpers against &mut [T]; Vecs and arrays deref-coerce into the borrowed slice the function actually needs.
Arc::make_mut clones the shared value only while other owners hold references, then mutates in place once the Arc is uniquely owned.
Fill a fixed-size array element by element with array::from_fn, getting an inline, stack-allocated table computed from each index at construction.
Apply array::map to fixed-size buffers: the result keeps the same length at compile time, can change element type, and never touches the heap.
Validate characters with is_ascii_hexdigit to accept only 0-9 a-f A-F, then decode each accepted char through to_digit with radix 16.
Capture the matched value with @ while range and or-patterns still select the branch, so one binding serves both branch decisions and output formatting.
fetch_add with Relaxed ordering keeps increments atomic without cross-operation ordering, and Release stores pair with Acquire loads to publish data.
Barrier::wait blocks until every thread in the group arrives, releasing them together each round so phase boundaries stay aligned across workers.
Replace two-arm true-or-None matches with then_some for eager values and then for lazy closures, and extend validation lists straight from the results.
Register heterogeneous closures in one Vec of Box<dyn FnMut> and fire them later, because boxed trait objects erase the distinct closure types.
BTreeMap keeps keys ordered so range queries return inclusive and exclusive windows without sorting, with first and last key access at logarithmic cost.
Stream file lines with BufReader and lines(), propagate io errors with ?, and tally valid versus invalid records without loading the whole file.