text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
"""PITDataReader — point-in-time reads over the Parquet lake via DuckDB. THE PIT RULE LIVES HERE AND ONLY HERE (dataDesign.md §3.1): every analytical read takes an explicit ``as_of`` (epoch ms UTC) and returns only records *available* at that instant. There is deliberately no ``as_of=now`` default — callers must state...
arhancanli/canli-pit-lake
src/alphaforge/data/store/reader.py
.py
3438b524af404776
7
0
"""Resampler — derive 4h/1d bars from stored 1h bars (dataDesign.md §2.4/§4.4). Derived bars are lake datasets like any other (``ohlcv_4h``/``ohlcv_1d``; see :func:`alphaforge.data.schemas.ohlcv_dataset`): written through the same validated, atomic :class:`~alphaforge.data.store.writer.LakeWriter`, read back through `...
arhancanli/canli-pit-lake
src/alphaforge/data/store/resample.py
.py
836f56a9a7c56e23
7
0
"""LakeWriter — validated, idempotent, crash-safe upserts into the Parquet lake. Write pipeline per call (dataDesign.md §2.2/§2.4, §3.3): 1. **Validate** the incoming table against the declared schema (:func:`alphaforge.data.schemas.validate_table`) — nothing malformed ever reaches disk. 2. **Partial-bar guard*...
arhancanli/canli-pit-lake
src/alphaforge/data/store/writer.py
.py
ce739a72ca6b2b11
7
0
"""UniverseStore — membership-interval persistence over the ``universe_membership`` dataset. Storage is the ordinary Parquet lake (``UNIVERSE_SCHEMA``; natural key ``(instrument_id, effective_from)``), written through :class:`LakeWriter` so the tmp-write + atomic-replace crash-safety protocol and schema validation app...
arhancanli/canli-pit-lake
src/alphaforge/data/universe/store.py
.py
7e955c6256d1e277
7
0
"""Point-in-time venue/instrument market-status and execution-blocking primitives.""" from __future__ import annotations from dataclasses import dataclass from enum import StrEnum from itertools import pairwise from typing import Protocol from alphaforge.core.errors import LookaheadError from alphaforge.core.symbols...
arhancanli/canli-pit-lake
src/alphaforge/execution/market_status.py
.py
91c4ec27018353dd
7
0
"""Network integration tests for ``CCXTDataSource`` against live Binance USDT-M. These tests hit real public endpoints (``/fapi/v1/klines``, ``/fapi/v1/fundingRate``, ``exchangeInfo`` + ``/fapi/v1/fundingInfo`` via ccxt) and are therefore: * marked ``@pytest.mark.network`` — deselected by default ``addopts`` (``-m ...
arhancanli/canli-pit-lake
tests/integration/test_ccxt_network.py
.py
4646be2594dd1bdd
7.5
0
"""Cross-module smoke test for the Phase 1 core kernel. Exercises the curated :mod:`alphaforge.core` surface end to end: settings load from the real repo configs, SCD2 instrument persistence, symbol round-trips, 24/7 calendar bar arithmetic, and Arrow schema validation — all through the public re-exports, so any drift...
arhancanli/canli-pit-lake
tests/integration/test_core_kernel.py
.py
8c0621b84010a455
7.5
0
"""End-to-end equities flat-files ingest against the FAKE S3 client into a tmp lake. NO network, NO live lake (EQUITIES_INGEST.md §4.2-4.3 / BUILD C). This is the integration counterpart to the unit job tests: it drives the REAL ``EquitiesFlatFilesJob`` → ``LakeWriter`` → ``PITDataReader`` chain over a multi-day synth...
arhancanli/canli-pit-lake
tests/integration/test_flatfiles_ingest_end_to_end.py
.py
35934a7066365d28
7.5
0
"""Network integration test for ``PolygonFlatFilesSource`` against live Polygon S3 flat files. This test hits the real Polygon flat-files S3 bucket (``flatfiles`` at ``https://files.polygon.io``) via the boto3 ``_Boto3FlatFilesClient`` and is therefore: * gated on the real ``POLYGON_S3_*`` credentials — skipped entir...
arhancanli/canli-pit-lake
tests/integration/test_flatfiles_network.py
.py
553211f60307f233
7.5
0
"""End-to-end lake integration: BackfillJob → Parquet lake → PITDataReader. The full Phase 2 chain on one merged lake, with zero network: a FakeSource (REST double) and a FakeVision (archive double) feed BackfillJob.run over two instruments across three calendar months — BTC stays LIVE (REST path) while LUNA is DELIST...
arhancanli/canli-pit-lake
tests/integration/test_lake_end_to_end.py
.py
2c2e9ae04500f0ee
7.5
0
"""Network integration tests for ``PolygonEquitiesSource`` against live Polygon.io. These tests hit real Polygon REST endpoints (``/v2/aggs/...``, ``/v3/reference/tickers``, ``/v3/reference/splits``, ``/v3/reference/dividends``) and are therefore: * gated on a real ``POLYGON_API_KEY`` — skipped entirely when it is ab...
arhancanli/canli-pit-lake
tests/integration/test_polygon_network.py
.py
5043be7d47830ea6
7.5
0
""" Data Loader Module Loads and validates the raw cybersecurity incident dataset. Author: Pramod Prakash Jadhav """ from __future__ import annotations from pathlib import Path import pandas as pd from src.config import ( CSV_ENCODING, CSV_SEPARATOR, EXPECTED_COLUMNS, RAW_DATA_FILE, ) from src.log...
pramodj551-oss/Part1-Cybersecurity-Data-Pipeline
src/data_loader.py
.py
52bfefe8ba67e843
7
0
""" Database Module Stores the feature engineered cybersecurity incident dataset into SQLite. Author: Pramod Prakash Jadhav """ from __future__ import annotations import sqlite3 from pathlib import Path import numpy as np import pandas as pd from src.config import ( BOOLEAN_COLUMNS, DATABASE_FILE, DAT...
pramodj551-oss/Part1-Cybersecurity-Data-Pipeline
src/database.py
.py
14c16b6234ccfcf2
7
0
""" Utility Functions Shared helper functions for the cybersecurity analytics pipeline. """ from pathlib import Path import pandas as pd def ensure_directory(path: Path) -> None: """Create directory if it does not exist.""" path.mkdir(parents=True, exist_ok=True) def dataframe_shape(df: pd.DataFrame) -> ...
pramodj551-oss/Part1-Cybersecurity-Data-Pipeline
src/utils.py
.py
80191b3e00978293
7
0
"""Core regression and integration tests for the Part 1 pipeline.""" from pathlib import Path import pandas as pd import pytest from src.config import DATABASE_TABLE, EXPECTED_COLUMNS from src.data_cleaning import DataCleaner from src.data_loader import DataLoader from src.database import DatabaseManager from src.fe...
pramodj551-oss/Part1-Cybersecurity-Data-Pipeline
tests/test_core_pipeline.py
.py
5b57d9fd712001eb
7.5
0
"""Fill models — how queued orders become executions (execDesign.md §4.2). THE no-lookahead contract (execDesign.md §4.1; leakageCritique.md findings 4/5): a decision taken at the close of bar ``t`` fills at the **open of bar t+1**, never inside bar ``t``. A fill model therefore receives *only* the next bar; it mechan...
arhancanli/canli-backtest
src/alphaforge/backtest/fills.py
.py
a65cf39822ad3787
7.5
0
"""Per-asset-class sleeve registry — the single source of (anchor TF, calendar). The engine spine (features, backtest, labeling, portfolio, signals, walk-forward) is valued on a per-sleeve **anchor timeframe** and reads its grid/annualization from the matching :class:`~alphaforge.core.calendar.TradingCalendar`. This m...
arhancanli/canli-backtest
src/alphaforge/config/sleeve.py
.py
228be91144ec35cb
7
0
"""Exchange fee schedules (execDesign §3.1). This module is part of ``alphaforge.costs`` — the single source of truth for every trading friction in the system. Fee rates are declared exactly once, here; the vectorized backtester, the event-driven backtester, ``PaperBroker`` and the optimizer all consume them through :...
arhancanli/canli-backtest
src/alphaforge/costs/fees.py
.py
92f9a22eeecef7e8
7
0
"""Point-in-time securities-borrow, locate, recall, and buy-in primitives. General-collateral assumptions are not sufficient for security-level short execution. This module keeps availability, quantity, fee, locate expiry, and recall deadlines explicit. It does not infer historical borrow from today's broker flags or ...
arhancanli/canli-backtest
src/alphaforge/execution/borrow.py
.py
dc0f6c5182406310
7
0
"""Point-in-time equity corporate-action primitives. The lake stores raw prices, so holdings must be transformed by explicit lifecycle events rather than inferred from price jumps. This module validates the event shape and its availability lineage; the backtest engine owns event ordering and the ledger owns cash/posi...
arhancanli/canli-backtest
src/alphaforge/execution/corporate_actions.py
.py
5fdb7e4caeecaba3
7
0
"""FeatureSpec — identity, contract, and data requirements of one registered feature. This is THE merged factor abstraction (buildabilityCritique.md ruling 3.4): Design A's ``FeatureSpec`` machinery absorbs Design B's ``FactorMeta`` fields (``family``, ``direction``, ``cross_sectional``). There is exactly one feature ...
arhancanli/canli-backtest
src/alphaforge/features/spec.py
.py
935fb30c066ef935
7.5
0
"""P&L concentration screening — the guard that catches an edge made of bad prints. WHY THIS EXISTS. On 2026-08-10 a zero-trial audit surfaced ``eq_ilrev``, a completed 15-year walk-forward that looked like the best free sleeve this book had seen: net Sharpe 0.69, turnover only 3.0x/yr, Newey-West t on the mean +2.46,...
arhancanli/canli-backtest
src/alphaforge/validation/concentration.py
.py
8deab4283c7217bb
7
0
"""Combinatorially Purged Cross-Validation (alphaDesign.md §7, the ``CombinatorialPurgedCV`` spec; Lopez de Prado, *Advances in Financial Machine Learning* ch. 12, "The Combinatorial Purged Cross-Validation Method"). CPCV exists to produce a *distribution* of out-of-sample (OOS) paths for a selection statistic (Sharpe...
arhancanli/canli-backtest
src/alphaforge/validation/cpcv.py
.py
5e6d2efd20f9125b
7
0
"""IC metrics with overlap-honest inference (alphaDesign.md §7.2). Per-timestamp Spearman rank IC of a factor against execution-aware forward returns, summarized with a Newey-West HAC t-statistic. Because an ``h``-bar label observed on a 1-bar grid overlaps its ``h - 1`` neighbours, the dense IC series is serially cor...
arhancanli/canli-backtest
src/alphaforge/validation/metrics.py
.py
dbb1ee5ac453db4a
7
0
"""Probability of Backtest Overfitting via CSCV (alphaDesign.md section 7.3). Combinatorially Symmetric Cross-Validation (Bailey, Borwein, Lopez de Prado, Zhu 2017, "The Probability of Backtest Overfitting", J. Computational Finance). Given a performance matrix ``M`` of per-period returns with ``T`` rows (observations...
arhancanli/canli-backtest
src/alphaforge/validation/pbo.py
.py
a861b7b0f053ff84
7
0
"""Make a pre-registration MACHINE-CHECKABLE, so a run cannot silently ignore it. THE BUG CLASS THIS CLOSES. On 2026-08-07, three separate runs failed for one reason: a pre-registration named a data source in prose, and nothing in the code ever read it. The profile is chosen by whoever launches the run; the declared s...
arhancanli/canli-backtest
src/alphaforge/validation/prereg.py
.py
0ad34850713b0b4e
7
0
"""Register a SCREEN-STAGE probe's trial on the honest ledger. THE HOLE THIS CLOSES. Multiple-testing deflation is this project's central honesty mechanism: every hypothesis tested raises the bar that every sleeve in the book must clear, so the deflation is only as truthful as the trial count behind it. That count has...
arhancanli/canli-backtest
src/alphaforge/validation/probe_ledger.py
.py
9ee397e78541f649
7
0
"""Refuse to PUBLISH a number that cannot be true. WHY THIS EXISTS. On 2026-08-08 canlicapital.com began serving a flagship live curve that read 100,000.00 then 400,207.73 — a 300% gain in one day, on a market-neutral book that runs gross at or below 1.0x. It stood for three days. The underlying cause was a database m...
arhancanli/canli-backtest
src/alphaforge/validation/publish_gate.py
.py
6c20e8bba6ce272a
7
0
"""THE purged walk-forward splitter (alphaDesign.md §7.1; leakageCritique.md finding 16). This is the ONE splitter library in AlphaForge. The Phase-6 walk-forward runner consumes it for leg layout; Phase 9/10 model cross-validation imports :class:`PurgedWalkForward` from here — a second splitter implementation anywher...
arhancanli/canli-backtest
src/alphaforge/validation/splits.py
.py
6e9e5fb0fed9b1b6
7
0
"""Every threshold a contract declares must be read by the code that enforces it. A contract is a promise about what will be checked. A threshold that sits in the JSON but is never read by ``evaluate_sleeve_evidence`` is not a weaker check -- it is *no* check, wearing the costume of one, and it reads as enforced to an...
arhancanli/canli-backtest
tests/unit/test_admission_contract_is_fully_enforced.py
.py
bc598d6b768bfb43
7.5
0
"""Unit tests for alphaforge.analytics.metrics (execDesign.md §10.1). Covers: hand-computed Sharpe/Sortino/CAGR/Calmar/MaxDD on tiny fixtures to 1e-12 (constant returns, single-dip drawdown with known depth and dates), the UTC-midnight daily aggregation boundary (the headline basis per leakageCritique.md finding 29), ...
arhancanli/canli-backtest
tests/unit/test_analytics_metrics.py
.py
0550da99586632f5
7.5
0
"""The screen that would have caught eq_ilrev before it was proposed. eq_ilrev passed EVERY conventional screen this repo runs: net Sharpe 0.69, turnover 3.0x/yr, Newey-West t +2.46, correlation under 0.05 to all four live sleeves, and R^2 0.0002 against SIZE+SPY so it was not the forbidden size/low-vol trade. It was ...
arhancanli/canli-backtest
tests/unit/test_concentration.py
.py
ec30333ee669490e
7.5
0
"""The lake writes NaN, not NULL, for a split that carries no cash. `CorporateAction.__post_init__` requires `cash_amount is None` for a SPLIT. The lake stores "no cash" as NaN, and `NaN is None` is False, so every split reaching the engine raised `ValueError("split cash_amount must be null")` and aborted the whole ru...
arhancanli/canli-backtest
tests/unit/test_corporate_action_nan_cash.py
.py
114fbbc7722c519f
7.5
0
"""CPCV per-path V[SR] — the honester within-path Sharpe variance (alphaDesign.md §7.4). The Deflated Sharpe Ratio's ``V[SR]`` is meant to be the dispersion of a config's own CombinatorialPurgedCV backtest PATHS (cpcv.py ``n_backtest_paths``), not the spread of mean Sharpe estimates ACROSS configs. This module pins th...
arhancanli/canli-backtest
tests/unit/test_cpcv_path_sharpes.py
.py
908e65305a20b846
7.5
0
"""The average pairwise correlation must carry a confidence bound, resampled jointly. The book's Sharpe ceiling is a function of the AVERAGE pairwise correlation, so that average is the number the whole fourteen-sleeve objective turns on. Admitting a candidate on its point estimate alone admits it on a statistic whose...
arhancanli/canli-backtest
tests/unit/test_diversification_average_bound.py
.py
23ec42b9b9cc5e90
7.5
0
#!/usr/bin/env python3 """ Script to augment relative links in markdown files to GitHub URLs. """ import argparse import os import re from re import Match def get_repo_root() -> str: """Get the repository root path.""" script_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.dirname(os.path...
6TcbpVB4h7jSZWz2/roboflow__supervision
.github/scripts/augment_links.py
.py
fb8deba94c44e2f7
7
0
"""Benchmark dense vs compact Roboflow RLE ingestion. Run with: uv run python examples/compact_mask/bench_inference_api.py The benchmark downloads supervision assets, runs one segmentation inference per source image, then times dense vs compact parsing of that fixed inference result. """ from __future__ import a...
6TcbpVB4h7jSZWz2/roboflow__supervision
examples/compact_mask/bench_inference_api.py
.py
4d7fa0b5360d481f
7
0
import cv2 from ultralytics import YOLO import supervision as sv from supervision.assets import VideoAssets, download_assets def download_video() -> str: download_assets(VideoAssets.PEOPLE_WALKING) return VideoAssets.PEOPLE_WALKING.value def main( source_weights_path: str, source_video_path: str | ...
6TcbpVB4h7jSZWz2/roboflow__supervision
examples/heatmap_and_track/script.py
.py
95cf032b14e24e96
7
0
import json from collections.abc import Generator import cv2 import numpy as np def load_zones_config(file_path: str) -> list[np.ndarray]: """ Load polygon zone configurations from a JSON file. This function reads a JSON file which contains polygon coordinates, and converts them into a list of NumPy...
6TcbpVB4h7jSZWz2/roboflow__supervision
examples/time_in_zone/utils/general.py
.py
61397a3fbd97e4dd
7
0
"""Private color and channel-operation fallbacks.""" from __future__ import annotations from collections.abc import Sequence from typing import Any import numpy as np import numpy.typing as npt from supervision._cv2._common import _cast_array_like_opencv from supervision._cv2.constants import ( _COLOR_BGR2GRAY,...
6TcbpVB4h7jSZWz2/roboflow__supervision
src/supervision/_cv2/_color.py
.py
3e0d1a0512e8b73e
7
0
"""Private helpers shared by OpenCV fallback implementations.""" from __future__ import annotations from typing import Any import numpy as np import numpy.typing as npt class BackendUnavailableError(RuntimeError): """Raised when an OpenCV operation is used without an available backend.""" def _cast_array_lik...
6TcbpVB4h7jSZWz2/roboflow__supervision
src/supervision/_cv2/_common.py
.py
dbf726659a51b487
7
0
"""Private Pillow-based drawing fallbacks for the OpenCV facade.""" from __future__ import annotations from collections.abc import Callable, Sequence from typing import Any import numpy as np import numpy.typing as npt from PIL import Image, ImageDraw _ImageArray = npt.NDArray[Any] _Point = tuple[int, int] def _d...
6TcbpVB4h7jSZWz2/roboflow__supervision
src/supervision/_cv2/_drawing.py
.py
53fe1b7d87fc6514
7
0
"""Private image-operation and image-I/O fallbacks.""" from __future__ import annotations from collections.abc import Sequence from typing import Any, cast import numpy as np import numpy.typing as npt from supervision._cv2._common import _cast_array_like_opencv from supervision._cv2.constants import ( _BORDER_...
6TcbpVB4h7jSZWz2/roboflow__supervision
src/supervision/_cv2/_image.py
.py
a3ee5b07e66caa03
7
0
"""Private Pillow-based text fallback for the OpenCV compatibility facade. OpenCV renders text with built-in Hershey stroke fonts. The fallback instead draws a proportional TrueType face (DejaVu Sans, shipped with Matplotlib, an existing required dependency), so glyph shapes and text metrics differ from OpenCV within ...
6TcbpVB4h7jSZWz2/roboflow__supervision
src/supervision/_cv2/_text.py
.py
7f3628ec0d175dfa
7
0
"""Private PyAV-backed video and audio fallbacks.""" from __future__ import annotations import logging import os import tempfile from collections.abc import Callable, Iterator from fractions import Fraction from pathlib import Path from typing import Any import av import numpy as np import numpy.typing as npt from ...
6TcbpVB4h7jSZWz2/roboflow__supervision
src/supervision/_cv2/_video.py
.py
c441a07c090bea27
7
0
"""CinC 2017 record loading, labels, and a preprocessed signal cache.""" from __future__ import annotations import warnings from pathlib import Path import numpy as np import pandas as pd import wfdb from heartscreen.preprocessing import FS, condition LABELS = ("N", "A", "O", "~") LABEL_TO_INDEX = {label: i for i,...
jasonjesuraja06/heartscreen
heartscreen/data.py
.py
e428f4f10220cbfe
7
0
"""Residual 1D CNN for fixed-length ECG windows with padding masks.""" from __future__ import annotations import flax.linen as nn import jax.numpy as jnp def length_mask(valid: jnp.ndarray, length: int, dtype) -> jnp.ndarray: return (jnp.arange(length)[None, :] < valid[:, None]).astype(dtype) class MaskedGrou...
jasonjesuraja06/heartscreen
heartscreen/models.py
.py
a04a0d43027be210
7
0
"""Signal conditioning and windowing for 300 Hz single-lead ECG.""" from __future__ import annotations from fractions import Fraction from functools import lru_cache import numpy as np from scipy.signal import butter, resample_poly, sosfiltfilt FS = 300 BAND = (0.5, 40.0) @lru_cache def bandpass_sos(fs: int = FS,...
jasonjesuraja06/heartscreen
heartscreen/preprocessing.py
.py
fbf1917fbbb9b076
7
0
"""Provider-neutral interfaces for producing benchmark responses.""" from __future__ import annotations import json from typing import Protocol import urllib.error import urllib.request from opsbench.prompts import render_prompt from opsbench.responses import BenchmarkResponse, parse_response_text from opsbench.scen...
jagarkarlo/opsbench
src/opsbench/adapters.py
.py
d26f32bacc19f708
7
0
"""Deterministic summaries for comparing immutable benchmark result bundles.""" from __future__ import annotations from dataclasses import dataclass from opsbench.runs import ResultBundle @dataclass(frozen=True) class ComparisonSummary: """Aggregate result totals for a single scenario and its runners.""" ...
jagarkarlo/opsbench
src/opsbench/comparisons.py
.py
d31689b4db1c1228
7
0
"""Export and import utilities for benchmark result bundles and store archives.""" from __future__ import annotations import json from pathlib import Path from typing import Any from opsbench.runs import ResultBundle, load_result_bundle from opsbench.store import RunQuery, SQLiteResultStore EXPORT_SCHEMA_VERSION = ...
jagarkarlo/opsbench
src/opsbench/export.py
.py
42e6525a857c958e
7
0
"""Structured JSON logging utilities for OpsBench platform services.""" from __future__ import annotations from datetime import datetime, timezone import json import sys from typing import Any, TextIO def format_json_log_entry( level: str, message: str, *, timestamp: str | None = None, **extra: ...
jagarkarlo/opsbench
src/opsbench/logging.py
.py
0ea5993a3febb52c
7
0
"""Local deterministic benchmark execution orchestration.""" from __future__ import annotations from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from opsbench.adapters import ResponseAdapter from opsbench.runs import ...
jagarkarlo/opsbench
src/opsbench/runner.py
.py
0d25a8efebb4f437
7
0
"""Versioned scenario contracts for reproducible OpsBench evaluations.""" from __future__ import annotations from dataclasses import dataclass import hashlib import json from pathlib import Path from typing import Any, Sequence SUPPORTED_SCHEMA_VERSION = "1.0" SUPPORTED_CATEGORIES = frozenset( { "databa...
jagarkarlo/opsbench
src/opsbench/scenarios.py
.py
762041891f2fa419
7
0
"""Storage and query interfaces for indexable benchmark result bundles.""" from __future__ import annotations from dataclasses import dataclass import json from pathlib import Path import sqlite3 from typing import Protocol, Sequence from opsbench.runs import BenchmarkRun, ResultBundle, load_result_bundle from opsbe...
jagarkarlo/opsbench
src/opsbench/store.py
.py
567a93a43ebbc7d2
7
0
"""OpenTelemetry-compatible span and trace context primitives for OpsBench.""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime, timezone import os import uuid @dataclass(frozen=True) class TraceSpan: """Immutable trace span record representing an execution phas...
jagarkarlo/opsbench
src/opsbench/tracing.py
.py
aa6ca8f251495811
7
0
"""Opus 4.8 style: verbose, multi-line, heavily documented code. This fixture reproduces the patterns that broke the V4 grep scorer. Every function here is MODERN but would false-flag under grep-based detection. """ import asyncio import subprocess from pathlib import Path from typing import TypeGuard def run_comman...
yottayoshida/modern-python-guidance
bench/fixtures/edge-cases/opus48_multiline.py
.py
63d481290e20ef95
7
0
"""Valid alternative patterns that should score VALID_ALT, not OUTDATED. SA2: sync SQLAlchemy 2.0 (create_engine + select() style) TY6: TypeGuard (broader semantics than TypeIs, still valid) AS3: TaskGroup + per-task try/except (structured concurrency without except*) """ import asyncio from sqlalchemy import create_...
yottayoshida/modern-python-guidance
bench/fixtures/edge-cases/valid_alt_patterns.py
.py
c3a21962dfdfb737
7
0
#!/usr/bin/env python3 """V6 reach-benchmark scorer. Parses --output-format stream-json transcripts (one per chained turn) plus the optional hook-shim log, and reports whether the mpg guide catalog was ever actually referenced during an organic multi-turn .py-editing session -- via a real MCP tool_use call or a real `...
yottayoshida/modern-python-guidance
bench/score_v6.py
.py
f4218df354a8ae61
7
0
#!/usr/bin/env python3 """Decide what a `uv audit` run actually established, and report it. Split out of the workflow YAML on purpose. The interesting failure here is not "a vulnerability exists" — that path is easy — but "the audit did not really look at this project and said nothing anyway". That judgement needs fix...
yottayoshida/modern-python-guidance
scripts/check_dependency_audit.py
.py
8fa5bab7b237fd32
7
0
#!/usr/bin/env python3 """Verify that an installed (non-editable) wheel bundles its skills/ and rules/ assets. The package's asset finders fall back to the source tree when the installed package lacks the assets, so this script MUST be run from outside the repository checkout against a wheel install (never ``pip insta...
yottayoshida/modern-python-guidance
scripts/verify_wheel_assets.py
.py
0e57003432566666
7
0
"""Derive the guide detection capability and target-specific check scope. This module is the single source for what the scanner can actually consume. The check engine and user-facing metadata both use these helpers so a guide cannot be reported as detectable while its effective patterns are ignored. The coverage IDs d...
yottayoshida/modern-python-guidance
src/modern_python_guidance/detection_coverage.py
.py
8743de09988d8166
7
0
"""Reverse `mpg setup`: deregister the MCP server and remove the Skills symlink.""" from __future__ import annotations import shlex import shutil import subprocess import sys from pathlib import Path from modern_python_guidance.hook_config import ( remove_hook, settings_local_path, symlinked_parent_notes...
yottayoshida/modern-python-guidance
src/modern_python_guidance/uninstall_cmd.py
.py
41e0a94a936aec5c
7
0
"""Detect the target Python version for a project. Precedence chain: 1. CLI --python-version flag (explicit override) 2. pyproject.toml [project].requires-python (PEP 621) 3. pyproject.toml [tool.poetry.dependencies].python (caret/tilde/PEP 440) 4. .python-version file (pyenv/asdf) 5. Default: 3.11 """ from...
yottayoshida/modern-python-guidance
src/modern_python_guidance/version_detect.py
.py
f7b0410cec65804f
7
0
"""Shared test helpers for modern-python-guidance.""" from __future__ import annotations import json import re from pathlib import Path _DESIGN_MD = Path(__file__).resolve().parent.parent / "docs" / "design.md" def extract_design_md_keys(section: str, variant: str | None = None) -> set[str]: """Extract JSON fi...
yottayoshida/modern-python-guidance
tests/conftest.py
.py
36cfe5efa3ef0a1c
7.5
0
"""Repository-local bootstrap for Forge2D Template tooling.""" from __future__ import annotations from pathlib import Path from typing import Sequence import sys def _repository_root() -> Path: """Return the repository root without relying on the current working directory.""" return Path(__file__).resolve(...
kleiveist/Forge2D-Template
tools/control.py
.py
42f3e580acd2e2f9
7
0
"""Locate the Forge2D Template repository and its canonical local paths.""" from __future__ import annotations from pathlib import Path from dataclasses import dataclass class RepositoryNotFoundError(RuntimeError): """Raised when no Git repository exists at or above a start path.""" @dataclass(frozen=True, sl...
kleiveist/Forge2D-Template
tools/src/g2dtool/repository.py
.py
33f0358a9843f055
7
0
"""Tests for project and toolchain configuration validation.""" from pathlib import Path from tempfile import TemporaryDirectory import textwrap import unittest from _source_path import add_source_root add_source_root() from g2dtool.config import ( ProjectConfigError, ToolchainConfigError, load_project_...
kleiveist/Forge2D-Template
tools/tests/test_config.py
.py
69b23ca3a9ef1d78
7.5
0
"""Application service for one bounded E-book intake decision.""" from __future__ import annotations from .model import TriageLimits, TriageReport, evidence from .ports import SnapshotIssue, SnapshotReader from .preflight import EpubPreflight class TriageService: """Orchestrates snapshot capture and path-free p...
gecompat/SammlungsLotse
src/sammlungslotse/ebook_intake/application.py
.py
da82da5c07f42f7e
7
0
"""Application gate for one explicit deep read-only tool call.""" from __future__ import annotations from .deep_model import DeepToolResult from .deep_ports import DeepReadOnlyToolPort from .model import TriageReport class DeepReadOnlyService: """Starts a tool only for the already approved immutable snapshot.""...
gecompat/SammlungsLotse
src/sammlungslotse/ebook_intake/deep_application.py
.py
7ed28fbd14a12e12
7
0
"""Provider-neutral application port for deep read-only evidence.""" from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol from .deep_model import DeepToolResult from .model import Snapshot if TYPE_CHECKING: from .deep_workspace import TaskWorkspace @d...
gecompat/SammlungsLotse
src/sammlungslotse/ebook_intake/deep_ports.py
.py
d85f7ee24d8e83b4
7
0
"""EPUBCheck adapter behind the provider-neutral deep read-only port.""" from __future__ import annotations import hashlib import json from dataclasses import replace from pathlib import Path, PurePosixPath from .deep_model import DeepEffects, DeepFinding, DeepLocation, DeepToolResult from .deep_ports import Process...
gecompat/SammlungsLotse
src/sammlungslotse/ebook_intake/epubcheck_provider.py
.py
f606b5fc3e118445
7
0
"""Ports used by the WI-0004 application service.""" from __future__ import annotations from typing import Protocol from .model import Scalar, Snapshot, TriageLimits class SnapshotIssue(RuntimeError): """A bounded, path-free input rejection that produces a normal report.""" def __init__( self, ...
gecompat/SammlungsLotse
src/sammlungslotse/ebook_intake/ports.py
.py
03ef7072762c67ac
7
0
""" Final answer generation with inline citations: takes a question + retrieved Document objects, numbers them as sources, and asks the LLM to cite which source(s) support each part of its answer using [n] markers. The markers are then resolved back to real chunk metadata for display. """ import re import time import ...
adityavidiyala/FinSage
src/finance_rag/generation/answer.py
.py
ca40bb371f405e20
7
0
""" Converts semantic chunk dicts (from chunker.py) into LangChain Document objects, ready for embedding. Table chunks get an LLM summary + deterministic text rendering merged into the page content; text chunks pass through unchanged. """ import json from langchain_core.documents import Document from finance_rag.ingest...
adityavidiyala/FinSage
src/finance_rag/indexing/documents.py
.py
e8ca0ef2792cbeb3
7
0
""" Semantic chunking: walks a parsed docling document and produces token-bounded, heading-aware chunks, keeping tables as their own standalone chunks. """ import re from pathlib import Path from transformers import AutoTokenizer from finance_rag.config import EMBED_MODEL, PDF_PATH, MAX_TOKENS, OVERLAP_TOKENS _toke...
adityavidiyala/FinSage
src/finance_rag/ingestion/chunker.py
.py
4d26c0a36ea023c8
7
0
""" PDF parsing via docling, with local JSON caching so re-runs skip the slow parse step. """ from collections import Counter from docling.document_converter import DocumentConverter, PdfFormatOption from docling.datamodel.pipeline_options import PdfPipelineOptions from docling_core.types.doc import DoclingDocument ...
adityavidiyala/FinSage
src/finance_rag/ingestion/parser.py
.py
e6845d65fefff4c3
7
0
""" Local latency + token/cost logging: wraps a pipeline stage, timing it and optionally recording token usage, writing one CSV row per call. Complementary to LangSmith (Step 26) — this is data you own and can chart without needing API access to your LangSmith project. """ import os import csv import time from datetim...
adityavidiyala/FinSage
src/finance_rag/observability/tracing.py
.py
f3e02977a4d65bf6
7
0
""" Top-level orchestration. Three entry points: build_index() — run once: parse -> chunk -> build docs -> embed+upsert -> cache docs for BM25. build_retriever() — run once per process: rebuilds BM25 + connects Qdrant + loads reranker. answer_query() — run per question, given an already-built retriever...
adityavidiyala/FinSage
src/finance_rag/pipeline.py
.py
0cd913bd9ecf9bcf
7
0
"""CLI: python -m i2i_watch [--iterations N] [--interval S] [-v] Default (no subcommand): scrape/monitor loop. Self-loop (--iterations>1) approximates sub-hourly polling inside one GitHub Actions run. Subcommands: invest [--live] place investments (dry-run unless --live) cancel <loanId>… [--live] reve...
chirag127/i2i-yield-watch
src/i2i_watch/__main__.py
.py
43941886ea7af068
7
0
"""i2iFunding auth — pure login. AES-encrypt the password the way the SPA does (CryptoJS AES.encrypt(pw, passphrase), passphrase from i2i's main.js — proven by decrypting a captured login blob), POST /login/, return fresh tokens. Fresh session_id + csrf_token EVERY run removes the short-lived-session expiry that made ...
chirag127/i2i-yield-watch
src/i2i_watch/auth.py
.py
3546bc01bd99cf63
7
0
"""Telegram command bot — re-trigger workflows by message. The owner sends "/invest", "/scrape", "/status", "/help" … to the i2i bot and this module long-polls Telegram, dispatches the matching GitHub Actions workflow through the REST API (GITHUB_TOKEN, needs actions:write), and replies in the same chat. Runs as a sel...
chirag127/i2i-yield-watch
src/i2i_watch/bot.py
.py
1527fd9b22a728bc
7
0
"""Telegram + ntfy notifiers. Both read config from env and no-op cleanly when unconfigured. Telegram uses HTML parse_mode: each loan is a block whose bold first line (Rate + Yield) is a clickable link to the loan's i2iFunding profile, followed by label-free info lines. Messages chunk to Telegram's 4096 limit. """ fro...
chirag127/i2i-yield-watch
src/i2i_watch/notify/channels.py
.py
c238ebfca6ca8139
7
0
"""Yield scoring engine — opportunity score (higher rate = better), NOT a risk score. High rates never penalized. Ranking importance (both notify sort and auto-invest select): 1. RETURN — the loan's interest rate / expected return (top weight). 2. CREDIT SCORE of the borrower. 3. TENURE — longer locks the high r...
chirag127/i2i-yield-watch
src/i2i_watch/scorer.py
.py
b58d38286db1d4d0
7
0
"""Convert raw i2iFunding API rows (pl_*/bloan_*/usr_* fields) into the normalized loan dict the dashboard, storage, and notifiers expect. Output shape matches the legacy Node parser exactly so `dashboard/` needs no changes. """ from __future__ import annotations import logging from urllib.parse import quote from .s...
chirag127/i2i-yield-watch
src/i2i_watch/transform.py
.py
545c2e342ff36901
7
0
"""Shared helpers: number/date parsing, NA detection, logging.""" from __future__ import annotations import logging import re import sys from datetime import datetime, timezone log = logging.getLogger("i2i_watch") _NA_RE = re.compile(r"^(n/?a|na|null|none|-|unknown|#####)$", re.IGNORECASE) def configure_logging(v...
chirag127/i2i-yield-watch
src/i2i_watch/util.py
.py
2504720a66012fcd
7
0
"""Shared test fixtures: repo root + raw-loan fixture loader. The autouse `_isolate_json_storage` fixture redirects the git-as-DB JSON backend's data dir to a per-test temp dir, so the suite NEVER writes into the repo's real data/ directory. Without it, tests that exercise the invest loop (invest.run -> storage.save_i...
chirag127/i2i-yield-watch
tests/conftest.py
.py
c678371cdb70a7b6
7.5
0
"""Tests for the multi-account registry: env resolution, gates, storage names.""" from __future__ import annotations import pytest from i2i_watch import accounts @pytest.fixture(autouse=True) def _clean(monkeypatch): for k in ("I2I_ACCOUNT", "I2I_ACCOUNTS", "I2I_EMAIL", "I2I_PASSWORD", ...
chirag127/i2i-yield-watch
tests/test_accounts.py
.py
84f17d1b5fb2779c
7.5
0
"""Tests for I2iClient.from_env auth chain: auto-login primary, session-token fallback. Locks the rule the user cares about: auto-login (fresh tokens, no expiry) must win whenever creds are present; I2I_CSRF_TOKEN/I2I_SESSION_ID are only a fallback for when login fails or creds are absent. """ from __future__ import ...
chirag127/i2i-yield-watch
tests/test_client_auth.py
.py
ce6782cb408645fa
7.5
0
"""Wallet balance tests: investable = availableWallet − committed funds. Locks the live-observed bug: walletAndFund returned availableWallet=₹50,000 but only ~₹21k was actually investable (the platform defines Available Balance as Current − Funds Under Proposal/Disbursal). The plan overshot the real escrow and ADD BAL...
chirag127/i2i-yield-watch
tests/test_client_wallet.py
.py
2e4bd3339cf04ecb
7.5
0
"""loanId dedup + new-loan detection (pure storage helpers, no Firestore).""" from i2i_watch.storage import detect_new_loans, detect_fully_funded, filter_unnotified def test_detect_new_loans_excludes_notified_and_existing(): fresh = [{"loanId": "1"}, {"loanId": "2"}, {"loanId": "3"}] existing = [{"loanId": "...
chirag127/i2i-yield-watch
tests/test_dedup.py
.py
9ad81699ffc53237
7.5
0
"""Parser: raw API rows -> normalized loan dict. Validates the data shape the dashboard reads (loanId/borrowerRef/interestRate/loanUrl/... plus derived yieldScore + priority + funding). Runs offline against a captured fixture. """ from i2i_watch.transform import transform_loan, transform_loans # The exact key set the...
chirag127/i2i-yield-watch
tests/test_parser.py
.py
7bbc221c60b3680a
7.5
0
"""PII-boundary canary. The public getActiveFilteredBorrowers feed carries ~240 fields per row including borrower PII (pan_card, aadhar_card, cibil_report, bank statements, ITR/Form16 docs, addresses). This repo is PUBLIC, so `transform_loan` and `invest.select` must project that away. These tests fail if a future edi...
chirag127/i2i-yield-watch
tests/test_pii_boundary.py
.py
72a73c08bea97133
7.5
0
"""Scorer: yield-score + strict multi-key sort ordering. Ranking importance: rate desc > credit desc (no-credit imputed 720) > tenure desc > income desc > amount desc. Rate/return is always the top factor. """ from i2i_watch.scorer import ( calculate_yield_score, has_no_credit, imputed_credit, get_pri...
chirag127/i2i-yield-watch
tests/test_scorer.py
.py
ba522950faefefff
7.5
0
"""Offline tests for the Playwright fallback helpers; no browser or network.""" from i2i_watch.sources import i2i class _FakePage: def __init__(self, state, advance_on_wait=None): self.state = state self.advance_on_wait = advance_on_wait self.waits = [] def wait_for_timeout(self, mil...
chirag127/i2i-yield-watch
tests/test_sources.py
.py
7892d13c0d271d4d
7.5
0
"""Storage JSON (git-as-DB) backend works without firebase_admin importable.""" import builtins import json import pytest import i2i_watch.storage as storage @pytest.fixture def json_backend(tmp_path, monkeypatch): """Force JSON mode: block firebase_admin import + redirect data dir to tmp.""" real_import =...
chirag127/i2i-yield-watch
tests/test_storage_json.py
.py
25ad4f90007268b2
7.5
0
"""Static guard against workflow env overrides drifting from code policy.""" from pathlib import Path from i2i_watch import config as C ROOT = Path(__file__).parents[1] def _text(name: str) -> str: return (ROOT / ".github" / "workflows" / name).read_text(encoding="utf-8") def test_scraper_notification_overr...
chirag127/i2i-yield-watch
tests/test_workflow_gate_consistency.py
.py
43e30cc195719e34
7.5
0
"""Benchmark workload matrix; names encode kind, key parameters, and request rate.""" from __future__ import annotations from dataclasses import dataclass @dataclass(frozen=True) class WorkloadConfig: name: str kind: str # "sharegpt" | "agent" | "ablation" request_rate: float num_requests: int ...
jasonjesuraja06/clockwork
clockwork/bench/configs.py
.py
61f1260d362f0b45
7
0
"""Nearest-rank percentile math and per-workload summaries over runner CSVs.""" from __future__ import annotations import csv import math from pathlib import Path def percentile(values: list[float], pct: float) -> float: """Nearest-rank percentile: the ceil(pct / 100 * n)-th smallest value.""" # Nearest-ran...
jasonjesuraja06/clockwork
clockwork/bench/metrics.py
.py
bee996f0d681f019
7
0
"""Async wrapper: background step loop with per-request streaming queues.""" from __future__ import annotations import asyncio import threading from collections.abc import AsyncIterator from clockwork.config import EngineConfig from clockwork.engine.llm_engine import LLMEngine from clockwork.engine.sequence import R...
jasonjesuraja06/clockwork
clockwork/engine/async_engine.py
.py
c8cc75685d6c1e43
7
0