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/tools/audit/fmt/codemod_design_b_rates.py | .py | #!/usr/bin/env python3
"""Normalize fixed-unit rate/FLOP output names and refs.
This is the Design-B companion for output-name semantics. It is intentionally
unit-driven, not suffix-driven: the displayed unit is inferred from the
formatter call, then the export name is updated so the token before ``_str``
matches what... | 548 | 21,278 |
cs249r_book | book/tools/audit/fmt/fix_spurious_prose.py | .py | #!/usr/bin/env python3
"""Fix fmt() calls whose rendered output triggers spurious-.0 prose flags.
See ``fmt/README.md`` for the full chapter workflow.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
CELL_START = re.compile(r"^```\{python\}")
CELL_END = re.compile(r"^```\s*$")
FM... | 129 | 4,256 |
cs249r_book | book/tools/audit/fmt/codemod_design_b_multipliers.py | .py | #!/usr/bin/env python3
"""Design B codemod for fmt_multiple exports and inline refs.
Reads the frozen inventory from ``inventory_design_b_rates.py`` and performs
only the mechanical part of Design B:
* ``foo_str = fmt_multiple(...)`` -> ``foo_mult_str = fmt_multiple(...)``
* ``foo_multiplier_str`` / ``foo_multiple_st... | 169 | 5,421 |
cs249r_book | book/tools/audit/fmt/run_percent_lane.py | .py | #!/usr/bin/env python3
"""
run_percent_lane.py — move ``fmt(x, suffix='%'|' percent')`` into the guarded
``fmt_percent`` formatter with a BYTE-IDENTICAL acceptance gate (WS1 percent).
The migration is value- and prose-preserving by construction:
cell: X = fmt(x, …, suffix='%') → X = fmt_percent((x)/100, …... | 225 | 9,082 |
cs249r_book | book/tools/audit/fmt/audit_prose_semantics.py | .py | #!/usr/bin/env python3
"""
audit_prose_semantics.py — read the book the way a reader does and flag prose
that is wrong once the LEGO values are substituted in.
`fmt_prose_contract.py` proves the *formatter* and prose agree about who owns a
glyph (static, AST-level). This tool is complementary and operates on the
**ren... | 189 | 7,407 |
cs249r_book | book/tools/audit/fmt/run_unit_lane.py | .py | #!/usr/bin/env python3
"""
run_unit_lane.py — migrate clean Quantity-backed unit suffixes to fmt_qty.
This lane intentionally handles only the low-risk, mechanically provable shape:
cell: X = fmt(q.m_as(UNIT), ..., suffix=" UNIT") -> X = fmt_qty(q, UNIT, ...)
The existing lane engine accepts a rewrite only wh... | 71 | 2,489 |
cs249r_book | book/tools/audit/index/check_xref_resolves.py | .py | #!/usr/bin/env python3
r"""
book-index-xref-resolves hook.
Fails if any \index{X|see{Y}} or \index{X|seealso{Y}} target Y doesn't
resolve to a real main entry in the corpus.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
ROOT = Path.cwd()
CONTENT = ROOT / "book" / "quarto" / "con... | 53 | 1,725 |
cs249r_book | book/tools/audit/index/audit.py | .py | #!/usr/bin/env python3
"""
Index audit — produces 4 reports per the project index rules plan.
Run from a MLSysBook worktree root:
python3 .claude/_reviews/index_audit_2026-05-02/audit.py
Outputs (CSV) in this same directory:
coverage_gaps.csv — Phase A: under-indexed concepts
singleton_classifier.csv... | 461 | 16,998 |
cs249r_book | book/tools/audit/index/check_tag_placement.py | .py | #!/usr/bin/env python3
r"""
book-index-tag-placement hook.
Fails if any \index{} is placed inside a structural element where it
breaks formatting:
- Inside opening **bold** span (V1)
- Inside *italic* span (V2)
- Inside `code` span (V3)
- On heading line (V4)
- On callout fence (V5) — extends existing book-c... | 93 | 3,118 |
cs249r_book | book/tools/audit/index/format_audit.py | .py | #!/usr/bin/env python3
r"""
Phase C.1 — formatting violation detector.
Scans every body-prose .qmd and reports \index{} placements that violate
formatting rules:
V1. \index{} inside **bold** span
V2. \index{} inside *italic* span
V3. \index{} inside `code` span
V4. \index{} on heading line (#+)
V5. \index{} ... | 176 | 6,556 |
cs249r_book | book/tools/audit/index/check_anti_patterns.py | .py | #!/usr/bin/env python3
r"""
book-index-anti-patterns hook.
Fails (exit 1) if the corpus contains any \index{} anti-pattern from
the project index rules §9. Run from repo root.
Anti-patterns checked:
- Sub-subentries (A!B!C)
- Author-year subentries
- et al. subentries
- Generic-bare entries (Algorithm, Archit... | 127 | 4,290 |
cs249r_book | book/tools/audit/checks/longtable_continuity.py | .py | """Check: long pipe / HTML tables that should declare longtable handling.
Rule: PDF-output integrity — the print build (LuaLaTeX) needs `longtable`
handling on any table that exceeds one printed page. Without it:
1. The table-caption counter restarts on the continuation page, so the
same table is numbered twic... | 347 | 14,780 |
cs249r_book | book/tools/audit/checks/source_citations.py | .py | """Check: Source-attribution formatting in prose and captions.
This is the binder-native replacement for the old `manage_sources.py`
one-off. It enforces the small set of source-attribution conventions the
book uses in figure captions, table captions, listings, and the rare
body-prose source note:
- `Source:` is capi... | 248 | 9,018 |
cs249r_book | book/tools/audit/checks/lowercase_prose_references.py | .py | """Check: capitalized 'Chapter 12', 'Section 3.2' etc. in body prose.
Rule: book-prose-merged.md section 10.4
Lowercase chapter/section/figure/table words when written by hand.
Quarto's @sec-/@fig-/@tbl-/@eq- references handle this automatically.
Detection: "Chapter 12", "Section 3.2", "Figure 1.1", "Table 5"... | 127 | 4,114 |
cs249r_book | book/tools/audit/checks/latin_running_text.py | .py | """Check: Latin abbreviations in running text (§10.6).
Rule: book-prose-merged.md section 10.6
"In running text, prefer English to Latin abbreviations":
- "for example" not e.g.
- "that is" not i.e.
- "and so on" not etc.
The Latin abbreviations are acceptable inside parentheses,
... | 288 | 10,688 |
cs249r_book | book/tools/audit/checks/percent_symbol.py | .py | """Check: '%' symbol in body prose should be 'percent'.
Rule: book-prose-merged.md section 2 + section 10.2
Spell out "percent" in body prose; '%' is OK inside tables, equations
(`$60\\%$`), code blocks, and figure captions.
Two forms to detect:
1. Hard-coded: '94%' -> '94 percent'
2. Inline Python: '`{py... | 164 | 5,917 |
cs249r_book | book/tools/audit/checks/abbreviation_first_use.py | .py | """Check: abbreviation first-use policy (§10.5).
Rule: book-prose-merged.md section 10.5 / abbreviations.md
Most specialized abbreviations expand on first use in each chapter.
Each `.qmd` file is treated as one chapter for the ordinary chapter-level
abbreviation set. The check walks the file
once and for each ab... | 550 | 21,911 |
cs249r_book | book/tools/audit/checks/index_placement.py | .py | """Check: `\\index{}` placement — forbidden contexts.
Rule: index.md §1 (placement) + book-prose-merged.md §7 (LaTeX in attribute strings)
"Place the tag immediately after the term IN BODY PROSE. Not before,
not at the end of the paragraph."
This check enforces the converse: `\\index{...}` must NEVER appear ... | 171 | 6,575 |
cs249r_book | book/tools/audit/checks/duplicate_citation.py | .py | r"""Check: duplicate Pandoc citation keys within a close window.
Rule: .claude/rules/citation.md (duplicate citation density)
The same `[@key]` cited 3+ times within a tight window (~50 lines)
inside one file means the cluster needs editorial review. This is not
a deletion rule. Keep repeats that anchor d... | 228 | 8,382 |
cs249r_book | book/tools/audit/checks/compound_prefix.py | .py | """Check: pre-/non- compound prefix close-up.
Rule: book-prose-merged.md section 10.8
Close up to remove the hyphen — STRICT 6-term list (no extrapolation):
pre-training -> pretraining
pre-trained -> pretrained
pre-deployment -> predeployment
pre-learning -> prelearning
pre-processing -> p... | 223 | 8,120 |
cs249r_book | book/tools/audit/checks/h3_titlecase.py | .py | """Check: H3+ headings in title case (should be sentence case).
Rule: book-prose-merged.md section 10.9
H1 and H2: headline style (capitalize principal words)
H3 and below: sentence style (first word + proper nouns only)
Detection: any heading at H3/H4/H5/H6 where more than one word starts with
a capital lett... | 586 | 23,726 |
cs249r_book | book/tools/audit/checks/__init__.py | .py | """Audit check functions, one module per category.
Each check module exports a single function with the signature:
def check(file_path: Path, text: str, lines: list[str]) -> list[Issue]
where Issue is the dict format defined in book/tools/audit/ledger.py.
The scanner imports all check modules in this package and... | 10 | 337 |
cs249r_book | book/tools/audit/checks/caption_orphan.py | .py | """Check: a `: caption {#tbl-...}` line sandwiched between two `:::` close fences.
Rule: EPUB build integrity — Pandoc's EPUB writer treats a caption as orphan
when it is separated from its table by a closing div fence and then followed
by another closing div fence. The label never registers, `@tbl-` xrefs go
unresolv... | 162 | 5,494 |
cs249r_book | book/tools/audit/checks/bare_attribution.py | .py | r"""Check: bare narrative attribution `Author et al. YEAR` without `[@cite]`.
Rule: book-prose-merged.md section 5 (Footnotes, Citations & Index → Citations
& References, "Bare Attributions are Forbidden")
Hand-typed author/year text in body prose or footnote prose is the same
anti-pattern as the manual+brack... | 379 | 16,221 |
cs249r_book | book/tools/audit/checks/alt_text_style.py | .py | """Check: §10.12 alt-text must follow §10.3 concept-term rules.
Rule: book-prose-merged.md section 10.12
"Alt-text strings live inside `fig-alt="..."` attributes and are
easy to forget during prose passes — but they ARE body prose for
screen readers. The same Section 1, 2, and 10 prose rules apply:
... | 251 | 9,381 |
cs249r_book | book/tools/audit/checks/table_caption.py | .py | """Check: every markdown pipe table has a caption + {#tbl-...} ID.
Rule: book-prose-merged.md section 6 (Visuals & Assets) — Table Formatting
Tables that carry quantitative content (numbers, multipliers, comparisons)
MUST have a caption + `@tbl-` ID, regardless of whether they sit in body
text or inside a... | 178 | 7,113 |
cs249r_book | book/tools/audit/checks/unresolved_xref.py | .py | """Check: unresolved Quarto cross-references (`?@` literal in rendered output).
Defect class: when a Quarto cross-reference like `@sec-foo` fails to resolve,
the rendered HTML/PDF shows the literal text `?@sec-foo` (with a question
mark prefix). Source-level scanners typically miss this because the source
`@sec-foo` l... | 275 | 11,200 |
cs249r_book | book/tools/audit/checks/concept_term_capitalization.py | .py | """Check: §10.3 concept terms must be lowercase in body prose.
Rule: book-prose-merged.md section 10.3
"Concept terms that are NOT proper nouns must be lowercase in body
prose, even when they were capitalized in pre-round-1 drafts."
The §10.3 lowercase list includes: iron law, degradation equation,
verificat... | 609 | 26,409 |
cs249r_book | book/tools/audit/checks/vs_period.py | .py | """Check: bare 'vs' should be 'vs.' (with period).
Rule: book-prose-merged.md section 1 + section 10.10
"vs. always with period" — never "versus" or bare "vs".
Auto-fixable: yes. The proven regex from pass 10b (commit c3e328c0b):
only replace when bracketed by single space + alphabetic word on both
sides,... | 99 | 3,232 |
cs249r_book | book/tools/audit/checks/layout_proxies.py | .py | r"""Check: source-level proxies for rendered-PDF layout defects.
Scanner H detects source-level patterns that *correlate* with bad layout
in the rendered PDF/HTML. The defects this scanner targets are inherently
visual — page breaks, stranded headings, widow/orphan paragraphs, runt
callouts — so the source-level rules... | 446 | 18,616 |
cs249r_book | book/tools/audit/checks/acknowledgements_spelling.py | .py | """Check: 'Acknowledgements' -> 'Acknowledgments' (American spelling).
Rule: book-prose-merged.md section 10.7 / 10.15
Per Webster's 11th: Acknowledgments (American) is the canonical form.
The QMD filename can stay as acknowledgements.qmd (path not rendered);
only the rendered heading text needs to change.
Auto-fixa... | 79 | 2,349 |
cs249r_book | book/tools/audit/checks/notation_consistency.py | .py | """Check: notation consistency against the Notations chapter(s).
This is a conservative, high-signal scanner intended for CI:
- Emits OPEN issues only for high-confidence convention violations.
- Emits DEFERRED issues for context-dependent collisions (review-only).
Ground truth definitions live in:
- book/quarto/co... | 560 | 21,455 |
cs249r_book | book/tools/audit/checks/math_notation_render.py | .py | r"""Check: math-notation rendering issues that break Pandoc/Quarto output.
Five known failure modes from prior copyedit findings (commits bcc4527f4a
"Normalize math rendering across QMD files" and 42209c08b0 "wave 4 — audit
backlog cleanup"):
1. **Adjacent math spans** (`$\sim$$15%$`): two abutting inline-math spans
... | 375 | 16,342 |
cs249r_book | book/tools/audit/checks/footnote_numbering.py | .py | """Check: footnote reference / definition integrity within a single file.
Quarto footnotes come in two shapes in this book:
1. Named, two-part: a reference `[^id]` in body prose pointing at a
definition `[^id]: explanatory text` later in the same file.
2. Inline: `^[inline footnote text]` — self-contained, n... | 325 | 13,898 |
cs249r_book | book/tools/audit/checks/sec_slug_placement.py | .py | """Check: Quarto crossref ID ({#sec-...}, {#fig-...}, etc.) at end of body
prose, where it does not attach to anything.
Background. In Quarto/Pandoc, the `{#sec-foo}` syntax is a header attribute.
It is recognized when it appears:
- immediately after an ATX heading `# Title {#sec-foo}`
- on a fence... | 345 | 12,697 |
cs249r_book | book/tools/audit/checks/binary_units.py | .py | """Check: binary units (GiB, TiB, KiB, MiB) in body prose.
Rule: book-prose-merged.md section 1
"Never binary units in prose. Write `GB` and `TB`, not `GiB` or `TiB`."
Auto-fixable: NO. The fix depends on whether the source value was a binary
or decimal quantity. A GiB -> GB conversion changes the number by ~7%. ... | 84 | 2,700 |
cs249r_book | book/tools/audit/checks/bibliography_hygiene.py | .py | """Check: Bibliography hygiene (§10.13 / §5).
Rule: book-prose-merged.md section 10.13 and section 5
"Every `@inproceedings` must have a `publisher` field.
Every `@article` must have a `journal` field.
Include `pages` and `doi` when available.
No em dashes for repeat author names.
Letter-by-le... | 345 | 10,014 |
cs249r_book | book/tools/audit/float_explanation/scan_floats.py | .py | #!/usr/bin/env python3
"""Float-explanation audit scanner (flag-only, no edits).
Enumerates floats in a chapter .qmd and assembles, for each one, the CONTEXT BUNDLE a
human/judging pass needs to rule on whether the float is *explained* in its neighborhood
(comprehension), not merely whether the ref resolves (covered b... | 270 | 10,695 |
cs249r_book | book/tools/audit/release/au_query_coverage.py | .py | #!/usr/bin/env python3
"""Phase A2 — AU query response coverage.
Reads ``11_au_queries/data/au_queries.json`` (200 highlights), filters down
to entries whose ``content`` actually starts with ``AU:`` / ``Au:`` /
``Comp`` (the true AU/Comp queries; the rest are mis-classified
em-dash/spacing notes), then assigns each qu... | 150 | 6,632 |
cs249r_book | book/tools/audit/release/alt_text_coverage.py | .py | #!/usr/bin/env python3
"""Phase A3 — alt-text coverage diff.
Reads ``07_alt_text/data/alt_text_edits_fixed.json`` (212 entries with a
``label`` like ``fig-ai-timeline`` and the editor-approved ``alt_text``
string), then walks ``book/quarto/contents/vol1/**/*.qmd`` looking for
``fig-alt="..."`` (or ``fig-alt: "..."``) ... | 163 | 6,246 |
cs249r_book | book/tools/audit/release/classify_annotations.py | .py | #!/usr/bin/env python3
"""Phase A1 — classify all 18,439 vol1 annotations into editorial buckets.
Reads ``00_overview/data/all_annotations.json`` from the configured
release-audit data root and tags every entry with one of the buckets below plus a
``needs_locator`` flag indicating whether Phase B has to find the chang... | 323 | 10,511 |
cs249r_book | book/tools/audit/release/__init__.py | .py | """MIT Press Release Deep Audit scripts.
Phase A scripts produce ground-truth ledgers from already-extracted editor
JSON inputs. By default, inputs are read from
``book/tools/audit/release/data/`` and outputs are written under
``book/quarto/_build/release_audit/``. Set ``MLSYSBOOK_RELEASE_AUDIT_DATA``
or ``MLSYSBOOK_R... | 11 | 433 |
cs249r_book | book/tools/audit/release/front_matter_coverage.py | .py | #!/usr/bin/env python3
"""Phase A4 — front-matter tracked-change coverage diff.
Reads ``10_front_matter/data/front_matter_changes.json`` (53 entries: 26
insertions, 25 deletions, 2 comments) and verifies each against the
current QMD source under ``book/quarto/contents/vol1/frontmatter/`` (and
shared ``book/quarto/cont... | 196 | 7,762 |
cs249r_book | book/tools/audit/release/programmatic_locate.py | .py | #!/usr/bin/env python3
"""Programmatic locator for Phase B1.
Replaces the per-chapter LLM subagents with a deterministic, reproducible
checker that judges every ``needs_locator`` annotation against the live
QMD source on the dev branch.
For each entry the locator picks an evidence string ("expected after"
text) deriv... | 345 | 12,962 |
cs249r_book | book/tools/audit/release/build_locator_bins.py | .py | #!/usr/bin/env python3
"""Phase B1 (prep) — build per-chapter locator input bins.
Reads ``vol1-annotations-ground-truth.json``, filters to entries with
``needs_locator == True``, and writes one input file per QMD chapter to
``16_release_audit/scripts/locator-input/<bin>.json``. Each bin holds at
most ``MAX_PER_BIN`` e... | 179 | 7,763 |
cs249r_book | book/tools/audit/release/scanner_baseline.py | .py | #!/usr/bin/env python3
"""Phase A6 — re-run the audit infrastructure against current dev HEAD.
Captures three measurements that together constitute the audit baseline:
1. ``book/tools/audit/scan.py --scope vol1|vol2`` ledger counts
2. The 6 detector self-tests (123/123 expected)
3. ``./book/binder check bib --json`` ... | 222 | 8,148 |
cs249r_book | book/tools/audit/release/vol2_baseline.py | .py | #!/usr/bin/env python3
"""Phase A5 — figure audit inventory (pointer-only).
The figure-caption verification work is being run separately by the
author. This script just records the inventory of HIGH/MEDIUM/LOW
figures per volume and chapter so the coverage report can quote the
baseline numbers without re-running the a... | 125 | 4,380 |
cs249r_book | book/tools/audit/release/paths.py | .py | """Shared paths for release-audit helper scripts."""
from __future__ import annotations
import os
from pathlib import Path
def _env_path(name: str, default: Path) -> Path:
raw = os.environ.get(name)
return Path(raw).expanduser().resolve() if raw else default.resolve()
REPO_ROOT = _env_path(
"MLSYSBOOK... | 31 | 743 |
cs249r_book | book/quarto/publish/compress_epub.py | .py | #!/usr/bin/env python3
"""
EPUB Compression Tool for MLSysBook
This tool compresses EPUB files by optimizing embedded images while maintaining
EPUB format compliance. It extracts the EPUB, compresses images, and repacks
the archive following EPUB specifications.
Usage:
python compress_epub.py --input input.epub -... | 436 | 15,243 |
cs249r_book | book/quarto/publish/compress_pdf.py | .py | #!/usr/bin/env python3
"""
PDF Compression Tool for MLSysBook
This tool compresses PDF files using Ghostscript with optimized settings for
academic textbooks. It reduces file size while maintaining readability and
print quality suitable for educational content.
Usage:
python compress_pdf.py --input input.pdf --ou... | 387 | 13,470 |
cs249r_book | book/quarto/calc/viz.py | .py | """
Backward-compat shim for Quarto build tooling.
Import visualization helpers from mlsys.viz.
"""
from mlsys.viz import * # noqa: F401,F403
| 7 | 144 |
cs249r_book | book/quarto/scripts/epub_postprocess.py | .py | #!/usr/bin/env python3
"""
Cross-platform EPUB post-processor wrapper.
Extracts EPUB, fixes cross-references, and re-packages it.
Works on Windows, macOS, and Linux.
"""
import re
import sys
import shutil
import tempfile
import zipfile
from pathlib import Path
# Import the resolve_cross_references module functions d... | 507 | 18,578 |
cs249r_book | book/quarto/scripts/revert_times_multipliers.py | .py | #!/usr/bin/env python3
"""
One-off: fix malformed dimensions and revert multiplier/range × to N$\\times$ form.
Run order:
1. Fix malformed dimensions: $N\\times$ M -> $N\\times M$ (so both numbers in one math span).
2. Revert range: $N\\text{--}M\\times$ -> N--M$\\times$
3. Revert single number: $N\\times$ -> N$... | 60 | 1,871 |
cs249r_book | book/quarto/scripts/save_latex_log.py | .py | #!/usr/bin/env python3
"""Post-render script: save LaTeX build log to the output directory.
Quarto deletes intermediate files (including index.log) after post-render
scripts finish. This script copies the log while it still exists, so the
binder post-build validator can scan it for overfull hbox, underfull vbox,
and o... | 69 | 2,421 |
cs249r_book | book/quarto/scripts/verify_rendered_xrefs.py | .py | #!/usr/bin/env python3
"""
Post-render guard: fail the build if any unresolved cross-reference literal
(`?@xxx-yyy`) remains in the rendered output or generated search index.
WHY THIS EXISTS
---------------
vol1/vol2 build as `project.type: website`, so Quarto cannot resolve
cross-chapter `@xref`s natively. `scripts/r... | 179 | 6,825 |
cs249r_book | book/quarto/scripts/resolve_cross_references.py | .py | #!/usr/bin/env python3
"""
Post-render step: resolve cross-chapter cross-references in HTML output.
WHY THIS SCRIPT EXISTS:
-----------------------
vol1 and vol2 build as `project.type: website` (each chapter is its own Pandoc
invocation), so Quarto cannot resolve `@sec-`, `@fig-`, `@tbl-`, `@eq-`, `@lst-`,
`@pri-`, o... | 896 | 35,167 |
cs249r_book | book/quarto/scripts/clean_svgs.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SVG Cleanup Script - Cross-Platform Version
============================================
Removes control characters from SVG files that can cause rendering issues
in browsers and other tools. Control characters are often introduced by
LaTeX -> SVG conversion tools.
Th... | 308 | 10,950 |
cs249r_book | book/quarto/scripts/fix_lightbox_paths.py | .py | #!/usr/bin/env python3
"""
Post-render step: fix lightbox hrefs for mediabag SVGs.
Quarto's lightbox feature generates <a href="HASH.svg"> for images stored in
the mediabag directory, but the actual file lives at
chapter_files/mediabag/HASH.svg. The <img src> inside the anchor is correct;
only the lightbox href is wro... | 82 | 2,272 |
cs249r_book | book/quarto/scripts/fix_times_math.py | .py | #!/usr/bin/env python3
"""
Fix inline math for dimension-like N×M only (two numbers) in QMD files.
When a digit is adjacent to $ (e.g. 224$\\times$224), some Quarto/Pandoc
configurations fail to open math mode. Wrapping the full expression in one
math span (e.g. $224\\times224$) fixes rendering. Only dimension pattern... | 51 | 1,612 |
cs249r_book | book/quarto/scripts/check_references.py | .py | #!/usr/bin/env python3
"""
check_references.py — Bibliography completeness validator.
Scans each volume's QMD chapters for [@citation] keys and verifies every key
is defined in the shared book bibliography at contents/references.bib.
Usage:
# Check only (no changes):
python3 scripts/check_references.py
#... | 179 | 6,258 |
cs249r_book | book/quarto/scripts/mit_press/generate_figure_list.py | .py | #!/usr/bin/env python3
"""
Figure List Generator for MIT Press
Usage:
Pre-render: python generate_figure_list.py --clear
Post-render: python generate_figure_list.py
Pre-render clears stale LaTeX data from previous builds.
Post-render creates a complete figure list with:
- Figure numbers and page numbers (from ... | 416 | 15,421 |
cs249r_book | book/tests/test_lego_dead_code.py | .py | from book.cli.checks.lego_dead_code import audit_file
def _write(tmp_path, body, prose=""):
chapter = tmp_path / "chapter.qmd"
chapter.write_text(
"\n```{python}\n# LEGO\n"
+ body
+ "\n```\n\n"
+ prose
+ "\n",
encoding="utf-8",
)
return chapter
def tes... | 48 | 1,424 |
cs249r_book | book/tests/test_fmt_semantic_suffix.py | .py | from book.cli.checks.fmt_semantic_suffix import audit
def _write(tmp_path, body):
chapter = tmp_path / "chapter.qmd"
chapter.write_text(
"\n```{python}\nfrom mlsysim.fmt import fmt, fmt_int, fmt_usd\n"
+ body
+ "\n```\n",
encoding="utf-8",
)
return chapter
def test_fl... | 90 | 2,855 |
cs249r_book | book/tests/test_codemod_fmt.py | .py | """Tests for the paired multiplier codemod (provable lane + queue lane)."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools/audit/fmt"))
import ast # noqa: E402
from codemod_fmt import ( # noqa: E402
_rewrite_call_to_multiple, _patch_prose, scan_file,
... | 399 | 16,362 |
cs249r_book | book/tests/test_markdown_list_spacing.py | .py | """Tests for Markdown list spacing around bold lead-in paragraphs."""
from book.cli.checks.markdown_list_spacing import check_text
def test_flags_bold_leadin_before_bullet_without_blank():
issues = check_text(
"**Step 2**: Add IT support power and apply PUE.\n"
"- Facility PUE: 1.12\n"
)
... | 56 | 1,521 |
cs249r_book | book/tests/test_lego_prose_units.py | .py | """Tests for closed LEGO export ↔ prose unit duplication checker."""
from pathlib import Path
from book.cli.checks.lego_prose_units import check_file
def _write(tmp_path, body: str) -> Path:
p = tmp_path / "chapter.qmd"
p.write_text(body, encoding="utf-8")
return p
CELL = """```{{python}}
#| echo: fals... | 114 | 3,132 |
cs249r_book | book/tests/test_mlsysim_registry_coverage.py | .py | """Vol I/II calculations must stay wired to MLSysIM registries.
The book is allowed to have illustrative scenario constants in a chapter, but
model, hardware, dataset, platform, system, infrastructure, literature, and ops
objects used by rendered calculations should resolve through the package API.
"""
from __future_... | 148 | 4,996 |
cs249r_book | book/tests/test_audit_prose_semantics.py | .py | """Regression tests for the composite-prose semantic scanner.
These guard against the scanner silently rotting into a no-op: each red-flag
pattern must FIRE on a known-bad rendered sentence and stay quiet on good ones.
"""
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(... | 85 | 2,979 |
cs249r_book | book/tests/test_pdf_layout_checks.py | .py | """Tests for PDF overfull-box and margin-overflow detection.
Covers:
* Log-based vertical-overflow gate (Overfull \\vbox) — blocking when severe,
because it corresponds to rendered content exceeding page geometry.
* The pure margin-overflow geometry used by `binder layout margins`.
The log-based hbox gate and... | 857 | 27,691 |
cs249r_book | book/tests/test_mitpress_terms.py | .py | from book.cli.checks.mitpress_terms import find_in_text
def test_limited_data_set_preserves_hipaa_legal_term():
assert find_in_text("HIPAA permits a limited data set with an agreement.") == []
def test_general_data_set_still_uses_canonical_spelling():
hits = find_in_text("The training data set is versioned.... | 12 | 411 |
cs249r_book | book/tests/test_binder_lego_scope_paths.py | .py | """Binder LEGO/fmt scopes respect --path and expose formatter prose contract."""
from __future__ import annotations
import json
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
ONE_QMD = "book/quarto/contents/vol1/index.qmd"
def _binder_json(*args: str) -> dict:
proc = sub... | 54 | 1,461 |
cs249r_book | book/tests/test_inline_python_math_spans.py | .py | from book.cli.commands.validate import (
_inline_python_latex_operator_warnings,
_inline_python_math_spans,
)
def test_inline_python_between_math_spans_is_not_inside_math():
line = "Training distribution $P_0$: `{python} KLDrift.P0_vec_str`. Serving distribution $P_t$."
assert _inline_python_math_span... | 30 | 1,159 |
cs249r_book | book/tests/test_registry.py | .py | # test_registry.py
# Unit tests for the mlsysim Hardware and Models registries.
import unittest
from mlsysim import Hardware, Models
from mlsysim.core.units import ureg
class TestMLSysRegistry(unittest.TestCase):
def test_hardware_ridge_points(self):
"""Test that ridge points are calculated correctly and ... | 45 | 1,754 |
cs249r_book | book/tests/test_binder_cli_contract.py | .py | from pathlib import Path
from book.cli.checks.cli_contract import CASES, run_contract
ROOT = Path(__file__).resolve().parents[2]
def test_binder_cli_contract_is_stable():
violations = run_contract(ROOT)
rendered = "\n".join(
f"{v.code}: {v.message}\n{v.context}\n{v.suggestion}"
for v in vi... | 18 | 399 |
cs249r_book | book/tests/test_math_canonical.py | .py | from book.cli.checks.math_canonical import audit
def test_math_canonical_flags_manual_fmt_string_assembly(tmp_path):
chapter = tmp_path / "chapter.qmd"
chapter.write_text(
"""
```{python}
from mlsysim.fmt import fmt, fmt_int
class BadFormatting:
cost_str = "\\\\$" + str(fmt(10, precision=0))
... | 216 | 5,388 |
cs249r_book | book/tests/test_units.py | .py | """
Unit conversion validation for the textbook's physics engine.
Run: python3 book/quarto/mlsys/test_units.py
From: repository root (mlsysbook-vols/)
Catches regressions where pint .to() returns raw base-unit magnitudes
instead of human-readable values (e.g., 312000000000000 instead of 312).
Also validates that ev... | 634 | 28,186 |
cs249r_book | book/tests/test_table_caption_position.py | .py | from types import SimpleNamespace
from book.cli.commands.validate import ValidateCommand
def _command(tmp_path):
return ValidateCommand(
config_manager=SimpleNamespace(book_dir=tmp_path),
chapter_discovery=None,
)
def test_pipe_table_caption_below_table_passes(tmp_path):
qmd = tmp_path ... | 72 | 1,813 |
cs249r_book | book/tests/test_flatten_vol_urls.py | .py | from __future__ import annotations
import subprocess
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
SCRIPT = REPO_ROOT / ".github" / "scripts" / "flatten-vol-urls.sh"
def write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, enc... | 79 | 3,421 |
cs249r_book | book/tests/test_fmt_prose_contract.py | .py | """Tests for the OUTPUT-formatter ↔ prose glyph contract checker."""
from pathlib import Path
from book.cli.checks.fmt_prose_contract import (
build_formatter_map,
check_file,
extract_python_cells,
)
def _write(tmp_path, body: str) -> Path:
p = tmp_path / "c.qmd"
p.write_text(body, encoding="utf-... | 194 | 7,517 |
cs249r_book | book/tests/test_footnote_cross_chapter.py | .py | from types import SimpleNamespace
from book.cli.commands.validate import ValidateCommand
def _command(tmp_path):
return ValidateCommand(
config_manager=SimpleNamespace(book_dir=tmp_path),
chapter_discovery=None,
)
def test_body_footnote_ref_with_colon_is_not_a_definition(tmp_path):
qmd ... | 52 | 1,397 |
cs249r_book | book/tests/test_visible_text.py | .py | """Tests for the fmt-migration visible-text normalizer (Regime-2 equivalence)."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools/audit/fmt"))
from visible_text import to_visible # noqa: E402
def test_multiplier_glyph_relocation_equivalent():
# the core Re... | 52 | 1,569 |
cs249r_book | book/tests/test_appendix_constants.py | .py | """CI gate: appendix assumption-table LEGO cells resolve against live registries."""
from __future__ import annotations
import importlib.util
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
GENERATOR = REPO_ROOT / "book/tools/audit/generate_appendix_constants.py"... | 69 | 2,185 |
cs249r_book | book/tests/test_currency_style.py | .py | from pathlib import Path
from book.cli.checks.currency_style import (
NOTATION_DEFINITION,
audit,
audit_rendered_html,
)
def test_currency_style_allows_single_notation_definition(tmp_path):
notation = tmp_path / "book/quarto/contents/vol1/frontmatter/_notation_body.qmd"
notation.parent.mkdir(pare... | 131 | 4,104 |
cs249r_book | book/tests/test_no_legacy_constant_refs.py | .py | """CI gate: migrated symbols must not be imported from mlsysim.core.constants."""
from __future__ import annotations
import ast
import json
import re
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
MANIFEST_PATH = REPO_ROOT / "book" / "tools" / "audit" / "artifacts" / "registry_migration_man... | 116 | 4,093 |
cs249r_book | book/tests/test_spurious_zero.py | .py | import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools/audit/fmt"))
from spurious_zero import find_spurious_zeros # noqa: E402
def test_unit_bearing_dot_zero_is_not_blanket_suppressed():
text = "The ridge is 153.0 FLOP/byte and the transfer rate is 0.0 MB/s."
... | 34 | 1,135 |
cs249r_book | book/tests/test_footnote_caps.py | .py | from __future__ import annotations
import importlib.util
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "book" / "tools" / "scripts" / "mit_press" / "check_footnote_caps.py"
spec = importlib.util.spec_from_file_location("check_footnote_caps_for_test", SCRIPT)
footnote... | 93 | 2,858 |
cs249r_book | book/tests/test_algorithm_xref_case.py | .py | from types import SimpleNamespace
from book.cli.commands.validate import ValidateCommand
def _run_xref_case(tmp_path, body):
qmd = tmp_path / "chapter.qmd"
qmd.write_text(body, encoding="utf-8")
command = ValidateCommand(
config_manager=SimpleNamespace(book_dir=tmp_path),
chapter_discover... | 92 | 2,482 |
cs249r_book | book/tests/test_epub_postprocess.py | .py | from pathlib import Path
import sys
SCRIPTS = Path(__file__).resolve().parents[1] / "quarto" / "scripts"
sys.path.insert(0, str(SCRIPTS))
from epub_postprocess import ( # noqa: E402
declare_nav_mathml_property,
sanitize_xml_for_epubcheck,
)
def _write_epub_manifest(tmp_path, properties, nav_body):
epu... | 81 | 2,472 |
cs249r_book | book/tests/test_validate_inline_refs.py | .py | from types import SimpleNamespace
from book.cli.commands.validate import ValidateCommand
def test_markdown_table_caption_inline_python_is_allowed(tmp_path):
qmd = tmp_path / "chapter.qmd"
qmd.write_text(
"""```{python}
class CaptionCalc:
value_str = "1.5"
```
| Metric | Value |
|:-------|------:... | 35 | 835 |
cs249r_book | book/tests/test_latex_balance.py | .py | """Regression tests for `binder check math --scope latex-balance`.
Added 2026-08-13. A corpus-wide cleanup script silently corrupted 38 math sites
across both volumes: it stripped the backslash from `\\}` and the opening `$`
from `$<`. Every one passed `check math`, `check all`, and a full pre-commit
run; LaTeX would ... | 146 | 5,009 |
cs249r_book | book/tests/test_appendix_lineage.py | .py | """Book appendix references must resolve to sourced MLSysIM registry entries."""
from __future__ import annotations
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO_ROOT))
from book.tools.audit.appendix_lineage import (
audit_appendix_defaults,
... | 37 | 941 |
cs249r_book | book/tests/sim/__init__.py | .py | # mlsys.sim — The ML Systems Simulator Sub-package
from .personas import Persona, Personas
from .simulations import BaseSimulation, ResourceSimulation
from .ledger import (
SystemLedger,
PerformanceMetrics,
SustainabilityMetrics,
EconomicMetrics,
ReliabilityMetrics
)
| 12 | 295 |
cs249r_book | book/cli/main.py | .py | #!/usr/bin/env python3
"""
MLSysBook CLI - Modular Entry Point
A refactored, modular command-line interface for building, previewing,
and managing the Machine Learning Systems textbook.
"""
import sys
from pathlib import Path
from rich.console import Console
from rich.markup import escape as _rich_escape
from rich.ta... | 696 | 33,606 |
cs249r_book | book/cli/__init__.py | .py | """
MLSysBook CLI Package
A modular command-line interface for building, previewing, and managing
the Machine Learning Systems textbook.
"""
__version__ = "2.0.0"
__author__ = "MLSysBook Team"
| 10 | 195 |
cs249r_book | book/cli/formats/__init__.py | .py | """
Format-specific handlers for different output types.
Each format (HTML, PDF, EPUB) has its own module containing
format-specific logic and configuration.
"""
| 7 | 163 |
cs249r_book | book/cli/core/__init__.py | .py | """
Core functionality for the MLSysBook CLI.
This module contains shared components used across different commands:
- Configuration management
- File and chapter discovery
- Output directory handling
"""
| 9 | 206 |
cs249r_book | book/cli/core/discovery.py | .py | """
File and chapter discovery for MLSysBook CLI.
Handles finding chapter files, validating paths, and managing file operations.
Supports volume-aware discovery for vol1 and vol2.
Single source of truth for chapter ordering: `get_chapters_from_config()` reads
the PDF YAML config for a volume and returns the ordered l... | 605 | 22,102 |
cs249r_book | book/cli/core/artifacts.py | .py | """Shared build-artifact cleanup primitives for Binder."""
from __future__ import annotations
import shutil
from dataclasses import dataclass
from pathlib import Path
from rich.console import Console
@dataclass(frozen=True)
class ArtifactCleanupResult:
cleaned_count: int
restored_count: int
def clean_bui... | 97 | 3,149 |
cs249r_book | book/cli/core/bib_mechanical.py | .py | """Mechanical bibliography fixes used by Binder and related book tools."""
from __future__ import annotations
import re
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Sequence, TextIO
BOOK_DIR = Path(__file__).resolve().parents[2]
if str(BOOK_DIR) not in sy... | 253 | 7,321 |
cs249r_book | book/cli/core/config.py | .py | """
Configuration management for MLSysBook CLI.
Handles Quarto configuration files, symlinks, and format-specific settings.
"""
import yaml
from pathlib import Path
from typing import Dict, Any, Optional
from rich.console import Console
console = Console()
def get_output_file(output_dir: Path, format_type: str) ->... | 311 | 11,898 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.