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
labs/tests/test_workflow_helpers.py
.py
from __future__ import annotations from mlsysbook_labs import ( constraint_tax, get_lab_track_variant, get_track_profile, iteration_frontier, resolve_mlsysim_ref, workflow_policy, workflow_track_profile, ) def _profile(track_id: str): track = get_track_profile(track_id) variant = ...
89
2,853
cs249r_book
labs/tests/conftest.py
.py
""" Labs Test Configuration ======================= Shared fixtures for testing Marimo lab notebooks. Four test levels: Level 1 (Static): AST parse, structure checks, import validation Level 2 (Engine): Run cells headlessly via marimo.App.run(), check computations Level 3 (Widget): Widget structure, predi...
86
2,838
cs249r_book
scripts/figure_audit.py
.py
import os import glob import subprocess import urllib.request import urllib.parse from bs4 import BeautifulSoup from concurrent.futures import ThreadPoolExecutor # Default paths assuming the script is run from the repository root book_dir = "book/quarto/contents" out_dir = ".claude/_reviews/Figure Audit" img_tmp_dir =...
123
5,189
cs249r_book
scripts/exec_analysis.py
.py
import glob import traceback import sys qmd_files = sorted(glob.glob('book/quarto/contents/**/*.qmd', recursive=True)) failed = False for qmd in qmd_files: with open(qmd, 'r') as f: content = f.read() import re blocks = re.findall(r'```\{python\}(.*?)```', content, re.DOTALL) if not block...
34
832
cs249r_book
scripts/exec_single.py
.py
import sys import traceback def test_file(qmd_file): with open(qmd_file, 'r') as f: content = f.read() import re blocks = re.findall(r'```\{python\}(.*?)```', content, re.DOTALL) if not blocks: print(f"βœ… {qmd_file} (No Python blocks)") return True combined_code...
43
1,216
cs249r_book
scripts/audit_blocks.py
.py
import re import sys def audit_file(filepath): with open(filepath, 'r') as f: content = f.read() blocks = re.findall(r'# β”Œβ”€β”€ LEGO ───────────────────────────────────────────────\nclass (.*?):(.*?)```', content, re.DOTALL) print(f"=== AUDIT: {filepath} ===") print(f"Found {len(blocks)} LEG...
31
1,314
cs249r_book
scripts/cross-references/audit_crossrefs.py
.py
#!/usr/bin/env python3 """Audit Volume 1 and Volume 2 cross-references. This script is deliberately conservative. It reports mechanical facts and chapter-sized editorial cues; it does not rewrite prose or infer final targets. """ from __future__ import annotations import argparse import json import re from collectio...
631
22,868
cs249r_book
scripts/cross-references/build_semantic_validation_packets.py
.py
#!/usr/bin/env python3 """Build chapter packets for semantic cross-reference validation. The mechanical audit proves that references resolve. These packets support the next question: whether each resolved target is editorially useful and canonical. """ from __future__ import annotations import argparse import json f...
167
6,540
cs249r_book
scripts/cross-references/merge_crossref_reports.py
.py
#!/usr/bin/env python3 """Merge reference-aware and blind-need cross-reference reports. The output is a decision queue for the second-pass editor. It does not edit book source files. """ from __future__ import annotations import json import argparse from collections import Counter, defaultdict from dataclasses impor...
409
15,089
cs249r_book
scripts/version/release.py
.py
#!/usr/bin/env python3 """Shared release-versioning helpers for MLSysBook artifacts. Single source of truth for "what release is this artifact?" across every publishable project in the repo (StaffML, TinyTorch, Book Vol I/II, MLSYSIM, Kits, Labs, Instructors). Designed to be additive: every helper either emits a NEW f...
406
15,320
cs249r_book
socratiq/serve.py
.py
import http.server import socketserver import os from pathlib import Path PORT = 8000 SERVE_DIRECTORY = "test_website/mlsys_book_removed_most" class COOPHandler(http.server.SimpleHTTPRequestHandler): def end_headers(self): self.send_header("Cross-Origin-Opener-Policy", "same-origin") self.send_hea...
39
1,369
cs249r_book
site/newsletter/cli/main.py
.py
"""news CLI main entry point. Mirrors the Tito CLI pattern. argparse subcommands are registered in a single dict (single source of truth). Each command is a class that extends BaseCommand. All output goes through a shared Rich console with a semantic Theme so a single file controls the color palette. """ from __futur...
209
6,430
cs249r_book
site/newsletter/cli/__init__.py
.py
"""news β€” CLI for the ML Systems newsletter.""" __version__ = "0.1.0"
4
73
cs249r_book
site/newsletter/cli/core/buttondown.py
.py
"""Thin Buttondown REST API client. Deliberately small: only the endpoints the CLI needs (images, emails). Does not model the whole API. If the API changes, this is the one place to update. """ from __future__ import annotations import logging from pathlib import Path from typing import Any import requests API_BAS...
197
5,970
cs249r_book
site/newsletter/cli/core/console.py
.py
"""Shared Rich console and semantic print helpers. A single Console instance is cached at module load time so every command prints to the same terminal with the same settings. The NO_COLOR environment variable (https://no-color.org) is honored: setting it to any non-empty value disables ANSI colors for the whole CLI. ...
62
1,654
cs249r_book
site/newsletter/cli/core/validate.py
.py
"""Preflight validation for draft markdown before pushing to Buttondown. A single entry point (`validate_draft`) returns a structured report that the CLI renders. Both `news check` (user-invoked) and `news push` (automatic) call this so we never push something broken. """ from __future__ import annotations import re...
217
6,980
cs249r_book
site/newsletter/cli/core/config.py
.py
"""Filesystem layout and credentials for the news CLI. Resolved lazily via `Config.discover()`: the CLI's own location on disk tells us where the newsletter root is. There is no global config state; callers pass a Config instance down explicitly. """ from __future__ import annotations import os import sys from datac...
82
2,615
cs249r_book
site/newsletter/cli/core/theme.py
.py
"""Semantic color palette for the news CLI. Mirrors the Tito CLI theme pattern: a single Theme class with constants for status, category, and panel borders. Using Rich color names so it adapts to both dark and light terminals. """ class Theme: # Brand BRAND_ACCENT = "bright_blue" BRAND_PRIMARY = "bold wh...
39
902
cs249r_book
site/newsletter/cli/scripts/backfill_metadata_author.py
.py
"""One-shot backfill: push every local .md file's author into Buttondown as ``email.metadata.author``. Why this exists: our posts historically stored the byline only in local .md frontmatter. Now that ``news pull`` honors ``metadata.author`` as its source of truth, we need to seed Buttondown with the authors we've alr...
143
4,650
cs249r_book
site/newsletter/cli/commands/list.py
.py
"""news list β€” show all drafts and published posts.""" from __future__ import annotations from argparse import ArgumentParser, Namespace from rich.table import Table from .base import BaseCommand from ..core.theme import Theme try: import frontmatter except ImportError: frontmatter = None # Handled gracef...
113
3,425
cs249r_book
site/newsletter/cli/commands/new.py
.py
"""news new β€” scaffold a new draft from the template.""" from __future__ import annotations import shutil import sys from argparse import ArgumentParser, Namespace from .base import BaseCommand from ..core.console import success, info, error class NewCommand(BaseCommand): category = "draft" @property ...
61
1,765
cs249r_book
site/newsletter/cli/commands/diff.py
.py
"""news diff β€” compare a local draft against its Buttondown version. Useful when you've pushed a draft and then tweaked it in the Buttondown UI. Surfaces any divergence so you can decide whether to update the repo or re-push from the repo. """ from __future__ import annotations import difflib import re from argparse...
135
4,365
cs249r_book
site/newsletter/cli/commands/open.py
.py
"""news open β€” open a Buttondown URL in the browser. By default, opens the Buttondown emails dashboard. Pass a slug to open the most recent draft whose subject matches that slug (useful right after `news push`). """ from __future__ import annotations import webbrowser from argparse import ArgumentParser, Namespace ...
84
2,399
cs249r_book
site/newsletter/cli/commands/pull.py
.py
"""news pull β€” sync sent emails from Buttondown into site/newsletter/posts/. The inverse of `news push`. Handles three real scenarios: 1. You edited in the Buttondown UI before sending. The repo's draft no longer matches what subscribers received. 2. A collaborator sent from Buttondown without pushing v...
540
19,853
cs249r_book
site/newsletter/cli/commands/check.py
.py
"""news check β€” run preflight validation on a draft.""" from __future__ import annotations from argparse import ArgumentParser, Namespace from pathlib import Path from rich.panel import Panel from rich.table import Table from .base import BaseCommand from ..core.console import error from ..core.theme import Theme f...
108
3,564
cs249r_book
site/newsletter/cli/commands/push.py
.py
"""news push β€” upload a draft to Buttondown as a draft email.""" from __future__ import annotations import logging import re from argparse import ArgumentParser, Namespace from pathlib import Path from rich.panel import Panel from .base import BaseCommand from .check import render_report from ..core.buttondown impo...
247
9,474
cs249r_book
site/newsletter/cli/commands/status.py
.py
"""news status β€” show Buttondown drafts and recently sent emails.""" from __future__ import annotations import logging from argparse import ArgumentParser, Namespace from rich.table import Table from .base import BaseCommand from ..core.buttondown import ButtondownError, list_emails from ..core.config import load_a...
97
2,820
cs249r_book
site/newsletter/cli/commands/base.py
.py
"""Base class all news CLI commands inherit from.""" from __future__ import annotations from abc import ABC, abstractmethod from argparse import ArgumentParser, Namespace from ..core.config import Config from ..core.console import get_console class BaseCommand(ABC): """Every news subcommand subclasses this."""...
37
893
cs249r_book
site/newsletter/cli/commands/archive.py
.py
"""news archive β€” move a sent draft from drafts/ to posts/YYYY/.""" from __future__ import annotations import shutil from argparse import ArgumentParser, Namespace from datetime import date from pathlib import Path from .base import BaseCommand from ..core.console import error, info, success from ..core.theme import...
121
4,061
cs249r_book
site/newsletter/cli/commands/set_author.py
.py
"""news set-author β€” attach a byline to a Buttondown email's metadata. The byline lives in ``email.metadata.author`` on Buttondown. ``news pull`` reads this field first (before any body-text heuristics), so once set, the byline is authoritative and survives body edits and re-pulls. Matches a local .md post against a ...
138
4,579
cs249r_book
site/scripts/build_stats.py
.py
#!/usr/bin/env python3 """Gather every number the site displays into one cache file. Runs as the site's Quarto pre-render step. Three tiers of source: 1. Repo-derived - counted from the filesystem and git. Always available. 2. Public API - GitHub stars and merged PRs. No credentials required, ...
619
26,174
cs249r_book
site/scripts/fingerprint_assets.py
.py
#!/usr/bin/env python3 """Version local CSS and JS references by content hash. The site serves HTML with max-age=600 but stylesheets with max-age=14400, and Quarto emits plain references such as `href="landing-v3.css"`. A returning visitor inside that four-hour window therefore fetches new HTML against a stale stylesh...
107
3,323
cs249r_book
site/scripts/inject_stats.py
.py
#!/usr/bin/env python3 """Substitute {{stats.*}} placeholders in the rendered site. Runs as the site's Quarto post-render step. Working on the built HTML rather than on the .qmd source means one mechanism covers every context a number appears in: body prose, attribute values such as iframe title=, and the <text> nodes...
116
4,439
cs249r_book
book/setup.py
.py
#!/usr/bin/env python3 """ Setup script to install binder CLI in virtual environment This allows using 'binder' command without './' when venv is active """ import os import sys import subprocess from pathlib import Path def main(): """Install binder CLI in development mode""" project_root = Path(__file__).pa...
49
1,612
cs249r_book
book/vscode-ext/scripts/smoke_extension_ux.py
.py
#!/usr/bin/env python3 from __future__ import annotations import json import re import shlex import subprocess import sys import time from dataclasses import dataclass from pathlib import Path from typing import Literal Verdict = Literal["pass", "fail", "pass_started"] @dataclass class Case: name: str comma...
203
7,974
cs249r_book
book/tools/run_ml_tie_in_audits.py
.py
import os import glob import subprocess import concurrent.futures from pathlib import Path BASE_DIR = Path("/Users/VJ/GitHub/MLSysBook/book/quarto") VOL1_DIR = BASE_DIR / "contents" / "vol1" VOL2_DIR = BASE_DIR / "contents" / "vol2" AUDIT_DIR = BASE_DIR / "audits" / "ml_tie_ins" # Find chapters, skip frontmatter, bac...
76
3,135
cs249r_book
book/tools/bib_lint.py
.py
#!/usr/bin/env python3 """Compatibility wrapper for the Binder-native bibliography linter. The implementation lives in ``book/cli/checks/bib_lint.py`` so publishing checks are owned by Binder. Keep this wrapper for older commands and docs that still call ``python3 book/tools/bib_lint.py`` directly. """ from __future_...
24
658
cs249r_book
book/tools/bib_sync_preserve.py
.py
#!/usr/bin/env python3 """WARNING: reviewed bibliography migration helper only. Run ``betterbib sync`` with a reviewed per-entry merge. This helper is the automation layer for bibliography refreshes in the repo. It does four things per ``.bib`` file: 1. Run ``betterbib sync --in-place`` on a temp copy of the file. 2...
718
25,144
cs249r_book
book/tools/tests/test_lint_lego_units.py
.py
"""Tests for LEGO unit discipline linter.""" from __future__ import annotations import json import tempfile from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[3] from book.cli.checks.lego_units import lint_file, main def _write_qmd(tmp_path: Path, rel: str, body: str) -> Path: path...
174
5,035
cs249r_book
book/tools/tests/test_lego_quantity_flow_audit.py
.py
"""Tests for the advisory LEGO quantity-flow audit.""" from __future__ import annotations import sys from pathlib import Path from book.cli.checks.lego_prose_literals import check_file as check_prose_literals ROOT = Path(__file__).resolve().parents[3] sys.path.insert(0, str(ROOT / "book" / "tools" / "audit")) from...
117
3,726
cs249r_book
book/tools/tests/test_lego_scenario_inputs_audit.py
.py
from __future__ import annotations import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[3] sys.path.insert(0, str(ROOT / "book" / "tools" / "audit")) from book_check_lego_scenario_inputs import _classify, check_file # noqa: E402 def classify(name, rhs): return _classify(name, rhs, set()...
117
3,719
cs249r_book
book/tools/scripts/check_bib_qmd_integrity.py
.py
#!/usr/bin/env python3 """Comprehensive bib/qmd link-integrity check. Catches four failure modes that the standard `binder check refs --scope citations` does NOT cover: 1. **Unresolved cites** β€” `[@key]` appears in a `.qmd` but is not defined in *any* bib in the repo. 2. **Scope violations** β€” a source cites a key...
497
20,112
cs249r_book
book/tools/scripts/svg_polisher.py
.py
import os import glob from lxml import etree as ET def polish_svg(filepath): try: parser = ET.XMLParser(remove_blank_text=False) tree = ET.parse(filepath, parser) root = tree.getroot() except Exception as e: print(f"Error parsing {filepath}: {e}") return False chang...
98
3,949
cs249r_book
book/tools/scripts/figure_audit_review.py
.py
#!/usr/bin/env python3 """ Figure Audit Review Dashboard Generator. Parses audit markdown reports and generates a self-contained HTML review page. Uses fig-id as the definitive key throughout β€” matches id="fig-xxx" in rendered HTML to find the exact image <img src="..."> for each figure. Usage: python3 book/tools...
533
19,475
cs249r_book
book/tools/scripts/migrate_lego_m_as.py
.py
#!/usr/bin/env python3 """One-shot bulk .m_as() -> .to(unit).magnitude migration for LEGO cells.""" from __future__ import annotations import re import sys from pathlib import Path REPLACEMENTS = [ (".m_as(TFLOPs / second)", ".to(TFLOPs / second).magnitude"), (".m_as(TFLOPs/second)", ".to(TFLOPs/second).magni...
208
9,207
cs249r_book
book/tools/scripts/convert_icons.py
.py
import os from PIL import Image icon_dir = "book/quarto/assets/images/icons/callouts/" # Process all v* files and the main file files = [f for f in os.listdir(icon_dir) if (f.startswith("icon_callout_war_story") and f.endswith(".png"))] for f in files: img_path = os.path.join(icon_dir, f) pdf_path = os.path.j...
34
1,358
cs249r_book
book/tools/scripts/transform_pico_cells.py
.py
#!/usr/bin/env python3 """ Transform flat PICO Python cells in QMD files to class-based namespace isolation. Usage: python3 book/tools/scripts/transform_pico_cells.py <path_to_qmd> """ import re import sys from pathlib import Path def label_to_classname(label: str) -> str: """Convert label like 'nn-ops-calc...
283
10,266
cs249r_book
book/tools/scripts/wrap_readme_data_tables.py
.py
#!/usr/bin/env python3 """ Wrap README HTML tables in a wide, GitHub-safe frame (98% width, outer `#cfd6dd` border via cellspacing, white inner panel, padded cells). Handles: - ``<table>`` + newline + ``<thead>`` data tables (adds header cell styling) - ``<table>`` + newline + ``<tbody>`` body-only tables (skips A...
113
3,378
cs249r_book
book/tools/scripts/lint_lego_units.py
.py
#!/usr/bin/env python3 """Compatibility wrapper for the Binder-native LEGO unit discipline linter.""" from __future__ import annotations import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[3] sys.path.insert(0, str(ROOT)) from book.cli.checks.lego_units import ( # noqa: E402,F401 LintIs...
21
410
cs249r_book
book/tools/scripts/fix_lego_lint_warnings.py
.py
#!/usr/bin/env python3 """Bulk-fix common LEGO lint warnings (L007, L008, L009) in QMD python blocks.""" from __future__ import annotations import re import sys from pathlib import Path UREG_REPLACEMENTS = [ (r"ureg\.millijoule\b", "mJ"), (r"ureg\.megawatt\b", "MW"), (r"ureg\.joule\b", "joule"), (r"u...
93
2,612
cs249r_book
book/tools/scripts/bib_mitpress_openai.py
.py
#!/usr/bin/env python3 """Standalone MIT Press BibTeX validator for MLSysBook. This is the single command-line surface for the MIT Press bibliography sweep. It validates BibTeX entries with the repo's Binder-native canonical parser/rules in ``book/cli/checks/bib_lint.py`` and adds a small MIT Press production layer fo...
619
21,962
cs249r_book
book/tools/scripts/migrate_bridges.py
.py
#!/usr/bin/env python3 """Migrate LEGO bridge variables to direct ClassName.attr access. For each .qmd file, finds bridge assignments like: var = ClassName.attr and replaces all downstream uses (inline refs + Python code) with the direct ClassName.attr access, then removes the bridge line. """ import re import sy...
282
8,854
cs249r_book
book/tools/scripts/build_citation_reference_packets.py
.py
#!/usr/bin/env python3 """Build chapter packets for semantic citation-reference validation. The existing bibliography checks prove that citekeys resolve. These packets support the harder editorial question: whether the cited source actually backs the sentence or paragraph where it is used. """ from __future__ import ...
641
21,818
cs249r_book
book/tools/scripts/check_bib_boundaries.py
.py
#!/usr/bin/env python3 """Enforces strict bibliography boundaries between project components.""" import re import sys import argparse from pathlib import Path from collections import defaultdict REPO_ROOT = Path(__file__).resolve().parents[3] # Define strict scopes: {Name: {"sources": [dirs/files], "bibs": [files]}}...
162
5,717
cs249r_book
book/tools/scripts/fix_l015_prose_dup_units.py
.py
#!/usr/bin/env python3 """Remove prose unit words duplicated after closed-fixed {python} exports (L015).""" from __future__ import annotations import re import sys from pathlib import Path # Unit token immediately after a closed-fixed export ref. PROSE_DUP = re.compile( r"( `\{python\}\s*[\w.]+\.\w+_(?:w|kw|mw|w...
40
1,032
cs249r_book
book/tools/scripts/fix_glued_cell_fences.py
.py
#!/usr/bin/env python3 """Split closing ``` fences glued to the last line of a {python} cell.""" from __future__ import annotations import argparse from pathlib import Path def fix_text(text: str) -> tuple[str, int]: fixes = 0 out: list[str] = [] for line in text.splitlines(): if line.endswith("...
51
1,449
cs249r_book
book/tools/scripts/gen_bio_nn_svg.py
.py
import math def generate_svg(): width = 900 height = 380 svg_header = f'''<?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" font-family="Helvetica Neue, Helvetica, Arial, sans-serif"> <defs> <style> .panel-bg {{ fill: rgba(46...
189
8,681
cs249r_book
book/tools/scripts/svg_standardizer.py
.py
import os import glob import re from lxml import etree as ET COLOR_MAP = { # Compute (blue) '#e8f2fc': '#cfe2f3', '#eef4fb': '#cfe2f3', '#f0f6ff': '#cfe2f3', '#f0f8ff': '#cfe2f3', '#f7f9fc': '#cfe2f3', '#d0e4f5': '#cfe2f3', '#c8dde8': '#cfe2f3', '#b8d4e8': '#cfe2f3', '#c8daf0': '#cfe2f3', '#8ab8da': '#4a90c4',...
186
8,162
cs249r_book
book/tools/scripts/testing/test_format_tables.py
.py
#!/usr/bin/env python3 """ Test cases for table formatter. Tests various edge cases including: - Standard tables with multiple rows - Tables with empty cells - Tables with multi-row cells - Tables with Unicode characters - Tables with already bolded content """ import sys from pathlib import Path from format_tables i...
344
8,668
cs249r_book
book/tools/scripts/testing/struct_qa_html.py
.py
#!/usr/bin/env python3 """struct_qa_html.py Structural QA pass over a built HTML site for the MLSysBook camera-ready sweep. Walks every chapter HTML under --html-dir and emits one JSON line per chapter to --out, summarising image, anchor, math, and leaked-token checks. Stdlib only. BeautifulSoup is used opportunistic...
255
8,737
cs249r_book
book/tools/scripts/testing/struct_qa_pdf.py
.py
#!/usr/bin/env python3 """struct_qa_pdf.py Structural QA for a built PDF in the MLSysBook camera-ready sweep. Shells out to ``pdftotext``, ``pdfimages``, and ``mutool`` to inspect a single PDF and emit a one-line JSON summary. Usage: python3 struct_qa_pdf.py --vol vol1 \ --pdf /abs/path/to/build.pdf \ ...
150
4,396
cs249r_book
book/tools/scripts/testing/tikz_style_linter.py
.py
#!/usr/bin/env python3 import re import sys from pathlib import Path from typing import Dict, Iterable, List, Optional, Set, Tuple TIKZ_BLOCK_PATTERN = re.compile(r"```\{\.tikz\}[\s\S]*?```", re.MULTILINE) TIKZSET_BLOCK_PATTERN = re.compile(r"\\tikzset\s*\{([\s\S]*?)\}") STYLE_DEF_PATTERN = re.compile(r"(^|[,\s])([A...
231
7,291
cs249r_book
book/tools/scripts/testing/debug_section_builds.py
.py
#!/usr/bin/env python3 """ Build a chapter section-by-section to isolate which section causes a build failure. Uses section_splitter.py to split a chapter into ## sections, then progressively builds with more sections included until the build breaks. This pinpoints exactly which section introduces the error. Usage: ...
368
12,623
cs249r_book
book/tools/scripts/publish/extract_figures.py
.py
#!/usr/bin/env python3 """ Extract figures and captions/alt-text from book chapters for MIT Press. This script reads the chapter configuration from the YAML file, extracts all figures from each chapter, and outputs a Markdown file listing each chapter with its figures numbered sequentially (Figure 1, Figure 2, etc.). ...
423
13,966
cs249r_book
book/tools/scripts/publish/render_compress_publish.py
.py
import os import sys import re import subprocess import argparse from zipfile import ZipFile from PIL import Image import tempfile import shutil import time DEFAULT_COMPRESSION_QUALITY = 60 def compress_image(image_path, quality=DEFAULT_COMPRESSION_QUALITY): try: img = Image.open(image_path) img.s...
175
6,211
cs249r_book
book/tools/scripts/publish/modify_dev_announcement.py
.py
#!/usr/bin/env python3 """ Modify announcement banner for development preview deployment. This script modifies the Quarto announcement banner in HTML files to: 1. Make it non-dismissible 2. Add a prominent "DEVELOPMENT PREVIEW" banner at the top 3. Style it with appropriate warning colors Used by the deploy-preview G...
157
6,127
cs249r_book
book/tools/scripts/mit_press/check_footnote_caps.py
.py
#!/usr/bin/env python3 """Check footnote definition capitalization. MIT Press style requires that terms like "computer engineering" remain lowercase in running prose (e.g., "computer engineering is a discipline"). A global search/replace to enforce that rule can accidentally lowercase the *first letter of a footnote*,...
385
12,288
cs249r_book
book/tools/scripts/images/analyze_image_sizes.py
.py
#!/usr/bin/env python3 """ Textbook Image Size Analyzer Identifies large images and provides textbook-specific optimization recommendations. """ import os import glob from pathlib import Path # Textbook image size guidelines TEXTBOOK_GUIDELINES = { 'large': { 'threshold': 2.0, # MB 'recommendatio...
233
7,840
cs249r_book
book/tools/scripts/images/manage_external_images.py
.py
#!/usr/bin/env python3 """ External Image Downloader for Quarto Markdown Files This script automatically downloads external images referenced in markdown files and organizes them locally according to the project's directory structure. DESCRIPTION: Processes .qmd files to find markdown images with #fig references ...
561
22,402
cs249r_book
book/tools/scripts/images/convert_svg_to_png.py
.py
#!/usr/bin/env python3 """ convert_svg_to_png.py Helper tool to convert SVG files to PNG format and find QMD file references. This tool helps ensure consistency when converting SVG files to PNG. Usage: python convert_svg_to_png.py path/to/file.svg python convert_svg_to_png.py --dry-run path/to/file.svg python c...
232
9,001
cs249r_book
book/tools/scripts/images/manage_images.py
.py
#!/usr/bin/env python3 """ check_images.py Validates image files by inspecting their actual content. Supports .png, .jpg, .jpeg, .gif, .svg, .webp formats. Usage: - Single file: python check_images.py -f image.png - Directory scan: python check_images.py -d ./assets - CI hooks: python check_images.py i...
280
11,295
cs249r_book
book/tools/scripts/images/compress_images.py
.py
#!/usr/bin/env python3 """ Flexible Image Compression Tool Compresses images to textbook-appropriate sizes with automatic backup. """ import os import subprocess import shutil import sys from datetime import datetime def compress_images(files, quality=85, apply=False, preserve_dimensions=False, smart_compression=Fals...
243
11,712
cs249r_book
book/tools/scripts/images/remove_bg.py
.py
#!/usr/bin/env python3 """ Remove white background from PDF icon image Makes the background transparent while preserving the red PDF label and gray lines """ from PIL import Image import numpy as np from pathlib import Path def remove_white_background(input_path, output_path, threshold=250): """ Remove white ...
144
4,843
cs249r_book
book/tools/scripts/maintenance/regen_captions_baseline.py
.py
#!/usr/bin/env python3 """Regenerate book/tools/audit/baselines/captions_baseline.json. Snapshots the current per-file counts of captionless-float violations flagged by the `tables.caption-required`, `figures.label-required`, and `listings.caption-required` scopes. New violations beyond the per-file budget will fail t...
72
2,271
cs249r_book
book/tools/scripts/maintenance/validate_inline_refs.py
.py
#!/usr/bin/env python3 """ validate_inline_refs.py Pre-render guardrail for inline Python in QMD files. Checks: 1. Every `{python} ref` resolves to a defined variable or ClassName.attr 2. Every `{python} ref` appears AFTER its definition (Locality) 3. No grid tables with inline Python (use pipe tables instead) 4. No i...
830
34,083
cs249r_book
book/tools/scripts/maintenance/capitalize_sentence_start_xrefs.py
.py
#!/usr/bin/env python3 """ Capitalize cross-reference prefixes at sentence starts. MIT Press convention: lowercase inline refs ("figure 1", "table 2") with uppercase only at sentence starts ("Figure 1 shows..."). Quarto supports this via @Fig- / @Tbl- / @Sec- / @Eq- / @Lst- syntax when the crossref prefix config is s...
312
10,919
cs249r_book
book/tools/scripts/maintenance/update_texlive_packages.py
.py
#!/usr/bin/env python3 """ LaTeX Package Dependency Extractor This script analyzes files to extract LaTeX package dependencies and generate a list of required TeX Live packages and collections. It searches through specified files to find all \\usepackage declarations and TikZ library usage. The script uses tlmgr (TeX...
528
18,625
cs249r_book
book/tools/scripts/maintenance/repo_health_check.py
.py
#!/usr/bin/env python3 """ Repository Health Check and Maintenance Script Performs comprehensive health checks and cleanup operations on the MLSysBook repository """ import os import sys import subprocess import argparse import json from pathlib import Path from datetime import datetime from typing import List, Dict, ...
539
21,380
cs249r_book
book/tools/scripts/maintenance/validate_pint_usage.py
.py
#!/usr/bin/env python3 """ validate_pint_usage.py Static analysis for Pint anti-patterns in QMD files. Scans Python code blocks in .qmd files for patterns that may indicate unsafe unit handling: bare .magnitude access, hasattr duck-typing, and .to(unit).magnitude chains that should modernize to .m_as(unit). Severity ...
308
11,614
cs249r_book
book/tools/scripts/utilities/prettify_pipe_tables.py
.py
#!/usr/bin/env python3 """ Prettify pipe-style markdown tables in Quarto/Markdown files. Aligns columns for readability while preserving pipe table format. Before: | **Layer Type** | **Output Shape** | **Parameters** | |:--|:--|--:| | **Linear** | $(B, N_{out})$ | $(N_{in} + 1) \times N_{out}$ | After: | **Layer Typ...
367
12,050
cs249r_book
book/tools/scripts/utilities/check_list_formatting.py
.py
#!/usr/bin/env python3 """ Ensure markdown lists are preceded by a blank line. Markdown requires a blank line before the first item of a list for it to render as a proper list block. Without it, Quarto / Pandoc treat the items as continuation of the preceding paragraph. Detected patterns ----------------- 1. A non-b...
164
5,565
cs249r_book
book/tools/scripts/utilities/convert_grid_to_pipe_tables.py
.py
#!/usr/bin/env python3 """ Convert grid tables to pipe tables in Quarto/Markdown files. Grid tables use + for corners and borders: +---------------+------------------+ | **Paradigm** | **Where** | +:==============+:=================+ <- alignment markers here | **Cloud ML** | Data centers | +-----------...
320
9,933
cs249r_book
book/tools/scripts/utilities/manage_sources.py
.py
#!/usr/bin/env python3 """ Source Citation Checker and Cleaner This script analyzes, validates, and cleans up source citations in QMD files. Provides comprehensive reporting and automatic cleanup capabilities. Usage: python check_sources.py --analyze python check_sources.py --clean python check_sources.py...
562
23,709
cs249r_book
book/tools/scripts/infrastructure/cleanup_containers.py
.py
#!/usr/bin/env python3 """ Container Registry Cleanup Script This script helps clean up the GitHub Container Registry by removing unnecessary containers and keeping only the main quarto-linux container. Usage: python cleanup_containers.py """ import subprocess import json import sys from typing import List, Dict...
125
3,936
cs249r_book
book/tools/scripts/infrastructure/cleanup_workflow_runs_gh.py
.py
#!/usr/bin/env python3 """ GitHub Workflow Runs Cleanup Script using GitHub CLI This script uses the GitHub CLI (gh) for authentication, so no separate token needed. Just requires 'gh auth login' to be done once. Usage: python3 cleanup_workflow_runs_gh.py --help python3 cleanup_workflow_runs_gh.py --dry-run ...
364
12,229
cs249r_book
book/tools/scripts/infrastructure/list_containers.py
.py
#!/usr/bin/env python3 """ Container Details Lister This script helps identify container details from workflow logs and provides information to help distinguish between containers. """ import subprocess import json import re from typing import List, Dict def run_command(cmd: List[str]) -> Dict: """Run a command ...
141
4,603
cs249r_book
book/tools/scripts/margin_figures/render_margin_reader_alignment_html.py
.py
#!/usr/bin/env python3 """Render a readable HTML dashboard for margin-figure reader alignment. The page is an editor-facing companion to the markdown reader-link audit. It shows every placed margin figure with its SVG, caption, fig-alt evidence, source QMD location, strongest local prose anchor, and expandable before/...
898
26,989
cs249r_book
book/tools/scripts/margin_figures/insert_curated_margin_figures.py
.py
#!/usr/bin/env python3 """Insert curated margin-figure SVG references into MLSysBook QMD files. The source of truth is ``book/tools/audit/margin_figure_decisions.yml`` joined with ``margin_figure_opportunities.yml``. The script is idempotent: if a QMD already references the generated SVG filename, it leaves that candi...
193
5,985
cs249r_book
book/tools/scripts/margin_figures/inventory_margin_figures.py
.py
#!/usr/bin/env python3 """Inventory MLSysBook margin figures from rendered chapter source. This scans the actual QMD ``.column-margin`` blocks. The output is meant to answer the editorial question "what margin figure is placed where?" rather than only restating the audit files. """ from __future__ import annotations ...
260
9,353
cs249r_book
book/tools/scripts/margin_figures/generate_margin_figures.py
.py
#!/usr/bin/env python3 """Generate the committed MLSysBook margin-figure SVG assets. The output is intentionally SVG. The figures are authored at the native margin-column scale, use the book Helvetica stack through Book Tools, and reuse the canonical margin-device vocabulary documented in ``.claude/rules/margin-figure...
2,392
104,561
cs249r_book
book/tools/scripts/margin_figures/audit_margin_caption_alignment.py
.py
#!/usr/bin/env python3 """Audit margin-figure captions against nearby prose. This is an editorial support tool. It inventories QMD ``.column-margin`` blocks, captures the nearest prose before and after each figure, and emits a markdown packet for judgment. The score is only a triage signal; final pass/fix decisions mu...
294
9,506
cs249r_book
book/tools/scripts/margin_figures/render_margin_contact_sheet.py
.py
#!/usr/bin/env python3 """Render MLSysBook margin SVGs into a contact sheet for visual QA. The generator outlines text into SVG paths, so this script is primarily for human checks: margin-scale legibility, line weight, collisions, and whether the rendered result looks publication-clean. It uses ``rsvg-convert`` so the...
169
6,092
cs249r_book
book/tools/scripts/margin_figures/render_margin_reader_link_audit.py
.py
#!/usr/bin/env python3 """Render an inspectable reader-link audit for margin figures. This script creates a markdown packet for editor/LLM review. Each entry shows where the margin figure appears in QMD source, embeds the referenced SVG, shows the caption and figure alt text, and records the nearest prose before and a...
227
8,709
cs249r_book
book/tools/scripts/margin_figures/margin_devices.py
.py
#!/usr/bin/env python3 """Compatibility wrapper for the Book Tools margin-device package. Stable margin drawing devices live in ``book.tools.figures.margin.devices``. This module remains so older scripts or ad-hoc commands that import ``margin_devices`` from this directory keep working. """ from pathlib import Path i...
16
477
cs249r_book
book/tools/scripts/quizzes/validate_quiz_json.py
.py
#!/usr/bin/env python3 """Validate a quiz JSON file against the canonical spec and the chapter's anchors. Per the project quiz-generation spec Β§1 and Β§11: one quiz per ``##`` section only; material spans the whole section including its ``###`` subsections but ``###`` anchors are never valid ``section_id`` values. Run...
214
7,981
cs249r_book
book/tools/scripts/quizzes/build_audit_context.py
.py
#!/usr/bin/env python3 """Build a per-chapter audit/improve context package for a sub-agent. For each chapter we want to drive to A-grade, this script produces a single self-contained Markdown document containing: - Chapter identity (vol, name, position in reading order) - The list of prior chapters already read (so ...
356
13,137
cs249r_book
book/tools/scripts/quizzes/extract_anchors.py
.py
#!/usr/bin/env python3 """Extract ``## section`` and ``### subsection`` anchors from a Quarto ``.qmd`` chapter. Used by the quizzes pipeline to give each sub-agent an authoritative map of the exact anchors it may target as ``section_id`` / ``parent_section_id`` values in the generated quiz JSON. Usage ----- pytho...
94
2,869
cs249r_book
book/tools/scripts/quizzes/build_prior_vocab.py
.py
#!/usr/bin/env python3 """Build the cumulative prior-vocabulary context for a target chapter. Walks the Vol1 β†’ Vol2 reading order and, for chapter N, produces the union of every definition term first introduced in chapters 1..N-1. The resulting JSON is passed to that chapter's quiz-generation sub-agent so it knows whi...
201
6,476
cs249r_book
book/tools/scripts/quizzes/playwright_verify.py
.py
#!/usr/bin/env python3 """Verify that a rendered chapter HTML has quizzes injected correctly. Opens a rendered chapter (file path or URL) with Playwright and checks: 1. Every ``##`` section has a ``.callout-quiz-question`` div at its end, OR a nearby subsection does β€” i.e., quizzes are injected. 2. The chapter has...
168
6,234
cs249r_book
book/tools/scripts/quizzes/generate_quizzes.py
.py
#!/usr/bin/env python3 """Quiz regeneration runner for Vol1 and Vol2 of the ML Systems textbook. Reads the canonical quiz-generation spec from the project rules directory, reads a chapter's prose, and produces ``{chapter}_quizzes.json.new`` at the canonical path. Every decision about taxonomy, format, quality bar, and...
1,016
39,189