fileinput Streams CLI Line Context
fileinput reads CLI file arguments in sequence, tracks global and per-file line numbers, and rewrites files in place with a backup extension.
Page 9 of 50
fileinput reads CLI file arguments in sequence, tracks global and per-file line numbers, and rewrites files in place with a backup extension.
findall returns plain strings for one capture group but tuples once two or more groups appear, a shape change that trips naive parsers.
Slow and fast pointers meet inside a cycle; resetting one to the head and walking again at equal speed lands on the entry node.
__getattr__ runs only after normal lookup fails, so a settings wrapper can serve defaults lazily while real typos still raise AttributeError.
glob matches single levels with *, crosses directories only when ** is paired with recursive=True; results arrive in directory order, so sort them.
str.isprintable flags control, format and non-ASCII space characters, so one comprehension lists suspicious code points in untrusted input before storing.
Reversing a singly linked list needs three pointers: remember the successor, flip the link, and walk once so prev ends up the new head.
[[0] * cols] * rows copies row references, so writing one cell appears in every row; a comprehension allocates a fresh list per row and keeps edits local.
math.remainder snaps to the nearest multiple so results land inside half the divisor, while % follows the divisor sign and fmod follows the dividend.
ord returns the code point behind a character and chr inverts it, so char-level text math works on Unicode strings that iterate one code point at a time.
random.Random(seed) makes shuffle reproducible: the same deck reshuffled with the same seed replays card-for-card, which is what deal logs and tests need.
reversed hands back a one-shot reverse iterator instead of copying, leaving the sequence untouched, while slicing [::-1] allocates a re-usable list.
Set operators |, &, -, and ^ compose permission coverage checks directly, with union, intersection, difference, and issubset methods as named equivalents.
A deque of indices kept value-decreasing answers each sliding-window maximum in amortized constant time because every index enters and leaves the queue once.
No-argument split() treats any whitespace run as one separator and drops the edges, while rsplit with maxsplit keeps the left side intact for extension splits.
str.join is the separator method: it accepts any iterable of strings, requires conversion for numbers, and yields an empty string for an empty iterable.
str.replace accepts an optional count that limits replacement to the first N occurrences, enough for tiered masking without splitting strings.
string.ascii_uppercase plus string.digits defines the 36 legal characters for redeem codes; normalization absorbs separators, spaces and casing.
Annotated attaches validation markers next to field types, and get_type_hints with include_extras recovers them for runtime checks.
get_origin and get_args split generic aliases at runtime: list[int] yields list and int, unions expose their members, plain types expose nothing.
unicodedata.category assigns every character a class code, so sanitizers can whitelist letters and punctuation while dropping control and format characters.
Sort each word letters into a canonical key so anagrams land in the same bucket, then aggregate with defaultdict and rank groups by size.
Push openers on a stack and require each closer to mirror the stack top, so crossed pairs, stray closers, and unclosed openers all fail loudly.
date(year, month, day) validates on construction: impossible dates raise ValueError with the exact rule instead of rolling into the next month.
Run SequenceMatcher.get_opcodes over word lists to get equal, replace, delete, and insert ranges, so a diff describes sentence edits instead of whole lines.
Sentinel head and tail nodes make append and unlink constant-time with no None checks, and iteration walks head.next until it reaches the tail sentinel.
Build XML with Element and SubElement, serialize with tostring, pretty-print with indent, then parse it back with fromstring and read values by path lookup.
Index rows by id, attach each child under its parent reference, and collect roots separately, turning flat rows into a nested tree in one pass.
Slice a byte payload into fixed-width rows of offset, two-digit hex, and printable characters so binary data stays readable in logs.
Gate user-supplied field names behind str.isidentifier and keyword.iskeyword or issoftkeyword so dynamic attributes never collide with reserved syntax.
Flatten arbitrarily nested lists with an explicit iterator stack, so a thousand levels deep still works where recursion would hit its limit.
Catch json.JSONDecodeError and read msg, pos, lineno, and colno to show exactly where a malformed payload stopped parsing.
Kadane's scan extends or restarts the running subarray at each item and records the best window, handling all-negative arrays correctly.
Slice assignment replaces, inserts, or deletes ranges in place; the assigned sequence can have any length, so the list resizes around it.
Push onto an auxiliary stack that tracks the running minimum alongside the main stack, so pop and get_min stay O(1) with no rescanning.
Split digit runs out of names and compare them as integers, so report-2 sorts before report-10 and zero padding stops changing the order.
Walk two pointers inward from both ends, skipping non-alphanumeric characters and comparing lowercased letters, so punctuation-laden phrases still verify.
pickle round trips tuples that JSON silently widens to lists while None survives as null; loads must only ever receive payloads your own system produced.
Build one prefix array up front, then answer any range sum query with a single subtraction instead of re-summing the slice every time.
Build a FIFO queue from two stacks: pour the inbox once when the outbox empties, so every element moves at most twice and operations stay amortized O(1).
With a seeded Random, sample draws without replacement and rejects oversized k, choices draws with replacement under weights, shuffle reorders in place.
Greedy quantifiers stretch to the longest span and lazy quantifiers, written with an extra ?, stop at the shortest span that still succeeds.
Encode runs of repeated characters as count-plus-char pairs and expand them back, rejecting a dangling trailing count instead of dropping it.
Split a value stream across two heapq heaps so every insert rebalances the halves and yields the exact running median without re-sorting.
Walk both ends of a sorted array inward: move the left pointer when the pair sum is too small, the right one when it is too big.
An Arc-shared AtomicBool lets the main thread flip a stop flag while the worker spins on load, and join confirms the shutdown before the process exits.
A Release fence before publishing a flag pairs with an Acquire fence after observing it, so payload writes are visible without atomic ordering on each access.
Hold three threads at a Barrier until all arrive, then confirm exactly one thread per phase receives the leader signal.
Search a slice sorted by one field with binary_search_by_key, getting either the match index or the insertion point where a new record belongs.
An explicit stack replaces recursion for in-order traversal: push left spine nodes, pop to visit, then continue into the right subtree.
Derive Ord on a job struct field-by-field and push it into a BinaryHeap: pops come back highest priority first, and Reverse flips to a min-heap.
BinaryHeap::iter() walks internal heap layout rather than sorted order, so ordered consumption needs peek or an explicit into_sorted_vec.
Demote the failing top job in place with peek_mut: mutating through the guard and dropping it sifts the heap back into a valid max-heap.
String spends three words on ptr, len, and capacity; Box<str> is a two-word fat pointer into one exact allocation with no growth methods.
Match BTreeMap::entry to insert or update in one lookup, then read the map back in sorted key order without re-sorting.
Drain a BTreeMap deadline queue in key order with pop_first, and pop_last for reverse audit passes, consuming entries as they are taken.
BTreeMap iterates keys in ascending order; iter().rev() walks the same tree from the largest key down without sorting or reversing a Vec.
String len() counts UTF-8 bytes while chars().count() counts characters, and the gap decides password limits and text truncation.
Fill the recurrence ways(n) = ways(n-1) + ways(n-2) with two rolling variables, so each step count needs only one pass and O(1) memory.
Box<dyn Trait> has no Clone, so a clone_boxed method plus impl Clone for the boxed object rebuilds each concrete type and whole Vecs become cloneable.
Turn a map lookup into an owned value with cloned so the borrow ends immediately, letting later inserts into the same HashMap borrow-check cleanly.
std::cmp::min and max pick bounds for any Ord type, and nesting them clamps a value into a range without a hand-written if.
Bottom-up DP fills a table of least-coin counts for each amount, trying every denomination and returning None when the amount is unreachable.
Copy a file with fs::copy inside a fallible main, assert the byte count, and compare content line by line before cleaning up both temporary files.
Implement Iterator with a lifetime parameter so a hand-written iterator lends &a T items while the underlying slice keeps its owner.
Implement Read once to uppercase bytes as they stream through, then compose the reader with BufReader like any other Read source.
Keep unresolved indexes on a stack whose temperatures never increase, popping to settle wait distances the moment a warmer day appears.
Custom Debug impls branch on f.alternate, so {:?} renders one compact line while {:#?} gets the pretty multi-line shape.
Filter an iterator through a HashSet whose insert return flags first sightings, so duplicates drop while the original order of survivors is preserved.
Compare two HashMaps with get and contains_key to split keys into added, changed and removed buckets, borrowing both maps without cloning values.
u64::div_ceil computes ceiling division without the (n + d - 1) / d overflow trap, so page counts and batch boundaries stay correct near integer limits.
Choosing between numeric sources at runtime returns Box<dyn Iterator>, giving callers one concrete type instead of threading generic parameters through.
Show how enumerate and rev commute differently: rev().enumerate() renumbers from zero while enumerate().rev() preserves original positions.
Read OS, ARCH, FAMILY, and linker suffixes from env::consts so install paths and binary names follow the target platform.
env::split_paths breaks the PATH variable apart on the platform separator and env::join_paths rebuilds it, rejecting embedded separators.
Attach typed payloads like RetryInfo to errors with Error::provide and read them back via request_ref without downcasting.
Expand compact range notation like 1-3,5,8-9 by splitting on commas, matching each part with split_once, and flat_mapping ranges into one vector.
Keep numbers inside safe bounds with f64::clamp and Ord::clamp so sensor readings and queue depths never escape their configured ranges.
fetch_update folds the compare-and-swap retry loop into one call: Ok carries the previous value when the closure wrote, Err carries it when the closure refused.
Stage a write with write_all, force it to disk with sync_all, then publish with fs::rename so a crash never leaves a half-written live file.
Grouping the two remainders into one tuple lets a single match dispatch Fizz, Buzz, and FizzBuzz without nested if branches or repeated modulo checks.
Preallocate fixed-size record files with File::set_len, which extends or truncates to the exact byte count and keeps len fully controlled.
A hand-written Future returns Pending twice with self-wakeups, and a block_on executor polls it until Ready using the std Wake trait to unpark the thread.
The Euclidean loop replaces the pair with the remainder until it hits zero, and dividing before multiplying keeps the LCM inside u64 bounds.
Backtracking adds "(" while open is below n and ")" only when it would keep the prefix balanced, cloning each complete combination once.
HashMap::insert replaces the stored value and returns the old one moved out, so replacing is observable while entry keeps what is already there.
Look up equivalent keys with HashSet::get to retrieve the canonical stored form, so repeated normalization never duplicates entries.
Argument-position impl Trait is an unnamed generic parameter: each call site picks one concrete type, and callers never see the hidden name.
Rust 2021 placeholders capture identifiers directly, so format!, println!, and panic! read like the text they print while width and precision specs still apply.
Group integer digits in threes over the byte view, handling the sign and zero without overflow even for i64::MIN via unsigned_abs.
An into_parts method takes self by value and returns its fields, so calling it moves the struct away and any later use becomes a compile error.
Implementing io::Read by hand shows the contract: fill the caller buffer, decrement a budget, and return Ok(0) at EOF so read_to_end terminates cleanly.
Locate the first matching element with find_position, which returns the index and the item together in one pass on both borrowed and owning iterators.
Iterator::sum works on Result items too: Ok values accumulate and the first Err stops the fold, so a dirty row surfaces with its context.
Plain zip silently drops the longer side tail, so pad the short side with repeat and chain to equal length before pairing records.
Derive the missing number from the full range sum minus the iterator sum, then cross-check with an xor pass where paired indexes and values cancel out.
The failure table records the longest equal prefix-suffix per position, letting the scan reuse matched characters instead of restarting.
Count characters into a HashMap entry map, add every complete pair to the palindrome length, and reserve one leftover odd character for the center.
Track a HashSet-backed sliding window with two pointers so the longest run of non-repeating characters is found in one pass over the chars.
Implement LowerHex and UpperHex so {:x} and {:X} render a custom struct as fixed-width hex wire fields, lowercase and uppercase.