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
"""Tests for downloader orchestrator.""" from __future__ import annotations import asyncio from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch import pytest from pahebatcher.downloader import BatchOrchestrator, EpisodeDownloader from pahebatcher.models import AnimeInfo, AppContext, Episod...
smolfiddle/pahebatcher
tests/test_downloader.py
.py
380945c14b7a656c
8.13
17
"""Tests for M3U8 parser.""" from __future__ import annotations from unittest.mock import patch from pahebatcher.extract.m3u8 import parse_m3u8 class TestParseM3U8: def test_simple_playlist(self) -> None: content = """#EXTM3U #EXT-X-TARGETDURATION:10 #EXT-X-MEDIA-SEQUENCE:0 #EXTINF:10.0, segment1.ts #E...
smolfiddle/pahebatcher
tests/test_m3u8.py
.py
ad4843e0cf6a742e
7.13
17
"""Extended SegmentStore tests — atomicity, cleanup, assemble.""" from __future__ import annotations from pathlib import Path from unittest.mock import MagicMock, patch from pahebatcher.store import SegmentStore class TestStoreAtomic: def test_write_uses_tmp_then_rename(self, tmp_path: Path) -> None: c...
smolfiddle/pahebatcher
tests/test_store_extended.py
.py
faa759f663c75411
8.13
17
"""Tests for TLS context.""" from __future__ import annotations import ssl from pahebatcher.tls import make_ssl_ctx class TestTLS: def test_minimum_version(self) -> None: ctx = make_ssl_ctx() assert ctx.minimum_version == ssl.TLSVersion.TLSv1_2 def test_verify_mode(self) -> None: c...
smolfiddle/pahebatcher
tests/test_tls.py
.py
69bd9e7ecf1a54f4
8.13
17
"""Tests for UI helpers.""" from __future__ import annotations from pathlib import Path from unittest.mock import MagicMock from rich.table import Table from pahebatcher.models import AnimeInfo, EpisodeInfo from pahebatcher.ui.tables import episode_table, search_results_table, summary_table class TestTables: ...
smolfiddle/pahebatcher
tests/test_ui.py
.py
42a8b12edc1a025b
8.13
17
"""Extended tests for utils — fmt_bytes precision and edge cases.""" from __future__ import annotations from pahebatcher.models import EpisodeInfo from pahebatcher.utils import compact_ep_range, ep_prefix, fmt_bytes, sanitize class TestFmtBytesPrecision: def test_zero(self) -> None: assert fmt_bytes(0) ...
smolfiddle/pahebatcher
tests/test_utils_extended.py
.py
ce93cd1691e4772f
8.13
17
#!/usr/bin/env python3 # /* # * Copyright Said Sef # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * You may obtain a copy of the License at # * # * https://www.apache.org/licenses/LICENSE-2.0 # * # * Unless re...
saidsef/mcp-github-pr-issue-analyser
src/mcp_github/activity.py
.py
b863f3284449440b
7.42
6
#!/usr/bin/env python3 # /* # * Copyright Said Sef # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * You may obtain a copy of the License at # * # * https://www.apache.org/licenses/LICENSE-2.0 # * # * Unless re...
saidsef/mcp-github-pr-issue-analyser
src/mcp_github/auth.py
.py
e05ed7443ae195f0
7.42
6
#!/usr/bin/env python3 # /* # * Copyright Said Sef # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * You may obtain a copy of the License at # * # * https://www.apache.org/licenses/LICENSE-2.0 # * # * Unless re...
saidsef/mcp-github-pr-issue-analyser
src/mcp_github/exceptions.py
.py
8a81f8cc19e9e67a
7.42
6
#!/usr/bin/env python3 # /* # * Copyright Said Sef # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * You may obtain a copy of the License at # * # * https://www.apache.org/licenses/LICENSE-2.0 # * # * Unless re...
saidsef/mcp-github-pr-issue-analyser
src/mcp_github/issues_pr_analyser.py
.py
951c9a24110470c5
7.42
6
#!/usr/bin/env python3 # /* # * Copyright Said Sef # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * You may obtain a copy of the License at # * # * https://www.apache.org/licenses/LICENSE-2.0 # * # * Unless re...
saidsef/mcp-github-pr-issue-analyser
src/mcp_github/tool_annotations.py
.py
5cacee28402051d5
7.42
6
"""Tests for environment flag parsing in issues_pr_analyser.""" import subprocess import sys from unittest.mock import patch import pytest from mcp_github.issues_pr_analyser import MCP_ENABLE_REMOTE, _env_enabled class TestEnvEnabled: """Which environment variable values switch a flag on.""" @pytest.mark....
saidsef/mcp-github-pr-issue-analyser
tests/test_config.py
.py
0509be0d03c15a52
7.92
6
"""Tests for the MCP server lifespan.""" from __future__ import annotations from unittest.mock import AsyncMock, patch import pytest from starlette.testclient import TestClient from mcp_github.issues_pr_analyser import PRIssueAnalyser def _analyser() -> PRIssueAnalyser: with patch("mcp_github.github_integrati...
saidsef/mcp-github-pr-issue-analyser
tests/test_server.py
.py
bd580492c7131d88
7.92
6
#!/usr/bin/env python3 """ CPython runtime differential harness. Validates that pyrift rules agree with empirically observed runtime behaviour differences across CPython versions. Each entry maps a rule to: - which runtime probe confirms it, - what the expected transition is, - which versions are affected, - which ve...
BHUVANSH855/PyRift
benchmark/runtime_harness.py
.py
ee5b52ed4868d40b
7.48
8
""" pyrift.analysis.calls ~~~~~~~~~~~~~~~~~~~~~ Shared call detection utilities. Answers common questions: - Is function X called? - Is method X called on object Y? - What arguments were passed? """ from __future__ import annotations import ast from dataclasses import dataclass @dataclass class CallInfo: ...
BHUVANSH855/PyRift
pyrift/analysis/calls.py
.py
269ba9d7739dfd17
7.48
8
""" pyrift.analysis.imports ~~~~~~~~~~~~~~~~~~~~~~~ Shared import detection utilities used by multiple rules. Instead of every rule walking the AST and checking isinstance(n, ast.Import), rules can use these helpers to answer common questions: - Is module X imported? - Is name Y imported from module X? - What al...
BHUVANSH855/PyRift
pyrift/analysis/imports.py
.py
45b96f5e68045c27
7.48
8
""" pyrift.analysis.scope ~~~~~~~~~~~~~~~~~~~~~ Lightweight scope utilities for pyrift rules. Answers: - Is this code at module level? - Is this code inside a class? - Is this code inside a function? """ from __future__ import annotations import ast def is_module_level(node: ast.AST, paren...
BHUVANSH855/PyRift
pyrift/analysis/scope.py
.py
5820ec01f80cc3a5
7.48
8
""" pyrift.base_rule ~~~~~~~~~~~~~~~~ Every rule inherits from BaseRule. """ from __future__ import annotations import ast from abc import ABC, abstractmethod from typing import TYPE_CHECKING from .finding import Finding if TYPE_CHECKING: from .targets import TargetConfig class BaseRule(ABC): """Abstract ...
BHUVANSH855/PyRift
pyrift/base_rule.py
.py
19d225467cd65884
7.48
8
""" pyrift.baseline ~~~~~~~~~~~~~~~ Persistent baseline support for compatibility findings. """ from __future__ import annotations import json from pathlib import Path from .finding import Finding from .fingerprint import finding_fingerprint BASELINE_VERSION = 1 DEFAULT_BASELINE_FILE = ".pyrift-baseline.json" clas...
BHUVANSH855/PyRift
pyrift/baseline.py
.py
33c684c76f970594
7.48
8
""" pyrift.finding ~~~~~~~~~~~~~~ The Finding dataclass — every rule returns a list of these. """ from __future__ import annotations from dataclasses import dataclass from enum import Enum class Severity(str, Enum): ERROR = "error" WARNING = "warning" INFO = "info" class Confidence(str, Enum): """H...
BHUVANSH855/PyRift
pyrift/finding.py
.py
814519f662129a09
7.48
8
""" pyrift.fingerprint ~~~~~~~~~~~~~~~~~~ Stable identities for compatibility findings. A finding fingerprint is used to identify the same logical compatibility issue across scans. The fingerprint intentionally does not include the source line number because normal code movement should not make an existing finding ap...
BHUVANSH855/PyRift
pyrift/fingerprint.py
.py
07fdbd964787e3cf
7.48
8
"""Streamlit integration for pyvista-wasm. Provides components for displaying pyvista-wasm visualizations in Streamlit and stlite. """ from __future__ import annotations import json from pathlib import Path from typing import TYPE_CHECKING from jinja2 import Environment, StrictUndefined if TYPE_CHECKING: from ...
tkoyama010/pyvista-wasm
src/pyvista_wasm/streamlit_integration.py
.py
80e4b04cb1a7a14a
7.45
7
"""Texture class for pyvista-wasm. Provides surface texture support compatible with PyVista API. """ from __future__ import annotations class Texture: """Surface texture wrapping an image URL. Mirrors the PyVista :class:`pyvista.Texture` API for browser-based rendering via VTK.wasm. A texture is applie...
tkoyama010/pyvista-wasm
src/pyvista_wasm/texture.py
.py
7c19ec4309ea8dd9
7.45
7
"""Test the planet surface example helper.""" from pyvista_wasm import Texture, examples class TestDownloadMarsSurface: """Tests for examples.download_mars_surface.""" def test_returns_texture(self) -> None: """download_mars_surface returns a Texture instance.""" texture = examples.download_...
tkoyama010/pyvista-wasm
tests/test_examples.py
.py
2a5df7685197c4ab
7.95
7
"""Test package initialization and metadata.""" import pytest import pyvista_wasm def test_import() -> None: """Test that package can be imported.""" assert pyvista_wasm is not None @pytest.mark.parametrize( ("attr", "expected"), [ ("__author__", "Tetsuo Koyama"), ("__license__", "...
tkoyama010/pyvista-wasm
tests/test_init.py
.py
e034896aca46dfa9
7.95
7
"""Tests for Light class and lighting configuration.""" import pyvista_wasm as pv def test_light_basic_properties() -> None: """Test basic light property access.""" light = pv.Light(position=(1, 2, 3), color="red", intensity=0.5) assert light.position == (1, 2, 3) assert light.color == (1.0, 0.0, 0.0...
tkoyama010/pyvista-wasm
tests/test_light.py
.py
5ad51008e8edcbae
7.95
7
"""Tests for the Text class.""" import pytest import pyvista_wasm as pv from pyvista_wasm.text import Text, TextProperty def test_text_defaults() -> None: """Test Text default values.""" text = Text() assert text.input == "Text" assert text.position == (0.5, 0.5) assert text.prop is not None ...
tkoyama010/pyvista-wasm
tests/test_text.py
.py
70972081adea5d7e
7.95
7
# custom_strategies/sma_crossovers.py """SMA Crossover strategy plugin. Both variants are registered automatically when this module is imported via ``load_strategies("custom_strategies")``. No edits to ``strategies.py`` or ``main.py`` are needed to add, remove, or rename them. To add another SMA pair, copy one of th...
zachisit/july-backtester
custom_strategies/sma_crossovers.py
.py
f6a49f2f640e10d1
7.48
8
# helpers/aws_utils.py import os import boto3 import logging logger = logging.getLogger(__name__) def upload_file_to_s3(local_filepath, s3_bucket, s3_key): """ Uploads a local file to a specified S3 bucket and key. Args: local_filepath (str): Path to the file on the local machine. s3_buc...
zachisit/july-backtester
helpers/aws_utils.py
.py
e9c181600e0aa22a
7.48
8
# helpers/caching.py (Corrected for safe filenames) import os import pandas as pd from datetime import datetime, timedelta import logging from helpers.filename_utils import sanitize_symbol_for_filename as _sanitize_filename logger = logging.getLogger(__name__) # --- CONFIGURABLE SETTINGS --- CACHE_DIR = "data_cache...
zachisit/july-backtester
helpers/caching.py
.py
f984b8795b36e73f
7.48
8
# helpers/comparison_tickers.py """ Comparison ticker configuration parser and validator. Parses CONFIG["comparison_tickers"] and provides structured data for: 1. Buy & Hold benchmarking (benchmarks) 2. Strategy dependency injection (dependencies) Public API ---------- parse_comparison_tickers(config) -> dict Par...
zachisit/july-backtester
helpers/comparison_tickers.py
.py
dfe8113a34c49c83
7.48
8
"""helpers/continuous_contract.py Build a back-adjusted **continuous** futures series from individual contract-month frames, and validate pre-built continuous series (from CSV/Parquet). Polygon's futures API (and most raw vendors) return per-contract data — there is no native continuous series. Multi-year backtests n...
zachisit/july-backtester
helpers/continuous_contract.py
.py
c000f1cb5aa33ab7
7.48
8
# helpers/correlation.py """ Strategy correlation analysis. Builds a daily P&L time-series for each strategy from its completed trade log, computes pairwise Pearson correlations, identifies highly correlated pairs, and saves the matrix to a CSV file. Public API ---------- run_correlation_analysis(strategy_results, ou...
zachisit/july-backtester
helpers/correlation.py
.py
c5c6ec4ec58d5763
7.48
8
"""helpers/data_quality.py Pre-flight data quality validation for OHLCV data. Detects common data issues that silently corrupt backtest results: 1. Missing bars (gaps in expected calendar) 2. Price jumps >20% (potential unadjusted splits) 3. Zero volume days 4. OHLC relationship violations 5. Negative prices 6. Dupli...
zachisit/july-backtester
helpers/data_quality.py
.py
16238a6542bb4db2
7.48
8
"""helpers/filename_utils.py Shared filename-sanitization logic used by services and scripts. """ # Characters illegal in Windows (and generally problematic) filenames. _ILLEGAL_CHARS = r'\/:*?"<>|' # Comparison operators map to distinct semantic tokens *before* the generic # illegal-char scrub, so paired sweep conf...
zachisit/july-backtester
helpers/filename_utils.py
.py
b2064c61faa61236
7.48
8
"""helpers/intrabar.py Sub-bar (intraday) resolution for the daily execution engine (Phase 5 of the instrument-metadata rewrite, issue #229). A single daily OHLC bar can't say *when* within the day a level was hit, so the daily engine makes an optimistic assumption: a stop fills exactly at the stop level whenever ``L...
zachisit/july-backtester
helpers/intrabar.py
.py
896c57ea2a897a1a
7.48
8
# helpers/monte_carlo.py import pandas as pd import numpy as np from tqdm import tqdm from config import CONFIG def _equity_and_drawdown(sampled_trades, initial_equity): """Compute final equity and max drawdown for a single simulated path.""" equity_path = np.concatenate(([initial_equity], initial_equity + n...
zachisit/july-backtester
helpers/monte_carlo.py
.py
1606d5a180e9ee73
7.48
8
"""helpers/noise.py Price noise injection for stress-testing strategy robustness. Applies independent uniform random multipliers to each OHLC cell, then reconstructs High = row-wise max(O,H,L,C) and Low = row-wise min(O,H,L,C) to guarantee that every candlestick remains valid after perturbation. Volume, index, and a...
zachisit/july-backtester
helpers/noise.py
.py
705089062623c980
7.48
8
"""helpers/position_sizing.py Position sizing algorithms for portfolio risk management. Supports 4 methods: 1. Fixed % allocation (current default) 2. Kelly Criterion (optimal growth) 3. Volatility parity (inverse ATR) 4. Risk parity (equal $ risk per position) """ from __future__ import annotations import logging ...
zachisit/july-backtester
helpers/position_sizing.py
.py
973916599d7465c6
7.48
8
# helpers/sensitivity.py """ Parameter sensitivity sweep utilities. Builds a grid of param dicts by varying each numeric param in a strategy's base param dict by ±pct across ±steps steps, then provides labelling helpers for naming each variant in results output. Public API ---------- build_param_grid(params, pct, ste...
zachisit/july-backtester
helpers/sensitivity.py
.py
de6ee0f91cc0b139
7.48
8
# helpers/simulations.py import pandas as pd import numpy as np from config import CONFIG def calculate_advanced_metrics(pnl_list, portfolio_timeline, duration_list): metrics = {"max_drawdown": 0, "profit_factor": 0, "win_rate": 0, "sharpe_ratio": 0, "calmar_ratio": 0, "avg_trade_duration": 0} if not pnl_list...
zachisit/july-backtester
helpers/simulations.py
.py
ce1f03e8a27dfbcd
7.48
8
"""Asset-class-aware smoothness verdict profiles. The curve-smoothness verdict in :mod:`helpers.llm_verdict` grades an equity curve SMOOTH / ACCEPTABLE / ROUGH by counting how many of five failure conditions trip. Historically those five thresholds were hard-coded constants chosen for a steadily-compounding, many-name...
zachisit/july-backtester
helpers/smoothness_profiles.py
.py
f4e7ecf886ebcf19
7.48
8
# helpers/timeframe_utils.py def get_bars_for_period(period_str: str, timeframe: str, multiplier: int = 1) -> int: """ Translates a time period string (e.g., '200d', '50h') into the number of bars required for a given chart timeframe ('D', 'H', 'MIN'). This is essential for making strategies timeframe...
zachisit/july-backtester
helpers/timeframe_utils.py
.py
2c522afbc2528ac9
7.48
8
"""Ask endpoint: routes prompts through context router to local LLM.""" import json from uuid import UUID from typing import Optional from fastapi import APIRouter, Depends, HTTPException, Query from fastapi.responses import StreamingResponse from pydantic import BaseModel from sqlalchemy.ext.asyncio import AsyncSess...
Khaled-Saleh-KL1/9XAIPal
backend/app/api/v1/endpoints/ask.py
.py
e43abf14dbdcef6a
7.42
6
"""Auth endpoints: signup (invite-code gated), login, logout, and /me. Session is a Redis-backed opaque token in an httponly cookie — see app.core.auth. `SameSite=Lax` is sufficient here without a separate CSRF token: these are JSON POSTs with a non-simple Content-Type, so a cross-origin request needs a CORS preflight...
Khaled-Saleh-KL1/9XAIPal
backend/app/api/v1/endpoints/auth.py
.py
d1f8a8ae5a8d7552
7.42
6
"""Note endpoints: the anchored margin annotations that replaced the chat pane. A note is created, answered, and persisted in one streaming request. There is no router, no guardrail, no conversation compaction on this path — see app.chat.paper_agent for why none of that applies. """ import json from uuid import UUID ...
Khaled-Saleh-KL1/9XAIPal
backend/app/api/v1/endpoints/notes.py
.py
dbfd1a9ad978ad56
7.42
6
"""Sticky-note endpoints: the two boards. `board=chat` is the strip beside one conversation, keyed by `scope` (a study id or the literal `library`). `board=universal` is the standalone board. ⚠ **Deleting is reader-only, and that is a structural fact rather than a check here.** The assistant creates and edits notes b...
Khaled-Saleh-KL1/9XAIPal
backend/app/api/v1/endpoints/stickies.py
.py
64fb1aad32e045cb
7.42
6
"""Citation formatting for chunks and external sources.""" from typing import Optional from uuid import UUID from app.schemas.chat import Citation def citations_from_chunks(chunks: list[dict]) -> list[Citation]: """Create citations from retrieved chunks.""" citations = [] for c in chunks: citati...
Khaled-Saleh-KL1/9XAIPal
backend/app/chat/citations.py
.py
046320298fb3e221
7.42
6
"""External context builder: web search via the configured provider. This app is exclusively about technology / computer-science research papers (machine learning, NLP, systems, hardware, etc.), so we bias the web search toward that domain instead of running the raw user query — otherwise an ambiguous term like "trans...
Khaled-Saleh-KL1/9XAIPal
backend/app/chat/external_context.py
.py
7b32fe4aa5497967
7.42
6
"""Research Agent: hybrid, model-driven, iterative external research. This implements the "model decides it needs to research + iterative study + feed back to same model for synthesis" capability requested for knowledge-gap cases (brand new papers, external technologies the model has never seen, etc.). Design princip...
Khaled-Saleh-KL1/9XAIPal
backend/app/chat/research_agent.py
.py
0de0e37fc89f7457
7.42
6
"""Context router: classifies prompts into LOCAL, GLOBAL, EXTERNAL, or OVERVIEW. OVERVIEW is special: it triggers the pre-computed high-quality hierarchical section summaries (and paper-level executive overview) instead of vector search. This path exists to give the author the best possible answers to "what is this pa...
Khaled-Saleh-KL1/9XAIPal
backend/app/chat/router.py
.py
e8f9083e2298c36c
7.42
6
"""Structured logging configuration.""" import logging import sys from typing import Optional def setup_logging(level: str = "INFO") -> None: """Configure structured logging for the application.""" root = logging.getLogger() root.setLevel(getattr(logging, level.upper(), logging.INFO)) if not root.ha...
Khaled-Saleh-KL1/9XAIPal
backend/app/core/logging.py
.py
89802689417ed8a1
7.42
6
"""Centralized filesystem path management.""" from pathlib import Path from typing import Optional, Union from uuid import UUID from app.core.config import settings def _root() -> Path: return Path(settings.storage_root) def documents_dir() -> Path: return _root() / "documents" def extracted_dir() -> Pa...
Khaled-Saleh-KL1/9XAIPal
backend/app/core/paths.py
.py
1b8a6913923164dd
7.42
6
"""Async Redis client, shared by session storage (see app.core.auth). Redis is already a hard dependency (Celery broker/backend), but nothing async touches it anywhere else in this codebase — Celery owns its own connection internally. This is a separate, small client for the request path. """ from typing import Optio...
Khaled-Saleh-KL1/9XAIPal
backend/app/core/redis.py
.py
6526bc5986c1b8d5
7.42
6
"""Security middlewares: response headers and per-IP rate limiting. Both are dependency-free on purpose — this app targets "my machine = LAN server" deployments where pulling in Redis-backed limiters is overkill, but leaving the API completely unthrottled invites accidental (polling bugs) and deliberate (scripted) ham...
Khaled-Saleh-KL1/9XAIPal
backend/app/core/security.py
.py
adf5a470ab1802fe
7.42
6
"""PostgreSQL async engine and session factory.""" from collections.abc import AsyncGenerator from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy import text from app.core.config import settings from app.core.logging import get_logger logger = get_logger(__name__...
Khaled-Saleh-KL1/9XAIPal
backend/app/database/connection.py
.py
a0b94c3dab226f3d
7.42
6
"""pgvector operations: insert, search, and index management.""" from uuid import UUID from typing import Optional from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from app.core.config import settings from app.core.logging import get_logger logger = get_logger(__name__) def _vector_lite...
Khaled-Saleh-KL1/9XAIPal
backend/app/database/pgvector.py
.py
c86eaba1c24bf1b8
7.42
6
import logging import orjson import pyarrow as pa import pyarrow.compute as pc from millpond import metrics log = logging.getLogger(__name__) def _drop_null_typed_columns(table: pa.Table) -> pa.Table: """Drop columns whose Arrow type is ``pa.null()`` before they reach a Sink. In normal use ``_build_schema...
PostHog/millpond
millpond/arrow_converter.py
.py
cd0c4cb0e944f4e4
7.48
8
"""Adaptive batch sizing based on buffer fullness. Implements proportional backpressure: when the pending buffer approaches the flush threshold, reduce the consume batch size to smooth throughput. When the buffer is mostly empty, consume at full speed. fullness = pending_bytes / flush_size # 0.0 to 1.0+ ...
PostHog/millpond
millpond/backpressure.py
.py
894ed5395364cf53
7.48
8
import logging import os import orjson from confluent_kafka import OFFSET_INVALID, OFFSET_STORED, Consumer, KafkaException, TopicPartition from confluent_kafka.admin import AdminClient, OffsetSpec from millpond import metrics from millpond.config import Config log = logging.getLogger(__name__) def _maybe_attach_oa...
PostHog/millpond
millpond/consumer.py
.py
490f4b8c65abcc4f
7.48
8
"""Structured-logging setup for the millpond writer. Two-phase by design: - ``setup_stdout()`` — called BEFORE ``config.load()`` so that config-load errors land on a structured stdout sink rather than Python's default plain-text root. - ``attach_posthog_otlp(cfg)`` — called AFTER ``config.load()`` onc...
PostHog/millpond
millpond/logging_config.py
.py
bc662e9347039af7
7.48
8
from prometheus_client import Counter, Gauge, Histogram class _AutoCommonLabels: """Wrapper that auto-injects common labels (pipeline, broker_source) into .labels() calls.""" def __init__(self, metric, pipeline: str, broker_source: str): self._metric = metric self._pipeline = pipeline ...
PostHog/millpond
millpond/metrics.py
.py
327dbf9644e39a3d
7.48
8
"""Schema evolution for DuckLake tables. Compares incoming Arrow schema against the existing DuckLake table schema and issues DDL to reconcile: - New columns → ALTER TABLE ADD COLUMN IF NOT EXISTS - Wider types → ALTER TABLE ALTER COLUMN SET DATA TYPE (DuckLake enforces widening-only) - Incompatible changes → lo...
PostHog/millpond
millpond/schema.py
.py
4b4b0e55c97ea31c
7.48
8
import logging import threading import time from http.server import BaseHTTPRequestHandler, HTTPServer from prometheus_client import CONTENT_TYPE_LATEST, generate_latest log = logging.getLogger(__name__) class _HealthState: """Tracks recency of poll and flush for health checks.""" def __init__(self, max_po...
PostHog/millpond
millpond/server.py
.py
0005adcd3710b0a3
7.48
8
"""Structured-logging building blocks. Millpond emits JSON logs to stdout and (optionally) exports OTLP/HTTP log records to PostHog Logs. This module provides the service-agnostic pieces: - ``JsonFormatter`` — base JSON formatter. Subclasses override ``extra_context()`` to inject per-record fields from ContextV...
PostHog/millpond
millpond/structured_logging.py
.py
990ed024dd1870d9
7.48
8
"""E2E test for the full docker-compose stack. Brings up Kafka, Postgres, MinIO, producer, and Millpond via testcontainers, then verifies records flow through to DuckLake. Usage: just test-e2e uv run python -m pytest tests/e2e/test_e2e.py -v -s """ import time from pathlib import Path import duckdb import p...
PostHog/millpond
tests/e2e/test_e2e.py
.py
a569865bc730ef1b
7.98
8
"""Shared integration fixtures. The `conn` fixtures inside individual test modules attach a plain in-memory DuckDB as `lake`, which never writes Parquet. That is fine for SQL-shape assertions but structurally cannot exercise the physical write — VARIANT shredding, data inlining, file layout — so bugs living there (the...
PostHog/millpond
tests/integration/conftest.py
.py
f197fc28d842a458
7.98
8
"""Catalog-wide compaction must survive one poisoned table (real DuckLake). Builds a real local DuckLake (duckdb-file metadata + local data dir, stock ducklake extension), two hive-partitioned tables with several small files each, then rewrites half of one table's file paths in the metadata to a divergent hive directo...
PostHog/millpond
tests/integration/test_compaction_isolation_integration.py
.py
43477f7ed6c334f7
7.98
8
"""Engine-behavior contract for the pinned DuckDB + DuckLake build. `tests/unit/test_ducklake_pin.py` pins WHICH build we run; this file pins the physical behaviors millpond's variant guard ASSUMES of that build, probed the way the 2026-08-12 incident actually executed: raw `try_cast(... AS VARIANT)` INSERTs against a...
PostHog/millpond
tests/integration/test_ducklake_engine_contract.py
.py
a0f0891c01142c93
7.98
8
"""Integration test for tools/ducklake_metrics.py. Wires the daemon's components together against an in-memory DuckDB acting as a stub DuckLake catalog: builds the gauges, starts the HTTP server on an ephemeral port, runs the scheduler in a background thread, and scrapes /metrics + the health endpoints over real HTTP....
PostHog/millpond
tests/integration/test_ducklake_metrics_integration.py
.py
9b89ab7577c6be25
7.98
8
from datetime import UTC, datetime from unittest.mock import patch import orjson import pyarrow as pa from millpond.arrow_converter import _drop_null_typed_columns, coerce_typed_columns, convert class TestConvert: def test_basic(self): messages = [ orjson.dumps({"name": "alice", "age": 30}),...
PostHog/millpond
tests/unit/test_arrow_converter.py
.py
69ca09c89d701042
7.98
8
from unittest.mock import MagicMock, patch import duckdb import pyarrow as pa import pytest from millpond.ducklake import ( _ensure_table, _escape_libpq, _sanitize_setting_value, _table_exists, _validate_partition_expr, build_insert_select_sql, drop_variant_companion_columns, variant_c...
PostHog/millpond
tests/unit/test_ducklake.py
.py
d83df2e738bfc7fc
7.98
8
"""DuckLake behavior + value-fidelity locks. Ported from the deleted cross-backend equivalence suite (see the `final-iceberg` tag) — these are the DuckLake-side contracts that remain load-bearing now that DuckLake is the only sink: reserved-column collisions raise at the Sink boundary, `_inserted_at` provenance, no de...
PostHog/millpond
tests/unit/test_ducklake_fidelity.py
.py
149f7b8db0f0ad7e
7.98
8
"""Tier C: SQL macros in tools/ducklake_maintenance.sql against a stub schema. In-process DuckDB with stub catalog tables and a real local-filesystem glob. Exercises path-normalization logic where the same physical file may be referenced as either an absolute URI or a bucket-relative key (per quirk r1 in the followup ...
PostHog/millpond
tests/unit/test_ducklake_maintenance_macros.py
.py
7c39c1a0548720e1
7.98
8
"""DuckLake extension version-pin canary. `millpond/ducklake.py` exercises specific DuckDB+DuckLake behaviour: the multi-pod CREATE/ALTER race patterns, `INSERT INTO ... BY NAME SELECT * FROM _arrow_batch`, `ALTER TABLE SET PARTITIONED BY`, `ADD COLUMN IF NOT EXISTS` idempotency, and the `ALTER COLUMN SET DATA TYPE` w...
PostHog/millpond
tests/unit/test_ducklake_pin.py
.py
8155cef9c530cb1b
7.98
8
"""Tests for the DuckLakeSink wrapper class. The class wrapper is thin — constructor wiring, three delegate methods. The module-level helper functions are exercised separately by `test_ducklake.py`. These tests cover the class behaviour that those don't touch: * `__init__` validates required cfg fields and construc...
PostHog/millpond
tests/unit/test_ducklake_sink.py
.py
5ad0bd1bf3ec79ef
7.98
8
"""Include-values source semantics. The safety contract under test (see include_values.py): - additions apply on first sight; removals need M consecutive successful ACCEPTED polls absent — failed polls AND refused polls advance nothing; - a poll failure keeps the last-known set; - refusal guards: empty result vs a n...
PostHog/millpond
tests/unit/test_include_values.py
.py
1377cb970ed092f8
7.98
8
#!/usr/bin/env python3 """ Auto-resuming 311 downloader. Counts rows already in file and picks up from there. Retries indefinitely with long waits when the API goes unresponsive. """ import os, csv, time, requests, subprocess from datetime import datetime APP_TOKEN = os.environ["SOCRATA_APP_TOKEN"] DATASET_ID = "erm...
ccedacero/nyc-property-intel
resume_311.py
.py
ae30d681e9958f40
7.45
7
#!/usr/bin/env python3 """Per-dataset coverage audit: local DB vs Socrata source-of-truth. Run against Railway prod DB: RAILWAY_DB=postgresql://... uv run python scripts/coverage_audit.py Outputs JSON-lines on stdout (one row per dataset) and a Markdown summary to docs/data-coverage-audit-{YYYY-MM-DD}.md. """ fro...
ccedacero/nyc-property-intel
scripts/coverage_audit.py
.py
bdccbf35e55e7d01
7.45
7
#!/usr/bin/env python3 """Run all enabled sync_delta.py datasets in sequence and alert on failure. Designed for Railway Cron — single entry point that handles a whole tier. Usage: DATABASE_URL=... SOCRATA_APP_TOKEN=... RESEND_API_KEY=... \ uv run python scripts/sync_all.py [--tier 1] [--only hpd_violat...
ccedacero/nyc-property-intel
scripts/sync_all.py
.py
45f9a8b7b4cc9fd2
7.45
7
#!/usr/bin/env python3 """Regenerate site/sitemap.xml with <lastmod> derived from git history. The sitemap was hand-maintained and drifted weeks behind actual page edits (the flagship pillar advertised a lastmod ~8 weeks stale), which reads as dormancy to crawlers. Run this before deploying the site: python3 scri...
ccedacero/nyc-property-intel
scripts/update_sitemap.py
.py
4bd71dc8e5b048d1
7.45
7
"""PostHog product analytics — fire-and-forget server-side event capture. Usage: from nyc_property_intel.analytics import capture capture("token_hash_abc123", "tool_called", {"tool_name": "lookup_property"}) No-ops silently when POSTHOG_API_KEY is not set, so local dev requires no config. """ from __future__...
ccedacero/nyc-property-intel
src/nyc_property_intel/analytics.py
.py
fbe8ed0ccf4ee600
7.45
7
import asyncio import logging import time from collections import deque import httpx from nyc_property_intel.config import settings logger = logging.getLogger(__name__) SOCRATA_BASE = "https://data.cityofnewyork.us/resource" _MAX_RETRIES = 3 _RETRY_DELAYS = (1.0, 2.0, 4.0) # seconds between attempts class Socra...
ccedacero/nyc-property-intel
src/nyc_property_intel/socrata.py
.py
832228a915677911
7.45
7
#!/usr/bin/env python3 """Reconstruct snapshot fidelity for an already-collected corpus. No inference. The corpus preserves both the bounded snapshot the verifiers saw and the EvidenceStore it was drawn from, so fidelity is recoverable after the fact by comparing them. That is the whole point of having persisted both....
guelfoweb/orbit
scripts/evaluation/backfill_snapshot_fidelity.py
.py
f6c67eb6d66f2b81
7.59
14
#!/usr/bin/env python3 """Deterministic offline scorer for the completion-shadow corpus. Evaluation only. Reads a preserved corpus read-only, scores each persisted checkpoint against an evaluator-only oracle, and reports what the two verifiers got right and wrong. It performs no inference: there is no backend, no clie...
guelfoweb/orbit
scripts/evaluation/score_completion_shadow.py
.py
2db9bd0a9488661e
7.59
14
from __future__ import annotations from dataclasses import dataclass from typing import Any, Callable, Protocol Message = dict[str, Any] @dataclass(frozen=True) class StreamPromptMetrics: """What prefill measured, known before any token is generated.""" prompt_tokens: int | None = None evaluated_token...
guelfoweb/orbit
src/orbit/backend/base.py
.py
2a3e4b261633a390
7.59
14
"""What one exact GGUF is qualified to do, as distinct from what its profile supports. Discovery answers "which model is this?" from GGUF metadata, cheaply. This module answers a different question -- "is *these bytes* qualified for X?" -- and it has to, because two builds of the same model share every metadata field ...
guelfoweb/orbit
src/orbit/native_llama/artifact_capabilities.py
.py
3e441365db63b53a
7.59
14
from __future__ import annotations from pathlib import Path import os import subprocess from .native_names import platform_runtime_libs PACKAGE_NATIVE_ROOT = Path(__file__).resolve().parent / "vendor" BUNDLED_SOURCE_ROOT = PACKAGE_NATIVE_ROOT / "source" / "llama.cpp" # What a built artifact records as the place to...
guelfoweb/orbit
src/orbit/native_llama/build_support.py
.py
9c619e5cc2b72faa
7.59
14
"""action.yml must expose, and wire, exactly the contract the provider table describes. The resolver only ever sees what action.yml hands it. A provider in the table with no input declared is unreachable; an input declared but not wired reads as empty and is refused as "you did not set your key" when the user did. Bot...
CodeBoarding/CodeBoarding-action
tests/test_action_inputs.py
.py
7285d4c14c9fffa4
8.04
11
"""Tests for the stored-analysis reuse boundary owned by the action.""" from __future__ import annotations import json import os import subprocess import tempfile import unittest from pathlib import Path ROOT = Path(__file__).resolve().parent.parent STATE_NAMES = ROOT / "scripts" / "action" / "state-names.sh" ANALY...
CodeBoarding/CodeBoarding-action
tests/test_action_state.py
.py
d9d141e9672a9314
7.04
11
"""The action's provider table must match the CodeBoarding release action.yml pins. The table exists because credentials have to be validated before the engine is installed, which rules out asking the engine at run time. That copy is only safe while something fails when it stops matching -- otherwise bumping the pin s...
CodeBoarding/CodeBoarding-action
tests/test_provider_table_drift.py
.py
a0266e1e7156b661
8.04
11
""" Car Price Prediction API A FastAPI-based REST API that predicts car prices using a Gradient Boosting machine learning model. The API accepts a car brand and returns a predicted price along with the closest matching user listing. """ from fastapi import FastAPI, HTTPException from pydantic import BaseModel, validat...
3bsalam-1/Car-Info
src/main.py
.py
9edb2f89ce90324b
7.42
6
from pathlib import Path import pandas as pd import sqlite3 import os import unicodedata # Note: import 'json' supprimé (inutilisé) class PharmaDataPipeline: def __init__(self, db_name="data/bdpm.db", data_dir="data"): self.db_name = db_name self.data_dir = data_dir Path(self.db_name).pa...
matthieugraziani/bdpm-database
database.py
.py
c198f39f1ebf7444
7.45
7
import pytest import sqlite3 import pandas as pd import tempfile import os from database import PharmaDataPipeline class TestPharmaDataPipeline: """Test suite for PharmaDataPipeline class""" @pytest.fixture def temp_db(self): """Create a temporary database for testing""" with tempfile...
matthieugraziani/bdpm-database
tests/test_database.py
.py
580e85d94182d636
7.95
7
#!/usr/bin/env python3 """Locate installed Claude Code and Codex CLI binaries. Cross-client verification must run from either client's shell, from cron, or from CI. Each client's own shell puts its binary on PATH, but the other client's shell usually does not — the Codex CLI ships inside the ChatGPT desktop app on mac...
synthesisengineering/synthesis-skills
skills/synthesis-agent-conformance/scripts/client_binaries.py
.py
2270da3ec9c45fee
7.63
17
#!/usr/bin/env python3 """Shared parsing helpers for synthesis project context.""" from __future__ import annotations import re import subprocess from pathlib import Path CHECKLIST = re.compile(r"^(?:[-*]|\d+\.)\s+\[([ xX])\]\s+") def _git(project: Path, *arguments: str) -> subprocess.CompletedProcess[str]: r...
synthesisengineering/synthesis-skills
skills/synthesis-agent-conformance/scripts/project_context.py
.py
5890a1bc688d385e
7.63
17
#!/usr/bin/env python3 """Semantic currency of durable-context headers, checked per field. A `CONTEXT.md` header is a cache over the session log: `**Last session:**` points at the newest logged session and `**Phase:**` describes the state it left. The log is append-only truth. A header field that describes an older st...
synthesisengineering/synthesis-skills
skills/synthesis-context-lifecycle/scripts/context_currency.py
.py
9c31c07439ad3d01
7.63
17
#!/usr/bin/env python3 """Body-currency regressions — fixtures from the three real occurrences. Acceptance rule set by the third occurrence's escalation: a fixture set that does not flag the state found at current HEAD is not a fix. Occurrence 3 is therefore encoded verbatim from the live record (repo `d918071d`), in ...
synthesisengineering/synthesis-skills
skills/synthesis-context-lifecycle/scripts/test_body_currency.py
.py
aa150ce997a30356
8.13
17
#!/usr/bin/env python3 """Tests for fail-closed durable-context edits.""" from __future__ import annotations from pathlib import Path import pytest from context_edit import ( ContextEditError, apply_replacement, insert_before, main, replace_once, set_field, ) RECORD = """# Project — Context...
synthesisengineering/synthesis-skills
skills/synthesis-context-lifecycle/scripts/test_context_edit.py
.py
76ddf7f30d974ac9
7.13
17
#!/usr/bin/env python """ Downloads Drupal SA advisories using the REST API. By default, only advisories that have been modified since the most recent changed time out of all the existing SA advisories """ import json import os import time import typing import requests from typings import drupal from user_agent im...
DrupalSecurityTeam/drupal-advisory-database
scripts/download_sa_advisories.py
.py
894fc19c5b3c0a24
7.42
6