repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
cs249r_book
book/cli/utils/__init__.py
.py
""" Utility functions and helpers for the MLSysBook CLI. Contains shared utilities for console output, validation, and other common functionality. """
7
152
cs249r_book
book/cli/checks/math_multiplier_style.py
.py
"""Multiplier and ``\\times`` style checks for QMD prose. This checker is intentionally example-heavy because most failures are visual typography mistakes that look plausible in source. It catches: * ``body_multiplier_suffix``: ``speedup_str = fmt(speedup, suffix="×")`` or ``suffix="x"``. Fix by using the typed ...
333
12,860
cs249r_book
book/cli/checks/lego_prose_literals.py
.py
#!/usr/bin/env python3 """Flag hardcoded numeric literals in LEGO walkthrough prose. Policy (computation-sensitive, not number-free prose) ----------------------------------------------------- Flag literals when they appear in a *computational walkthrough*: a callout notebook or worked example whose nearby LEGO cell e...
457
15,467
cs249r_book
book/cli/checks/currency_style.py
.py
r"""Currency style checks for book currency notation. Policy: * Reader-facing prices use ``$``. * Source prose and LEGO currency prefixes escape the dollar sign as ``\$``. * ``USD`` appears only once, in the shared notation definition that says dollar-denominated costs are U.S. dollars unless noted otherwise...
329
12,401
cs249r_book
book/cli/checks/lego_dead_code.py
.py
#!/usr/bin/env python3 """LEGO exported-variable liveness check. This powers:: ./book/binder check code --scope lego-dead-code Binder owns the implementation; pre-commit reaches it through ``binder check``. """ from __future__ import annotations import argparse import re import sys from dataclasses import data...
207
6,370
cs249r_book
book/cli/checks/__init__.py
.py
""" Binder-native check implementations. Check logic that powers ``./book/binder check <group> --scope …`` lives here as ordinary Python modules. ``book/cli/commands/validate.py`` imports from this package and converts results to ``ValidationIssue`` records. Temporary standalone shims may import from ``cli.checks`` d...
13
483
cs249r_book
book/cli/checks/fmt_prose_contract.py
.py
#!/usr/bin/env python3 """ fmt_prose_contract.py — enforce the OUTPUT-formatter ↔ prose glyph contract. Static checker for invariant **I2** (ASSESSMENT.md §3 / fmt.md §7). For every ``{python} Class.var_str`` reference in prose it looks up the formatter that produced ``var_str`` (by AST-parsing the chapter's cells) an...
390
15,736
cs249r_book
book/cli/checks/binder_canonical.py
.py
"""Binder-as-front-door invariant check for the pre-commit config. This powers:: ./book/binder check cli --scope binder-canonical The rule it enforces, in one sentence: **every pre-commit hook that targets book content must dispatch through ``./book/binder``, not call a raw script.** Why this exists -----------...
143
5,313
cs249r_book
book/cli/checks/percent_prose.py
.py
#!/usr/bin/env python3 """Percent-in-prose: detect the `%` symbol where body prose should spell out 'percent'. This is the symmetric inverse of ``percent_tables.py``. House style (MIT Press ``AU_QUERY_RESPONSES.md`` Category H, aligned with Chicago Manual of Style §9.18) splits on *sentence vs. data*, not on context t...
145
5,689
cs249r_book
book/cli/checks/fmt_semantic_suffix.py
.py
#!/usr/bin/env python3 """ fmt_semantic_suffix check — value-kind must be a typed formatter, not a free-text ``suffix=`` on the generic ``fmt()``/``fmt_int()``. This is the regression gate for the typed-formatter migration. The semantic kind of a value (percent, multiplier, percentage-points, count-scale) belongs in t...
223
7,256
cs249r_book
book/cli/checks/percent_tables.py
.py
#!/usr/bin/env python3 """Percent-symbol-in-tables: single source of truth for the check and the fixer. House style inverts between prose and tables: - In PROSE and CAPTIONS, "percent" is spelled out (MIT Press §10.2); the `%` symbol is banned there. - In TABLES, cells are dense tabular data and the conventio...
217
7,433
cs249r_book
book/cli/checks/mitpress_terms.py
.py
#!/usr/bin/env python3 """MIT Press canonical spelling dictionary (§10.7) — detection + fix. The MIT Press editorial standard §10.7 fixes the canonical spelling of a long list of terms (Webster's 11th first spelling). This module enforces the **unambiguous** subset — terms with a single correct form regardless of gram...
179
6,951
cs249r_book
book/cli/checks/markdown_list_spacing.py
.py
"""Flag bold lead-in paragraphs that are immediately followed by lists. Pandoc treats a paragraph followed directly by ``- item`` as one paragraph, not as a separate list block. In rendered output this can collapse into text like ``**Step 2**: ... - item``. This check catches the high-signal house style case: a non-li...
106
2,920
cs249r_book
book/cli/checks/prose_integrity.py
.py
"""Prose-integrity detectors: sentence starts, hand-typed attributions, italics. Added 2026-08-14 after a tone-audit pass introduced nine banned section meta-openers, two of which left a sentence starting with a lowercase word ("...energy budget. this section introduces..."). Nothing in the gate set noticed. These thr...
205
8,327
cs249r_book
book/cli/checks/bib_lint.py
.py
#!/usr/bin/env python3 """BibTeX linter, validator, and formatter for the MLSysBook project. Enforces the canonical schema and formatting rules documented in the project prose style guide §5 Bibliography Hygiene. Usage: python3 book/tools/bib_lint.py <file.bib> [--check|--fix|--report] python3 book/tools/bib_...
1,138
43,679
cs249r_book
book/cli/checks/cli_contract.py
.py
"""Public command contract checks for the Binder CLI. This powers:: ./book/binder check cli --scope contract The check is intentionally small and example-heavy. It runs read-only commands that define the public Binder surface and fails if help text, migration hints, or exit codes drift. Examples of what it catc...
375
11,985
cs249r_book
book/cli/checks/lego_units.py
.py
#!/usr/bin/env python3 """LEGO unit discipline linter for QMD cells (warnings + blocking errors).""" from __future__ import annotations import argparse import json import os import re import subprocess import sys from dataclasses import dataclass from pathlib import Path @dataclass(frozen=True) class LintIssue: ...
279
10,849
cs249r_book
book/cli/checks/margin_geometry.py
.py
"""Binder-native rendered-PDF margin geometry checks. This module is the shared implementation behind ``binder layout overlaps`` and post-build PDF validation. It intentionally depends only on rendered PDF geometry from PyMuPDF, not on source anchors or LaTeX log heuristics. """ from __future__ import annotations fr...
391
12,089
cs249r_book
book/cli/checks/lego_prose_units.py
.py
#!/usr/bin/env python3 """Flag redundant unit/currency tokens after closed ``{python} *_str`` prose refs. Policy ------ Only **closed** exports (domain formatters, ``fmt_qty``, ``fmt_percent`` with ``style='prose'|'symbol'``, ``fmt_count(scale=...)``, ``fmt_multiple``, or ``*_unit_str`` names fed by open ``fmt()`` on ...
320
13,002
cs249r_book
book/cli/checks/math_canonical.py
.py
#!/usr/bin/env python3 """ Math canonical check — fmt-family and suffix discipline for LEGO cells. Enforces the canonical math-rendering convention (see the project math rules): 1. Every ``*_str`` / ``*_math`` / ``*_eq`` / ``*_frac`` assignment in a ``{python}`` cell must use ``mlsysim.fmt`` helpers or ``Markd...
917
35,589
cs249r_book
book/cli/commands/layout.py
.py
""" ``binder layout`` — PDF page-layout diagnostics. Subcommands: check — Scan a built PDF for pages with excessive bottom whitespace in the main body column, and guess the likely cause (the block at the top of the next page that probably forced the break). The plan...
3,742
146,342
cs249r_book
book/cli/commands/bib.py
.py
""" ``binder bib`` — Bibliography management. Subcommands: list — Show all .bib files with entry counts mechanical — Apply safe §5 field-level fixes (pre-commit first step) clean — Remove unused entries from .bib files update — Run betterbib sync-preserve on .bib files (fetch metadata, keep ci...
547
21,123
cs249r_book
book/cli/commands/reset.py
.py
"""Reset generated/local CLI state to a clean baseline.""" from __future__ import annotations import argparse from typing import List from rich.console import Console from rich.markup import escape as _rich_escape from rich.panel import Panel from rich.table import Table console = Console() class ResetCommand: ...
73
2,629
cs249r_book
book/cli/commands/_registry_checks.py
.py
"""Registry migration gates for `binder check registry`.""" from __future__ import annotations import importlib.util import subprocess import sys from dataclasses import dataclass from pathlib import Path @dataclass(frozen=True) class RegistryIssue: code: str message: str file: str = "(registry)" li...
239
8,559
cs249r_book
book/cli/commands/headings.py
.py
""" ``binder headings`` — Heading-case enforcement for MIT Press style. Enforces the H1/H2 headline-case + H3+ sentence-case policy documented in the project prose style guide §10.3.1. Preserves ten documented exceptions: acronyms, hyphenated-acronym compounds, digit-letter models (70B, 3D), single-letter labels (Arch...
569
24,059
cs249r_book
book/cli/commands/render.py
.py
""" ``binder render`` — Render generated figures to a browsable gallery. Subcommands: plots — Render all matplotlib/Python figures from QMD files to PNG. Outputs to ``_output/plots/<chapter>/<fig-label>.png``. Future subcommands: diagrams — Render TikZ diagrams (requires lualatex) all ...
339
11,602
cs249r_book
book/cli/commands/audit.py
.py
"""Chapter-level build audits (`binder audit chapter-pdf|chapter-html`).""" from __future__ import annotations import argparse import importlib.util import sys from pathlib import Path from rich.console import Console console = Console() def _repo_root() -> Path: return Path(__file__).resolve().parents[3] d...
73
2,580
cs249r_book
book/cli/commands/maintenance.py
.py
""" Maintenance commands for MLSysBook CLI. Handles setup, switch, hello, about, and other maintenance operations. """ import argparse import hashlib import json import os import re import subprocess import shutil import time from collections import defaultdict from datetime import datetime from pathlib import Path f...
1,108
49,068
cs249r_book
book/cli/commands/clean.py
.py
""" Clean command implementation for MLSysBook CLI. Handles cleaning build artifacts and restoring configurations. """ import shutil from rich.console import Console from rich.markup import escape as _rich_escape from rich.panel import Panel from rich.table import Table from cli.core.artifacts import clean_build_art...
212
8,091
cs249r_book
book/cli/commands/newsletter.py
.py
""" Newsletter command implementation for MLSysBook CLI. Manages newsletter drafts, publishing to Buttondown, and fetching sent newsletters for the website archive. Requires BUTTONDOWN_API_KEY environment variable for API operations. """ import json import os import re import shutil from datetime import datetime fro...
426
17,410
cs249r_book
book/cli/commands/_index_checks.py
.py
"""Index check primitives for `binder check index` scopes.""" from __future__ import annotations import re from dataclasses import dataclass from pathlib import Path INDEX_RE = re.compile(r"\\index\{([^{}]*(?:\{[^{}]*\}[^{}]*)?)\}") SEEREF_RE = re.compile(r"^([^|]+)\|see(?:also)?\{([^}]+)\}$") GENERIC_BARE = { ...
195
7,058
cs249r_book
book/cli/commands/info.py
.py
""" ``binder info`` — Book statistics and figure extraction. Subcommands: stats — Count figures, tables, equations, listings, text lines, words figures — Extract figure list with labels, captions, and alt-text Use --with-pdf to merge LaTeX figure numbers and page numbers from ...
1,129
44,557
cs249r_book
book/cli/commands/preview.py
.py
""" Preview command implementation for MLSysBook CLI. Handles starting development servers with live reload for interactive development. """ import subprocess import signal import sys from pathlib import Path from typing import List, Optional from rich.console import Console console = Console() class PreviewComman...
118
4,009
cs249r_book
book/cli/commands/__init__.py
.py
""" Command implementations for the MLSysBook CLI. Each command is implemented as a separate module for better maintainability and testing. """
7
145
cs249r_book
book/cli/commands/_pdf_checks.py
.py
"""PDF post-build verification used by `binder build pdf` and `binder check pdf`. Scans rendered PDF text (via ``pdftotext``) for defects Quarto/LuaLaTeX can emit without failing the render: unresolved cross-refs (``?@sec-foo``), literal unrendered cross-refs (``@sec-foo``), undefined LaTeX references (``Figure ??``),...
804
28,698
cs249r_book
book/cli/commands/debug.py
.py
""" Debug command implementation for MLSysBook CLI. Two-phase build debugger that isolates build failures: Phase 1: Scan chapters one-by-one to find which chapter(s) fail Phase 2: Binary search within a failing chapter to find the exact section Usage via binder: ./binder debug pdf --vol1 # ...
615
22,618
cs249r_book
book/cli/commands/reference_check.py
.py
""" Native reference check: validate .bib entries against academic DBs (hallucinator). Used by `binder check references --scope hallucinator`. Requires: pip install hallucinator bibtexparser (or install optional extra: pip install -e ".[reference-check]"). Optional env: OPENALEX_KEY, S2_API_KEY. Note: Semantic Schola...
428
16,817
cs249r_book
book/cli/commands/_epub_checks.py
.py
"""EPUB check primitives used by the `binder check epub` command group. This module holds the pure-Python logic for the two `check epub` scopes so that `validate.py` can call it as ordinary Python (not via a subprocess-to-a-script, which is what the older delegated-script pattern used). All checks here return a list o...
791
30,328
cs249r_book
book/cli/commands/release.py
.py
"""Release orchestration for Binder. `binder release` is the high-level release gate: it runs the checks that a human release audit currently remembers by hand, classifies build/layout outcomes, and writes one structured report for follow-up fixes. """ from __future__ import annotations import argparse import json i...
637
21,431
cs249r_book
book/cli/commands/build.py
.py
""" Build command implementation for MLSysBook CLI. Handles building chapters and full books in different formats (HTML, PDF, EPUB). """ import os import platform import subprocess import signal import sys from pathlib import Path from typing import Dict, List, Optional, Tuple from rich.console import Console from ri...
1,903
86,445
cs249r_book
book/cli/commands/doctor.py
.py
""" Health check command for MLSysBook CLI. Performs comprehensive system health checks to ensure everything is working properly. """ import subprocess import sys from pathlib import Path from typing import List, Tuple, Dict, Any from rich.console import Console from rich.table import Table from rich.panel import Pan...
608
23,503
cs249r_book
book/cli/commands/formatting.py
.py
""" Format commands for MLSysBook CLI. Auto-formatters for QMD content: blank lines, Python code blocks, list spacing, div spacing, and table formatting. Usage: binder format blanks — Collapse extra blank lines binder format python — Format Python code blocks (Black; display 70, LEGO 150) binder forma...
572
22,732
cs249r_book
interviews/vault/topic_schema.py
.py
"""Pydantic schema for the canonical topic taxonomy. Validates topics.json: unique IDs, kebab-case format, valid areas, prerequisite existence, and DAG acyclicity. Usage: python3 topic_schema.py # Validate topics.json python3 topic_schema.py --stats # Print topology stats python3 top...
261
8,081
cs249r_book
interviews/vault/vault.py
.py
#!/usr/bin/env python3 """vault.py — Unified CLI for the StaffML interview question vault. Usage: python3 vault.py validate # Schema check python3 vault.py stats # Full statistics python3 vault.py gaps # 3D coverage cube analysis python3 vault.py dedup # Multi-stage dedup (exa...
2,823
108,968
cs249r_book
interviews/vault/schema.py
.py
"""Pydantic schema for the StaffML question corpus (schema v1.0). Enum values are imported from :mod:`vault.schema.enums` — the single source of truth. Do not redefine them here. See ``schema/question_schema.yaml`` for the canonical LinkML schema. This module validates dict records (e.g. loaded from corpus.json or fr...
370
12,091
cs249r_book
interviews/vault/scripts/iterate_coverage_loop.py
.py
#!/usr/bin/env python3 """Iterative coverage loop: analyze → generate → render → judge → apply. The loop keeps tightening corpus balance by re-analyzing after every generation pass. It stops automatically when the corpus reaches a steady state — no big gaps remain, hallucination rate spikes, or budget is exhausted. Th...
334
13,485
cs249r_book
interviews/vault/scripts/generate.py
.py
#!/usr/bin/env python3 # STATUS (2026-05-03): preserved as a reference pattern — see vault/scripts/DEPRECATED.md # §"Preserved for adaptation". Coverage-survey-driven generation (find empty # cells, fill emptiest first, stop when saturated). `vault generate` does # per-cell generation but NOT the auto-balance loop. Ada...
682
30,263
cs249r_book
interviews/vault/scripts/audit_question_backfill_balance.py
.py
#!/usr/bin/env python3 """Audit StaffML `question` field coverage and balance after backfill.""" from __future__ import annotations import argparse import json import re import statistics from collections import Counter, defaultdict from pathlib import Path import yaml VAULT_DIR = Path(__file__).resolve().parent.par...
183
5,973
cs249r_book
interviews/vault/scripts/reclassify_zone_bloom_mismatch.py
.py
#!/usr/bin/env python3 """Reclassify questions whose (zone, bloom_level) pair violates the matrix. The ZONE_BLOOM_AFFINITY matrix in interviews/vault/schema/enums.py is the canonical "this zone admits these Bloom verbs" rule. Items that violate the matrix have a self-contradicting classification: zone says one thing, ...
122
4,205
cs249r_book
interviews/vault/scripts/audit_applicability_matrix.py
.py
#!/usr/bin/env python3 """Audit StaffML topic-track applicability sources. Compares: - schema enum topics, - taxonomy_data.yaml topic-track applicability, - paper app_matrix.tex topic labels, - observed YAML topic-track pairs. This report is advisory. It helps decide whether a sparse/invalid-looking cell should be ge...
197
7,165
cs249r_book
interviews/vault/scripts/compare_semantic_passes.py
.py
#!/usr/bin/env python3 """Compare two semantic audit passes and summarize agreement.""" from __future__ import annotations import argparse import collections import json from pathlib import Path from typing import Any VAULT_DIR = Path(__file__).resolve().parents[1] RESULTS_DIR = VAULT_DIR / "audit" / "semantic-revie...
109
4,232
cs249r_book
interviews/vault/scripts/format_yaml_questions.py
.py
#!/usr/bin/env python3 """Canonical formatter for StaffML question YAML files.""" from __future__ import annotations import argparse import difflib import sys from pathlib import Path from typing import Any import yaml VAULT_DIR = Path(__file__).resolve().parents[1] REPO_ROOT = VAULT_DIR.parents[1] QUESTIONS_DIR = ...
245
7,371
cs249r_book
interviews/vault/scripts/preprocess.py
.py
#!/usr/bin/env python3 """Preprocess QMD textbook chapters into clean prose for taxonomy extraction. Strips code blocks, LaTeX, TikZ, figures, tables, and Quarto markup. Keeps section headers, paragraph prose, and lists. Usage: python3 preprocess.py # Process all chapters python3 prep...
197
6,516
cs249r_book
interviews/vault/scripts/summarize_semantic_audit.py
.py
#!/usr/bin/env python3 """Summarize semantic audit JSONL files into a release report.""" from __future__ import annotations import argparse import collections import json from pathlib import Path from typing import Any VAULT_DIR = Path(__file__).resolve().parents[1] RESULTS_DIR = VAULT_DIR / "audit" / "semantic-revi...
111
3,454
cs249r_book
interviews/vault/scripts/gemini_backfill_question.py
.py
#!/usr/bin/env python3 # STATUS (2026-05-03): preserved as a reference pattern — see vault/scripts/DEPRECATED.md # §"Preserved for adaptation". The corpus walk targets the post-v1.0 YAML layout, # but the prompt / batching / threadpool pattern is reused by the upcoming # audit_corpus_batched.py (CORPUS_HARDENING_PLAN.m...
338
13,164
cs249r_book
interviews/vault/scripts/repair_registry.py
.py
#!/usr/bin/env python3 """Append-only repair of id-registry.yaml. The registry is an append-only audit log of every ID ever assigned. Two prior events broke its integrity: 1. Commit ``8a5c3ff3c`` (2026-04-25) renamed 4,754 cohort-tagged IDs (e.g. ``cloud-fill-04027``, ``tinyml-cell-13251``) to clean ``<track>-N...
118
4,570
cs249r_book
interviews/vault/scripts/gemini_cli_generate_questions.py
.py
#!/usr/bin/env python3 # STATUS (2026-05-03): preserved as a reference pattern — see vault/scripts/DEPRECATED.md # §"Preserved for adaptation". `vault generate` (vault-cli) is the modern # entrypoint but does NOT batch — it calls per-question. This script's batching # (12 cells / call, balanced track×area×zone×level ro...
781
35,326
cs249r_book
interviews/vault/scripts/vault_fill.py
.py
#!/usr/bin/env python3 """ Vault Fill — Parallel question generation for every empty cube cell. Architecture: 1. Analyze the 3D coverage cube 2. Generate one shell command per deficit cell 3. Each command writes to a temp JSON file (no file conflicts) 4. Run ALL commands in parallel (via xargs or background processes)...
334
11,641
cs249r_book
interviews/vault/scripts/semantic_audit_questions.py
.py
#!/usr/bin/env python3 """Parallel semantic audit runner for published StaffML questions. This consumes JSONL queues created by prepare_semantic_review_queue.py and appends one structured finding per question. It is resumable: existing qids in the output file are skipped on later runs. The runner batches a few questio...
300
10,862
cs249r_book
interviews/vault/scripts/vault_invariants.py
.py
#!/usr/bin/env python3 """Vault Invariant Checks — structural guardrails for StaffML data integrity. This script enforces invariants ACROSS the three data files (corpus.json, taxonomy.json, chains.json) that per-question schema validation cannot catch. Run it as a pre-commit gate or CI check whenever vault data change...
588
24,843
cs249r_book
interviews/vault/scripts/migrate_to_v1_0.py
.py
"""One-time migration: corpus.json -> per-question YAML at schema_version 1.0. This script replaces the `split_corpus.py` migration that introduced the bugs fixed here. It writes one YAML file per question into a flat-by-track layout: questions/<track>/<id>.yaml Every axis (track, level, zone, topic, competency_...
405
13,198
cs249r_book
interviews/vault/scripts/repair_chains.py
.py
#!/usr/bin/env python3 """Repair chain integrity issues in the StaffML question bank. Two kinds of chain damage accrue over time: 1. **Orphan singletons**: chains where the only remaining member is a single question. Sibling questions were deleted/renamed/archived, leaving a chain-of-one. By definition a chain ...
176
6,661
cs249r_book
interviews/vault/scripts/audit_visual_questions.py
.py
#!/usr/bin/env python3 """Audit and plan StaffML visual-question coverage.""" from __future__ import annotations import json from collections import Counter from pathlib import Path from typing import Any import yaml VAULT_DIR = Path(__file__).resolve().parent.parent ROOT_DIR = VAULT_DIR.parents[1] QUESTIONS_DIR = ...
177
6,650
cs249r_book
interviews/vault/scripts/run_semantic_audit_tracks.py
.py
#!/usr/bin/env python3 """Launch semantic audit jobs per track with separate output files.""" from __future__ import annotations import argparse import os import shlex import subprocess import sys from pathlib import Path VAULT_DIR = Path(__file__).resolve().parents[1] QUEUE_DIR = VAULT_DIR / "audit" / "semantic-rev...
73
2,428
cs249r_book
interviews/vault/scripts/prepare_semantic_review_queue.py
.py
#!/usr/bin/env python3 """Build a semantic review queue for published StaffML questions.""" from __future__ import annotations import argparse import json from pathlib import Path from typing import Any import yaml VAULT_DIR = Path(__file__).resolve().parents[1] REPO_ROOT = VAULT_DIR.parents[1] QUESTIONS_DIR = VAUL...
108
4,166
cs249r_book
interviews/vault/scripts/build_semantic_fix_queue.py
.py
#!/usr/bin/env python3 """Build a prioritized fix queue from semantic audit JSONL results.""" from __future__ import annotations import argparse import collections import json from pathlib import Path from typing import Any VAULT_DIR = Path(__file__).resolve().parents[1] RESULTS_DIR = VAULT_DIR / "audit" / "semantic...
104
3,437
cs249r_book
interviews/vault/scripts/gemini_fix_errors.py
.py
#!/usr/bin/env python3 # STATUS (2026-05-03): preserved as a reference pattern — see vault/scripts/DEPRECATED.md # §"Preserved for adaptation". The HARDWARE_REFERENCE constant (V100/A100/H100/B200/T4 # specs as ground-truth context for the judge) is exactly what # audit_corpus_batched.py needs in Phase 5 (CORPUS_HARDEN...
236
8,612
cs249r_book
interviews/vault/scripts/generate_gaps.py
.py
#!/usr/bin/env python3 """ Gap-fill generator for underfilled StaffML corpus cells. Reads corpus.json, identifies all (track, level, competency_area) cells with fewer than 3 questions, then generates the missing questions using either: - Gemini 2.5 Flash via the `gemini` CLI (default) - Claude Opus 4.6 via the Ant...
643
23,505
cs249r_book
interviews/vault/scripts/vault_loop.py
.py
#!/usr/bin/env python3 """ Vault Loop — Overnight autonomous generation for balanced question coverage. Unlike vault_fill.py (which fills deficit cells once), this script: 1. Fills deficit cells (coverage gaps) 2. Balances over-represented cells by boosting under-represented ones 3. Loops until the cube is both FULL a...
465
16,252
cs249r_book
interviews/vault/scripts/gpt_backfill_question.py
.py
#!/usr/bin/env python3 # STATUS (2026-05-03): preserved as a reference pattern — see vault/scripts/DEPRECATED.md # §"Preserved for adaptation". OpenAI variant of gemini_backfill_question.py. # Useful when the Gemini quota is exhausted or for cross-provider comparison. # Verify the OpenAI SDK version + the chat-completi...
417
15,981
cs249r_book
interviews/vault/scripts/plan_gap_improvements.py
.py
#!/usr/bin/env python3 """Build StaffML gap-analysis and generation-planning artifacts. This script implements the release-oriented improvement plan: - canonical v1 coverage cube from YAML source, - repair backlog for metadata/content drift, - 50-question pilot pack, - validation gates for generated items, - scaled 2...
1,058
41,039
cs249r_book
interviews/vault/scripts/scorecard.py
.py
#!/usr/bin/env python3 """ StaffML Quality Scorecard — single-command corpus health check. Usage: python3 staffml/vault/scripts/scorecard.py python3 staffml/vault/scripts/scorecard.py --compare path/to/previous.json """ import json import argparse from collections import Counter, defaultdict from datetime imp...
242
8,535
cs249r_book
interviews/vault/scripts/generate_hard_questions.py
.py
#!/usr/bin/env python3 """Generate ~500 hard (L4-L6+) questions to fill level distribution gaps. Uses Gemini API (gemini-3.1-pro-preview) to generate questions across all 35 knowledge areas, targeting deficit levels. Each batch includes examples from the existing corpus and valid concept tags for that KA. Usage: ...
560
24,684
cs249r_book
interviews/vault/scripts/audit_resources_migration.py
.py
#!/usr/bin/env python3 """ Phase 0 audit for the deep_dive → resources migration. Walks every question YAML under interviews/vault/questions/, extracts the details.deep_dive field (when present), and emits counts that determine the migration's blast radius: - total questions - questions with deep_dive present / a...
183
7,280
cs249r_book
interviews/vault/scripts/fix_yaml_hygiene.py
.py
#!/usr/bin/env python3 """Apply conservative mechanical hygiene fixes to question YAML files.""" from __future__ import annotations import argparse import re from pathlib import Path from typing import Any import yaml VAULT_DIR = Path(__file__).resolve().parents[1] QUESTIONS_DIR = VAULT_DIR / "questions" CODE_SPAN...
205
12,249
cs249r_book
interviews/vault/scripts/validate_generation_gates.py
.py
#!/usr/bin/env python3 """Validate generated StaffML question candidates against release gates. The script is intentionally local and deterministic. It checks the gates that do not require remote model calls: schema, question shape, duplication signals, topic-track applicability, zone-level affinity, chain references,...
245
9,684
cs249r_book
interviews/vault/scripts/migrate_to_hierarchical_layout.py
.py
#!/usr/bin/env python3 """One-shot migration: flat <track>/<id>.yaml -> hierarchical <track>/<area>/<id>.yaml. Reads each YAML's `track` and `competency_area` fields, then moves the file to the corresponding hierarchical path. Idempotent — running on an already-migrated tree is a no-op. Validates pre-flight that ever...
116
3,863
cs249r_book
interviews/vault/scripts/fix_competency_areas.py
.py
#!/usr/bin/env python3 """Phase 0 cleanup: remap malformed `competency_area` values to canonical. The schema's `competency_area` field is documented as "one of 13 canonical areas" but is enforced as a free-form string at the LinkML layer. This left a hole that Gemini-generated questions slipped through: when asked to ...
216
8,729
cs249r_book
interviews/vault/scripts/deep_verify.py
.py
#!/usr/bin/env python3 # STATUS (2026-05-03): preserved as a reference pattern — see vault/scripts/DEPRECATED.md # §"Preserved for adaptation". Unique among the audit scripts: Claude Opus + # extended thinking, asks the model to SHOW ITS WORK on every napkin-math claim. # Useful as a tiebreaker when audit_corpus_batche...
306
12,509
cs249r_book
interviews/vault/scripts/portfolio_balance_loop.py
.py
#!/usr/bin/env python3 """Plan iterative StaffML portfolio-balancing passes.""" from __future__ import annotations import argparse import json import sys from collections import Counter from pathlib import Path from typing import Any import yaml VAULT_DIR = Path(__file__).resolve().parent.parent ROOT_DIR = VAULT_DI...
237
9,332
cs249r_book
interviews/vault/scripts/verify_math.py
.py
#!/usr/bin/env python3 """Gemini-powered math verification pass for StaffML corpus. Sends chunks of questions to gemini-3.1-pro-preview for independent math verification. Each call checks ~25 questions. With 250 calls/day quota, this covers ~6,250 questions per day. Usage: python3 scripts/verify_math.py ...
231
8,006
cs249r_book
interviews/vault/scripts/generate_batch.py
.py
#!/usr/bin/env python3 """Fast parallel batch generator — fills ALL topic×track×zone gaps. Reads pre-computed jobs from /tmp/staffml_jobs.json and spawns gemini CLI calls in parallel, writing results to a temp file. Usage: python3 generate_batch.py --workers 40 --output /tmp/batch_all.json """ import argparse im...
152
5,730
cs249r_book
interviews/vault/scripts/render_visuals.py
.py
#!/usr/bin/env python3 """Render question visuals to ship-ready SVG. The schema the website cares about is minimal:: visual: kind: svg # always svg — that's what the website ships path: <id>.svg # the static asset alt: <text> caption: <text> # Build metadata ...
276
10,450
cs249r_book
interviews/vault/scripts/validate_questions.py
.py
#!/usr/bin/env python3 """Parallel Gemini validation of corpus questions. Validates math correctness, factual accuracy, and question quality using gemini-3.1-pro-preview across parallel batches. Usage: python3 validate_questions.py # Validate all 4,779 questions python3 validate_questions.p...
363
14,738
cs249r_book
interviews/vault/scripts/audit_yaml_corpus.py
.py
#!/usr/bin/env python3 """Read-only deterministic audit for StaffML question YAML files. This script intentionally ignores historical LLM audit artifacts. It validates the current YAML corpus against the local schema and authoring conventions, then writes a JSONL issue log plus a short Markdown summary. """ from __fu...
459
16,595
cs249r_book
interviews/vault/scripts/promote_validated.py
.py
#!/usr/bin/env python3 """Promote LLM-judge-PASS draft YAMLs to status:published. Reads the latest llm_judge summary.json files, collects every question ID that received a PASS verdict and is still a status:draft, and flips its lifecycle fields to the canonical published shape: status: draft -> publis...
131
4,356
cs249r_book
interviews/vault/scripts/analyze_coverage_gaps.py
.py
#!/usr/bin/env python3 """Coverage-gap analyzer for the StaffML question corpus. Surfaces where the corpus is thin so generation can be aimed precisely rather than scattered. Output is a structured report that downstream batched generation (`gemini_cli_generate_questions.py`) can consume. The dimensions analyzed: ...
461
19,642
cs249r_book
interviews/vault/scripts/rename_legacy_ids.py
.py
#!/usr/bin/env python3 """Rename cohort-tagged legacy IDs to clean <track>-NNNN form. The 2026-04-21 ID_SCHEMES.md retired the cohort-tagged form (cloud-fill-*, cloud-cell-*, etc.) but kept legacy IDs unchanged because rewriting them would have broken ~3,100 chain references and external bookmarks. This script applie...
243
9,396
cs249r_book
interviews/vault/visuals/mobile/mobile-1978.py
.py
import os import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(5,4)) ax.bar(['TCM Hit', 'LPDDR5x Spill'], [1, 100], color=['#d4edda', '#fdebd0'], edgecolor=['#3d9e5a', '#c87b2a']) ax.set_ylabel('Access Latency (ns, Approx)') ax.set_title('Impact of TCM Miss on NPU') plt.savefig(os.environ['VISUAL_OUT_PATH'],...
7
355
cs249r_book
interviews/vault/visuals/mobile/mobile-1965.py
.py
import os import matplotlib.pyplot as plt tiers = ['UFS 4.0', 'LPDDR5X', 'NPU SRAM'] bw = [4, 60, 1000] plt.figure(figsize=(6, 3)) plt.barh(tiers, bw, color=['#c87b2a', '#4a90c4', '#3d9e5a']) plt.xlabel('Bandwidth (GB/s, log scale)') plt.xscale('log') plt.title('Mobile Memory Tier Bandwidths') plt.savefig(os.environ....
12
389
cs249r_book
interviews/vault/visuals/mobile/mobile-1890.py
.py
import os import numpy as np import matplotlib.pyplot as plt n = np.arange(0, 10) rho = 0.75 prob = (1 - rho) * (rho**n) plt.figure(figsize=(6,4)) plt.bar(n[:5], prob[:5], color='#cfe2f3', label='NPU') plt.bar(n[5:], prob[5:], color='#fdebd0', label='CPU Fallback') plt.xlabel('Tasks in System') plt.ylabel('Probability...
15
447
cs249r_book
interviews/vault/visuals/mobile/mobile-1914.py
.py
import os import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(6,2)) ax.broken_barh([(0,2)], (0,1), facecolors='#cfe2f3', label='ISP Write') ax.broken_barh([(2,2)], (0,1), facecolors='#d4edda', label='GPU Convert') ax.broken_barh([(4,3)], (0,1), facecolors='#fdebd0', label='NPU Infer') ax.set_xlim(0, 8) ax.s...
12
501
cs249r_book
interviews/vault/visuals/mobile/mobile-1909.py
.py
import os import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(6,2)) ax.broken_barh([(0,13), (20,13)], (0, 5), facecolors='#cfe2f3', label='Sleep') ax.broken_barh([(13,2), (33,2)], (0, 200), facecolors='#fdebd0', label='Transient') ax.broken_barh([(15,5), (35,5)], (0, 450), facecolors='#d4edda', label='Activ...
11
510
cs249r_book
interviews/vault/visuals/mobile/mobile-1979.py
.py
import os import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(figsize=(5,2)) ax.barh(['Sequential'], [2], color='#d4edda', edgecolor='#3d9e5a', label='ISP') ax.barh(['Sequential'], [3], left=[2], color='#cfe2f3', edgecolor='#4a90c4', label='NPU') ax.legend() ax.set_xlabel('Latency (ms)') plt.savef...
9
403
cs249r_book
interviews/vault/visuals/mobile/mobile-1912.py
.py
import os import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(5,3)) ax.bar(['FP16', 'INT4'], [40, 10], color='#cfe2f3', edgecolor='#4a90c4') ax.axhline(16, color='red', linestyle='--', label='SRAM Limit') ax.set_ylabel('Model Size (MB)') ax.legend() out = os.environ.get('VISUAL_OUT_PATH', 'out.svg') plt.sav...
9
364
cs249r_book
interviews/vault/visuals/mobile/mobile-1887.py
.py
import os import matplotlib.pyplot as plt ctx = [1000, 2000, 3814, 5000] mem = [128, 256, 500, 640] plt.figure(figsize=(6,4)) plt.bar([str(c) for c in ctx], mem, color='#cfe2f3', edgecolor='#4a90c4') plt.axhline(500, color='red', linestyle='--', label='500MB Limit') plt.xlabel('Sequence Length') plt.ylabel('Memory (MB...
13
448
cs249r_book
interviews/vault/visuals/mobile/mobile-1985.py
.py
import os import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(figsize=(6,2)) ax.barh(['Memory'], [1.5], color='#d4edda', edgecolor='#3d9e5a', label='Weights (1.5GB)') ax.barh(['Memory'], [2.5], left=[1.5], color='#cfe2f3', edgecolor='#4a90c4', label='KV Cache (2.5GB)') ax.set_xlim(0, 4.5) ax.axvli...
11
533
cs249r_book
interviews/vault/visuals/mobile/mobile-1895.py
.py
import os import matplotlib.pyplot as plt import numpy as np t = np.linspace(0, 200, 400) active = np.where(t % 50 < 5, 1, 0) plt.plot(t, active, color='#3d9e5a', drawstyle='steps-pre') plt.xlabel('Time (ms)') plt.yticks([0, 1], ['Sleep', 'Active']) plt.ylim(-0.2, 1.2) out = os.environ.get('VISUAL_OUT_PATH', 'out.svg')...
11
372
cs249r_book
interviews/vault/visuals/mobile/mobile-1872.py
.py
import matplotlib.pyplot as plt import numpy as np import os lambda_rate = np.linspace(0.1, 2.4, 50) mu = 1 / 0.4 # 2.5 req/s # M/D/1 wait time: rho = lambda/mu. W_q = (rho * service_time) / (2 * (1 - rho)) rho = lambda_rate / mu wait_time = (rho * 0.4) / (2 * (1 - rho)) fig, ax = plt.subplots(figsize=(6, 4)) ax.plot...
22
782
cs249r_book
interviews/vault/visuals/mobile/mobile-1901.py
.py
import os import matplotlib.pyplot as plt import numpy as np t = np.linspace(0, 10, 200) power = np.where(t % 1 < 0.1, 50, 2) plt.plot(t, power, color='#c87b2a', drawstyle='steps-pre') plt.xlabel('Time') plt.ylabel('Power (mW)') plt.ylim(0, 60) out = os.environ.get('VISUAL_OUT_PATH', 'out.svg') plt.savefig(out, format=...
11
347