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 |
|---|---|---|---|---|---|---|
"""add weekly user spend escalation threshold
Revision ID: slack_user_spend_threshold_001
Revises: user_alert_task_finished_001
Create Date: 2026-07-27
"""
from typing import Sequence, Union
from alembic import op
revision: str = "slack_user_spend_threshold_001"
down_revision: Union[str, Sequence[str], None] = "use... | abundant-ai/oddish | backend/alembic/versions/slack_user_spend_threshold_001.py | .py | ba78f1c0fbbe33ae | 7.65 | 19 |
"""drop users.run_probe_default
Revision ID: t6u7v8w9x0y1
Revises: s5t6u7v8w9x0
Create Date: 2026-07-01 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
revision: str = "t6u7v8w9x0y1"
down_revision: Union[str, Sequence[str], None] = "s5t6u7v8w9x0"
branch_labels: Union[str, Sequence[str... | abundant-ai/oddish | backend/alembic/versions/t6u7v8w9x0y1_drop_user_run_probe_default.py | .py | 164a22ef915c7569 | 7.65 | 19 |
"""add tasks.api_key_id
Revision ID: taskapikey_be_001
Revises: u7v8w9x0y1z2
Create Date: 2026-07-06 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
revision: str = "taskapikey_be_001"
down_revision: Union[str, Sequence[str], None] = "u7v8w9x0y1z2"
branch_labels: Union[str, Sequence[s... | abundant-ai/oddish | backend/alembic/versions/taskapikey_be_001_add_task_api_key_id.py | .py | 7d81609328e2d021 | 7.65 | 19 |
"""add user_provider_keys
Per-user BYOK provider API keys: AES-GCM ciphertext only, one live row per
(user, vendor). Plain-text status/vendor + CHECK constraints (not PG enums)
so the migration downgrades cleanly.
Revision ID: u7v8w9x0y1z2
Revises: apk_role_backend_001
Create Date: 2026-07-04 00:00:00.000000
"""
fro... | abundant-ai/oddish | backend/alembic/versions/u7v8w9x0y1z2_add_user_provider_keys.py | .py | 16edcabcb20eacb5 | 7.65 | 19 |
#!/usr/bin/env python3
"""Ceremony Step Gate Hook.
PreToolUse hook on Bash that blocks ``gz closeout --ceremony --next``
from being called twice in the same agent turn. Uses a two-file
protocol: the CLI writes a turn-lock with ``presented_step``, and
this hook maintains a ``last_allowed_step`` counter. When both mat... | tvproductions/gzkit | .claude/hooks/ceremony-step-gate.py | .py | 4d579f489ab29d86 | 7.5 | 9 |
#!/usr/bin/env python3
"""gzkit ledger writer and validator hook for claude.
This hook records governance artifact edits and enforces completion gates.
COVERAGE LIMIT (GHI #847): this hook binds Edit|Write and keys on
tool_input.file_path, a field a Bash payload does not carry. A governance
artifact written by sed, a... | tvproductions/gzkit | .claude/hooks/ledger-writer.py | .py | 393f7cff93f7facd | 7.5 | 9 |
#!/usr/bin/env python3
"""MX Awareness Hook (ADR-0.0.74, OBPI-0.0.74-07).
UserPromptSubmit hook — injects the MX banner to stdout on every agent turn
while the MX marker is present. Stdout content is injected as agent context
by the Claude Code harness on each turn.
Per-turn guarantee (not agent memory): an agent dri... | tvproductions/gzkit | .claude/hooks/mx-awareness.py | .py | fd1bfaeaf82a2765 | 7.5 | 9 |
#!/usr/bin/env python3
"""OBPI Completion Validator Hook.
PreToolUse hook that gates OBPI brief completion by checking ledger evidence
before allowing status changes to 'Completed'.
Aligned with airlineops canonical obpi-completion-validator.py.
Uses ADR-local audit ledger ({adr-dir}/logs/obpi-audit.jsonl) as evidenc... | tvproductions/gzkit | .claude/hooks/obpi-completion-validator.py | .py | ec8687bc9ef53d67 | 7.5 | 9 |
#!/usr/bin/env python3
"""Pipeline Completion Reminder Hook.
PreToolUse hook on Bash that emits a non-blocking reminder before
`git commit` or `git push` when an OBPI pipeline is still active
and the corresponding brief has not been completed.
Exit codes:
0 - Always (advisory only)
"""
import json
import os
import... | tvproductions/gzkit | .claude/hooks/pipeline-completion-reminder.py | .py | 16edbe2cfac837d6 | 7.5 | 9 |
#!/usr/bin/env python3
"""Pipeline Gate Hook.
PreToolUse hook on Write|Edit that blocks implementation file writes
under `src/` and `tests/` for a governed OBPI whose pipeline is not
active. The OBPI is identified by either a passing plan-audit
receipt (plan-mode path) or an OBPI lock held by the current agent
(GHI #6... | tvproductions/gzkit | .claude/hooks/pipeline-gate.py | .py | 71b77edb88171bb1 | 7.5 | 9 |
#!/usr/bin/env python3
"""Pipeline Router Hook.
PostToolUse hook on ExitPlanMode that routes the agent to
`uv run gz obpi pipeline` after plan approval for OBPI work.
How it works:
1. Reads `.claude/plans/.plan-audit-receipt.json`
2. If the receipt exists, names an OBPI, and has verdict `PASS`,
emit a routin... | tvproductions/gzkit | .claude/hooks/pipeline-router.py | .py | 18039402b820d8a3 | 7.5 | 9 |
#!/usr/bin/env python3
"""Plan Audit Gate Hook.
PreToolUse hook on ExitPlanMode that enforces the gz-plan-audit pre-flight
alignment check. If the most recent plan referencing an OBPI exists in
either ``<project>/.claude/plans/`` or ``~/.claude/plans/`` (Claude Code's
plan mode writes new plans to the global directory... | tvproductions/gzkit | .claude/hooks/plan-audit-gate.py | .py | b6b1e372394b3a1f | 7.5 | 9 |
#!/usr/bin/env python3
"""Session-Exit Bookmark Hook (GHI #756).
SessionEnd hook. Writes a CHECKPOINT handoff recording where the
session stopped, so continuity does not depend on an agent
remembering to author one — the trigger ADR-0.0.65 never specified.
Books, never refuses (operator ruling: "DO NOT BLOCK HERE ...... | tvproductions/gzkit | .claude/hooks/session-exit-bookmark.py | .py | 603a9f5e2ddf124c | 7.5 | 9 |
#!/usr/bin/env python3
"""Session Staleness Check Hook (gzkit adaptation).
PreToolUse hook on Write|Edit that detects stale pipeline artifacts
left from previous sessions and emits warnings so the agent can
clean up before hitting gate blocks.
Adapted from airlineops canonical session-staleness-check.py.
Uses gzkit's... | tvproductions/gzkit | .claude/hooks/session-staleness-check.py | .py | 6d5e6f5201d57832 | 7.5 | 9 |
#!/usr/bin/env python3
"""gzkit ledger writer and validator hook for copilot.
This hook records governance artifact edits and enforces completion gates.
COVERAGE LIMIT (GHI #847): this hook binds Edit|Write and keys on
tool_input.file_path, a field a Bash payload does not carry. A governance
artifact written by sed, ... | tvproductions/gzkit | .github/copilot/hooks/ledger-writer.py | .py | 8a82996da117ac9e | 7.5 | 9 |
#!/usr/bin/env python
"""Measure declared-but-never-fired ledger vocabulary, and report paired-event ratios.
The sibling chore `control-surface-validator-reachability` asks whether a
*validator* runs. This one asks the same question of the *ledger*: an event type
declared in ``src/gzkit/schemas/ledger.json`` that noth... | tvproductions/gzkit | .gzkit/chores/ledger-vocabulary-inertness/check_ledger_inertness.py | .py | 9e6e7b459568d28d | 7.5 | 9 |
"""Witness that the auto-memory surface has not drifted since the last hygiene pass.
The acceptance criterion this backs must be able to FAIL for the reason the chore
exists (GHI #743): a criterion that cannot fail when the chore's subject changes is
green by construction. `test -f MEMORY.md` witnessed that an index w... | tvproductions/gzkit | .gzkit/chores/memory-hygiene/check_memory_drift.py | .py | ea7c37fe25d2a433 | 7.5 | 9 |
#!/usr/bin/env python3
"""Module-size gate for the ``module-sloc-cap-radon`` chore.
Reads the ``radon_raw_nloc`` ``block`` band from the ONE canonical threshold
table (``.gzkit/rules/complexity-thresholds.json``) and enforces it over
``src/``. The chore previously declared its own ``<=1000 SLOC`` hard cap and
``<=600`... | tvproductions/gzkit | .gzkit/chores/module-sloc-cap-radon/check_module_size.py | .py | c331a4c8ac8acdac | 7.5 | 9 |
#!/usr/bin/env python3
"""Run the dependency-free function tests when pytest is unavailable."""
from __future__ import annotations
import runpy
from pathlib import Path
def main() -> None:
root = Path(__file__).resolve().parents[1]
tests = []
for path in sorted((root / "tests").glob("test_*.py")):
... | amap-cvlab/UniMapGen | scripts/run_tests.py | .py | d2ad62b0174b19a4 | 7.16 | 20 |
#!/usr/bin/env python3
"""LayoutLens Benchmark Evaluator.
Scores LayoutLens answers against ground-truth answer keys using a
**deterministic** structured yes/no comparison:
- The answer key's ``expected`` is always ``"yes"`` or ``"no"``.
- The model answer's leading yes/no token is parsed with the same
word-boundar... | gojiplus/layoutlens | benchmarks/evaluation/evaluator.py | .py | 3182a78307f213c6 | 7.62 | 16 |
#!/usr/bin/env python3
"""Generate axe-core ground truth for the accessibility benchmark fixtures.
Runs the deterministic :class:`~layoutlens.a11y.AxeAuditor` (WCAG 2.0 A + AA)
over each accessibility fixture, prints a reconciliation report comparing what
axe actually finds against the claims baked into
``benchmarks/a... | gojiplus/layoutlens | benchmarks/generators/generate_a11y_ground_truth.py | .py | a3de163fa9bbfceb | 7.62 | 16 |
#!/usr/bin/env python3
"""
LayoutLens Benchmark Runner
Runs LayoutLens API against benchmark test data and generates results for evaluation.
This script demonstrates the async API and proper JSON output handling.
Usage:
python benchmarks/run_benchmark.py --api-key YOUR_KEY
python benchmarks/run_benchmark.py -... | gojiplus/layoutlens | benchmarks/run_benchmark.py | .py | 09b6f015a18280e0 | 7.62 | 16 |
"""Keyless deterministic layout checks: LayoutScorer and check_layout.
Everything here runs with NO API key and NO LLM — the browser's own layout
engine does the measuring, so results are exact and reproducible.
"""
import asyncio
from layoutlens import LayoutLens, LayoutScorer, contrast_ratio
from layoutlens.layout... | gojiplus/layoutlens | examples/deterministic_layout.py | .py | 853dc6dd31f39a90 | 7.62 | 16 |
"""Deterministic accessibility auditing via a vendored axe-core bundle.
:class:`AxeAuditor` injects the bundled axe-core JavaScript into a Playwright
page, runs ``axe.run``, and maps the resulting JSON into typed
:class:`~layoutlens.a11y.types.A11yReport` objects. The axe-core assets are
vendored under ``layoutlens/a1... | gojiplus/layoutlens | src/layoutlens/a11y/axe.py | .py | 3451a402ffbba7bd | 7.62 | 16 |
"""Dataclasses for deterministic accessibility findings and reports.
These types model the structured output of the axe-core engine after it has
been mapped from raw JSON into typed Python objects. They are intentionally
engine-agnostic so future deterministic engines can reuse the same shapes.
"""
from __future__ im... | gojiplus/layoutlens | src/layoutlens/a11y/types.py | .py | d57c24a6479866e0 | 7.62 | 16 |
"""Faithful judge interface for LayoutLens.
This module turns LayoutLens into a faithful *instrument* for external
evaluation harnesses (UIJudgeBench first). Unlike :meth:`LayoutLens.analyze`,
which wraps queries in its own persona/JSON scaffolding, :func:`judge` sends the
caller-supplied prompt VERBATIM as the only t... | gojiplus/layoutlens | src/layoutlens/api/judge.py | .py | dcec3f9cfb9224ab | 7.62 | 16 |
"""Shared browser and page lifecycle for LayoutLens.
This module centralizes Playwright browser management so there is a single
place that owns launching chromium, serving local HTML files over a temporary
HTTP server, and yielding a fully loaded :class:`~playwright.async_api.Page`.
Both the screenshot capture path (... | gojiplus/layoutlens | src/layoutlens/browser.py | .py | 1b603b5900a0f72a | 7.62 | 16 |
"""Caching mechanism for LayoutLens to reduce API calls and improve performance."""
import copy
import hashlib
import json
import pickle # nosec B403 - Used only for internal caching, not user input
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from pathlib import Path
from ... | gojiplus/layoutlens | src/layoutlens/cache.py | .py | 4890366708134f86 | 7.62 | 16 |
"""Simplified URL capture system for live website screenshots.
Provides a single, clean interface that handles any number of URLs naturally.
"""
import asyncio
import hashlib
import time
from pathlib import Path
from urllib.parse import urlparse
from .browser import VIEWPORTS, open_browser, open_page
from .logger im... | gojiplus/layoutlens | src/layoutlens/capture.py | .py | 0462002f2a41d5e3 | 7.62 | 16 |
"""Custom exception classes for LayoutLens with comprehensive error handling.
This module provides a hierarchy of custom exceptions for different error scenarios
that can occur during LayoutLens operations, including API errors, screenshot failures,
configuration issues, and analysis problems.
"""
from .logger import... | gojiplus/layoutlens | src/layoutlens/exceptions.py | .py | f872789239ac81ec | 7.62 | 16 |
"""Type definitions for Browser Use integration.
Provides data classes for validation policies, results, and session recordings.
"""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
class ValidationTrigger(Enum):
"""When to tri... | gojiplus/layoutlens | src/layoutlens/integrations/browser_use/types.py | .py | 29e640c78cb6ae78 | 7.62 | 16 |
"""Post-run validation for browser-use agent sessions.
Integrates at browser-use's most *stable* seam: the ``AgentHistoryList`` that
``Agent.run()`` returns (its ``urls()``/``screenshot_paths()`` accessors have
been stable across minor versions), rather than the per-step hook API, whose
signature has changed repeatedl... | gojiplus/layoutlens | src/layoutlens/integrations/browser_use/validator.py | .py | ccbf9d246d922649 | 7.62 | 16 |
"""WCAG relative-luminance / contrast-ratio math and a page-wide contrast scan.
The arithmetic (:func:`relative_luminance`, :func:`contrast_ratio`,
:func:`parse_css_color`) is pure and browser-free, so it unit-tests against
published WCAG example pairs. :func:`check_contrast` walks a rendered page,
reads each text ele... | gojiplus/layoutlens | src/layoutlens/layout/contrast.py | .py | d658922be9ab81e6 | 7.62 | 16 |
"""Dataclasses for deterministic layout/geometry findings and reports.
These mirror the shapes in :mod:`layoutlens.a11y.types` (``A11yFinding`` /
``A11yReport``) but model visual defects measured directly off a rendered page —
overlap, clipping, viewport protrusion, undersized targets, low text contrast,
focus obscura... | gojiplus/layoutlens | src/layoutlens/layout/types.py | .py | 2740bf3f4222d646 | 7.62 | 16 |
"""Logging configuration and utilities for LayoutLens.
This module provides centralized logging configuration with support for
different environments, log levels, and output formats.
"""
import logging
import logging.handlers
import os
from pathlib import Path
# Default log format with structured information
DEFAULT... | gojiplus/layoutlens | src/layoutlens/logger.py | .py | 87300e696bfcf82a | 7.62 | 16 |
"""LayoutLens MCP server: deterministic UI checks as agent tools.
Run with ``layoutlens-mcp`` (or ``uvx --from "layoutlens[mcp]" layoutlens-mcp``)
and register it with any MCP client (Claude Code, Cursor, ...).
Design notes:
- ``audit_accessibility`` and ``scan_layout`` are **keyless and deterministic**
— they ret... | gojiplus/layoutlens | src/layoutlens/mcp_server.py | .py | 983c35405e075cc1 | 7.62 | 16 |
"""Per-model completion-parameter policy for LiteLLM calls.
Different vision models accept different sampling parameters. In particular,
Anthropic's newest reasoning-tuned Claude models REJECT any non-default
sampling parameter (notably ``temperature``) with an HTTP 400 — they only
accept the provider default. Sending... | gojiplus/layoutlens | src/layoutlens/param_policy.py | .py | 6d2eebb0224edd83 | 7.62 | 16 |
"""Base prompt template system for LayoutLens expert analysis."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from .context import Instructions
@dataclass
class PromptTemplate:
"""A r... | gojiplus/layoutlens | src/layoutlens/prompts/base.py | .py | 17363630a564b61c | 7.62 | 16 |
"""Expert persona registry for LayoutLens."""
from __future__ import annotations
from typing import TYPE_CHECKING
from .experts import (
AccessibilityExpert,
ConversionExpert,
EcommerceExpert,
FinanceExpert,
HealthcareExpert,
MobileExpert,
)
if TYPE_CHECKING:
from .base import ExpertProm... | gojiplus/layoutlens | src/layoutlens/prompts/utils.py | .py | 61f2adb1b5f315f4 | 7.62 | 16 |
"""Type definitions for LayoutLens JSON schemas and API interfaces.
This module provides TypedDict definitions for all JSON inputs and outputs,
plus enums for type-safe parameter validation.
"""
from enum import Enum
from typing import Any, TypedDict
# Enums for type-safe API parameters
class ComplianceLevel(Enum)... | gojiplus/layoutlens | src/layoutlens/types.py | .py | 2f975fb5dfd0b7b7 | 7.62 | 16 |
from __future__ import annotations
"""Resolve a ChromeDriver compatible with the locally installed Chrome."""
import logging
import os
import sys
from pathlib import Path
try:
from webdriver_manager.chrome import ChromeDriverManager
except ImportError: # Frozen/source startup reports this through the normal bro... | gavinedwardbrooks-zjc/KOLConnect | app/chromedriver_resolver.py | .py | 7ea797182db4e777 | 7.57 | 13 |
from __future__ import annotations
"""Read-only dashboard data access built on top of local repositories."""
from typing import Any
from campaign_creator_repository import CampaignCreatorRepository
from campaign_repository import CampaignRepository
from creator_repository import CreatorRepository
class DashboardRe... | gavinedwardbrooks-zjc/KOLConnect | app/dashboard_repository.py | .py | 7a44051c57a72615 | 7.57 | 13 |
from __future__ import annotations
"""Strict extraction of Feishu Bitable relation record IDs."""
from typing import Any
def relation_record_ids(value: Any) -> list[str]:
"""Return explicit record IDs only, preserving first-seen order."""
result: list[str] = []
def add(candidate: Any) -> None:
... | gavinedwardbrooks-zjc/KOLConnect | app/feishu_relation.py | .py | ac6f17a71cc2fae5 | 7.57 | 13 |
"""Settings, health, account, and mail HTTP endpoints."""
from services.workbook_backup_service import (
WorkbookBackupError,
WorkbookBackupNotFoundError,
)
def _merge_mail_configuration_update(payload: dict, existing_mail: dict | None, services: dict) -> dict:
"""Apply only explicitly supplied mail fiel... | gavinedwardbrooks-zjc/KOLConnect | app/http_handlers/settings_handler.py | .py | cd648f59ed2f5e2f | 7.57 | 13 |
"""Logger construction helpers shared by all samplers."""
import logging
import sys
def setup_logger(
name: str, level: int = logging.INFO, log_file: str | None = None
) -> logging.Logger:
"""Set up a standardized logger for RepoRoulette components.
Args:
name: Logger name (typically module name... | gojiplus/reporoulette | src/reporoulette/logging_config.py | .py | 058230c92356f5ba | 7.59 | 14 |
"""Abstract base class with the shared sampler plumbing (rate limits, filters)."""
import logging
import random
import time
from abc import ABC, abstractmethod
from datetime import UTC, datetime
from typing import Any, cast
import requests
# HTTP status code constants
HTTP_OK = 200
HTTP_FORBIDDEN = 403
HTTP_NOT_FOUN... | gojiplus/reporoulette | src/reporoulette/samplers/base.py | .py | ef33bb533c9e4eec | 7.59 | 14 |
"""Small helpers for running BigQuery queries and shaping their results."""
import logging
from datetime import datetime
from typing import Any
def execute_query(
client: Any, query: str, logger: logging.Logger
) -> list[dict[str, Any]]:
"""Execute a BigQuery query and return results as a list of dictionarie... | gojiplus/reporoulette | src/reporoulette/samplers/bq_utils.py | .py | b4fc2be286219093 | 7.59 | 14 |
"""Random sampling by probing GitHub's sequential repository ID space."""
import logging
import random
import time
from datetime import UTC, datetime, timedelta
from typing import Any
import requests
from ..logging_config import get_logger
from .base import HTTP_OK, BaseSampler
class IDSampler(BaseSampler):
""... | gojiplus/reporoulette | src/reporoulette/samplers/id_sampler.py | .py | ec8d12de7e37e7ee | 7.59 | 14 |
import logging
import unittest
from unittest.mock import MagicMock, patch
from reporoulette.samplers.id_sampler import IDSampler
from reporoulette.samplers.temporal_sampler import TemporalSampler
def rate_limited_get(core_remaining, search_remaining):
"""Mock requests.get routing /rate_limit and repo URLs."""
... | gojiplus/reporoulette | tests/test_base.py | .py | 7c531e8d8559dbb2 | 8.09 | 14 |
import base64
import logging
import os
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from reporoulette.samplers.bigquery_sampler import BigQuerySampler
def make_offline_sampler(seed=42):
"""Construct a BigQuerySampler without credentials or the google-cloud de... | gojiplus/reporoulette | tests/test_bq_sampler.py | .py | 762063609e48fc01 | 8.09 | 14 |
import logging
import unittest
from unittest.mock import MagicMock, patch
from reporoulette.samplers.id_sampler import IDSampler
class TestIDSampler(unittest.TestCase):
def setUp(self):
# Create a real instance
self.sampler = IDSampler(seed=42)
# Mock logger
self.sampler.logger =... | gojiplus/reporoulette | tests/test_id_sampler.py | .py | 94e38d0b48d3bd3d | 8.09 | 14 |
import re
import unittest
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock, patch
from reporoulette.samplers.temporal_sampler import TemporalSampler
def search_response(total_count, items):
response = MagicMock()
response.status_code = 200
response.json.return_value = {"t... | gojiplus/reporoulette | tests/test_temporal_sampler.py | .py | a04161ac05d6548f | 8.09 | 14 |
import logging
import os
import unittest
from collections import Counter
from datetime import UTC, datetime
from typing import Any
from unittest.mock import MagicMock, patch
from reporoulette.samplers.bigquery_sampler import BigQuerySampler
from reporoulette.samplers.gh_sampler import GHArchiveSampler
from reporoulett... | gojiplus/reporoulette | tests/test_validation.py | .py | 62b0fc8b77f664b7 | 8.09 | 14 |
"""
Example 16: Roulette Wheel Simulation
Demonstrates realistic casino roulette physics including:
- Spinning wheel with rotational motion
- Ball launched with initial velocity
- Ball bounces off deflectors (diamond-shaped obstacles)
- Friction and damping slow the ball
- Ball settles into a numbered pocket
This sho... | IBM/chuk-mcp-physics | examples/16_roulette_simulation.py | .py | 1588b0b97001f54e | 7.52 | 10 |
#!/usr/bin/env python3
"""Viscosity and Reynolds Number Demo.
This example demonstrates the viscosity parameter for accurate Reynolds number
calculations across different fluids. The Reynolds number determines flow regime:
- Re < 2,300: Laminar flow (smooth, predictable)
- 2,300 < Re < 4,000: Transitional flow... | IBM/chuk-mcp-physics | examples/17_viscosity_and_reynolds_number.py | .py | 578c0ab6901325b7 | 7.52 | 10 |
"""Advanced Projectile Motion Examples: Magnus Force, Wind, and Altitude.
This example demonstrates the enhanced features of calculate_projectile_with_drag:
- Spin effects (Magnus force) for curveballs, slices, hooks
- Wind effects (tailwind, headwind, crosswind)
- Altitude and temperature effects on air density
All ... | IBM/chuk-mcp-physics | examples/advanced_projectile_effects.py | .py | 8515cd90f2cc0253 | 7.52 | 10 |
"""Physics analysis utilities for trajectories and events."""
import math
from typing import Optional
from .models import BounceEvent, ContactEvent, TrajectoryFrame, TrajectoryWithEventsResponse
def detect_bounces(
frames: list[TrajectoryFrame],
height_threshold: float = 0.01,
velocity_threshold: float ... | IBM/chuk-mcp-physics | src/chuk_mcp_physics/analysis.py | .py | 15185b75a84c4ddb | 7.52 | 10 |
"""Configuration for chuk-mcp-physics server.
This module handles configuration loading from YAML files and environment variables.
Configuration sources (in order of precedence):
1. Environment variables
2. YAML configuration file (physics.yaml)
3. Default values
"""
import logging
import os
from enum import Enum
fro... | IBM/chuk-mcp-physics | src/chuk_mcp_physics/config.py | .py | c01ead42eb3814a2 | 7.52 | 10 |
"""Fluid dynamics calculations for drag, buoyancy, and underwater motion.
This module provides analytical calculations for fluid dynamics effects including:
- Drag force (quadratic air/water resistance)
- Buoyancy force (Archimedes principle)
- Terminal velocity
- Underwater projectile motion with drag and buoyancy
T... | IBM/chuk-mcp-physics | src/chuk_mcp_physics/fluid.py | .py | d1ccc5cf2611e221 | 7.52 | 10 |
"""Provider factory for creating physics providers.
This module provides a factory pattern for instantiating providers
based on configuration.
"""
import logging
from enum import Enum
from ..config import ProviderConfig
from .base import PhysicsProvider
logger = logging.getLogger(__name__)
class ProviderType(str,... | IBM/chuk-mcp-physics | src/chuk_mcp_physics/providers/factory.py | .py | 6dea7563f270c0c6 | 7.52 | 10 |
"""Session bucket conventions and crash-robust state for aw-watcher-agent.
A session is modelled as a single event in the ``app.agent.session`` bucket.
``emit-start`` posts a zero-duration start event and records its server id; on
``emit-end`` we delete that placeholder and post one clean event carrying the
full durat... | gptme/gptme-contrib | packages/aw-watcher-agent/src/aw_watcher_agent/core.py | .py | 9c8dec69647f8e16 | 7.6 | 15 |
"""Canonical coerce_int helper.
Replaces 5 per-script ``_coerce_int`` definitions whose core logic was
identical (None/bool → default, int → int, float → int(round), str → int)
but varied in whether failure returns 0 or None.
Callers that intentionally convert bool to int (e.g. True→1) keep a local
function — see val... | gptme/gptme-contrib | packages/bobutils/src/bobutils/coerce.py | .py | 9d6d289cecf90969 | 7.6 | 15 |
"""Canonical JSONL loading.
Replaces ~20 per-file ``load_jsonl``/``_iter_jsonl`` implementations whose
behavior had drifted across four axes: missing-file handling, corrupt-line
handling, non-dict-row filtering, and encoding. The canonical semantics match
the de-facto majority pattern, with explicit opt-ins for the st... | gptme/gptme-contrib | packages/bobutils/src/bobutils/jsonl.py | .py | 24de9c4b850c939a | 7.6 | 15 |
"""Tests for bobutils.datetimes.parse_datetime."""
from __future__ import annotations
from datetime import datetime, timezone
from bobutils.datetimes import parse_datetime
UTC = timezone.utc # datetime.UTC added in Python 3.11; alias for >=3.10 compat
# --- None / invalid input ---
def test_none_returns_none():... | gptme/gptme-contrib | packages/bobutils/tests/test_datetimes.py | .py | 1cb3f706bd4864d1 | 7.1 | 15 |
"""Tests for bobutils.roots."""
from __future__ import annotations
import subprocess
from pathlib import Path
from typing import Any
import pytest
from bobutils.roots import find_repo_root
def test_find_repo_root_returns_path_with_git(tmp_path: Path) -> None:
subprocess.run(["git", "init"], cwd=tmp_path, check... | gptme/gptme-contrib | packages/bobutils/tests/test_roots.py | .py | 480eb851a48722ff | 7.1 | 15 |
#!/usr/bin/env python3
"""Script to identify and clean up duplicate email files.
This script finds duplicate sent emails that were created before the
duplicate detection fix was implemented. It identifies pairs of files
where one has the agent's UUID Message-ID and another has Gmail's Message-ID,
but they represent th... | gptme/gptme-contrib | packages/gptmail/scripts/cleanup_duplicates.py | .py | 8dc3ba901ae54fac | 7.6 | 15 |
"""
OAuth callback server for local OAuth flows.
Provides a lightweight Flask server to handle OAuth callbacks
during authorization flows. Supports configurable ports and paths.
"""
import html
import threading
from queue import Empty, Queue
from flask import Flask, request
from werkzeug.serving import BaseWSGIServe... | gptme/gptme-contrib | packages/gptmail/src/gptmail/communication_utils/auth/callback_server.py | .py | 19a4fafdd2b630bb | 7.6 | 15 |
"""Cross-process locking for OAuth2 token refresh.
Twitter uses rotating single-use refresh tokens (RFC 6749 §6). If two
processes call the Twitter token endpoint with the same refresh token,
Twitter accepts only the first request and the second fails with 400,
leaving the account deauthenticated.
Serialising the cr... | gptme/gptme-contrib | packages/gptmail/src/gptmail/communication_utils/auth/refresh.py | .py | 98f3426f8c2611e3 | 7.6 | 15 |
"""Token storage utilities for managing authentication tokens in .env files."""
import shutil
import tempfile
from pathlib import Path
from typing import List
def _read_env_lines(env_path: Path) -> List[str]:
"""Read lines from .env file."""
try:
with open(env_path) as f:
return f.readlin... | gptme/gptme-contrib | packages/gptmail/src/gptmail/communication_utils/auth/token_storage.py | .py | 79098d33b1643b6b | 7.6 | 15 |
"""
Retry logic with exponential backoff.
Provides decorators and utilities for retrying failed operations
with configurable backoff strategies and error handling.
"""
import functools
import time
from dataclasses import dataclass
from typing import Callable
class RetryError(Exception):
"""Raised when all retry... | gptme/gptme-contrib | packages/gptmail/src/gptmail/communication_utils/error_handling/retry.py | .py | a123e4e2f3b43cfe | 7.6 | 15 |
"""Message header parsing and formatting utilities."""
import uuid
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict, List
@dataclass
class MessageHeaders:
"""Cross-platform message headers.
Provides unified interface for message metadata across platforms.
"""
... | gptme/gptme-contrib | packages/gptmail/src/gptmail/communication_utils/messaging/headers.py | .py | 750750515c17ccc3 | 7.6 | 15 |
"""
Logging configuration for cross-platform communication.
Provides consistent logging setup with platform-specific loggers,
structured logging support, and configurable output formats.
"""
import logging
import sys
from pathlib import Path
class PlatformLogger:
"""
Platform-specific logger with consistent... | gptme/gptme-contrib | packages/gptmail/src/gptmail/communication_utils/monitoring/loggers.py | .py | ec07ddd5db2f75dd | 7.6 | 15 |
"""
Benchmarks from Salsa.
- "Intra-procedural Optimization of the Numerical Accuracy of Programs" (FMICS '15)
"""
import fpy2 as fp
@fp.fpy(meta={'cite': ['salsa-fmics15']})
def odometry(sl: fp.Real, sr: fp.Real):
"""
Compute the position of a robot from the speed of the wheels.
Inputs: Speed `sl`, `sr`... | bksaiki/fpy | examples/misc/salsa.py | .py | 841725ff6c651c34 | 7.48 | 8 |
"""
Shared helpers for the MMA-Sim models (`nv.py`, `amd.py`).
"""
import fpy2 as fp
# input conversion applied by TF32 (NVIDIA) and XF32 (AMD CDNA3)
# instructions to their FP32 operands
RZ_TF32 = fp.IEEEContext(8, 19, fp.RM.RTZ)
@fp.fpy(ctx=fp.REAL)
def join(xs, ys):
"""
Concatenates two lists.
FPy ha... | bksaiki/fpy | examples/mmasim/utils.py | .py | f9e276804d769442 | 7.48 | 8 |
import fpy2 as fp
@fp.fpy(ctx=fp.REAL)
def dot_prod(xs: list[fp.Real], ys: list[fp.Real], c: fp.Real) -> fp.Real:
with fp.REAL:
return sum([x * y for x, y in zip(xs, ys)]) + c
@fp.fpy(ctx=fp.REAL)
def dot_prod_mixed(xs: list[fp.Real], ys: list[fp.Real], c: fp.Real) -> fp.Real:
QUANT_CTX = fp.MX_E5M2
... | bksaiki/fpy | examples/mpfx.py | .py | 3134232379fe0eb1 | 7.48 | 8 |
"""
fused-dp/sweep.py: Performs parameter sweep of FPy model.
This model is based on "Optimized Fused Floating-Point Many-Term Dot-Product
Hardware for Machine Learning Accelerators" (Kaul et al., 2019).
"""
import fpy2 as fp
import matplotlib.pyplot as plt
import math
import random
from argparse import ArgumentPars... | bksaiki/fpy | exploration/fused_dp/sweep.py | .py | 4d1e1a3a2c7a9d80 | 7.48 | 8 |
"""
sweep.py: Performs a parameter sweep of stochastic rounding bias.
The model stochasicically rounds values sampled from U(0, 1) to either 0 or 1
where the probability of rounding `x` up to 1 is `x`.
"""
import argparse
import fpy2 as fp
import matplotlib.pyplot as plt
import numpy as np
import random
from concurr... | bksaiki/fpy | exploration/stochastic_bias/sweep.py | .py | 77f155da096723e1 | 7.48 | 8 |
"""Emit C++ for every corpus function, for before/after comparison.
The cheapest check that a change to the lowering pipeline is behaviour-preserving
is that the emitted code does not move:
python -m exploration.storage_infer.emit_corpus /tmp/base
... change something ...
python -m exploration.storage_inf... | bksaiki/fpy | exploration/storage_infer/emit_corpus.py | .py | 054d72b4e20f3a74 | 7.48 | 8 |
"""
Call graph analysis.
Builds the call graph of a :class:`~fpy2.ast.FuncDef` and everything it
transitively calls. The graph is keyed on ``FuncDef`` objects (by
identity); each edge ``caller -> callee`` corresponds to a :class:`Call`
targeting a user-defined :class:`~fpy2.function.Function`. A call's
target is its... | bksaiki/fpy | fpy2/analysis/call_graph.py | .py | 10daccbb1e077e43 | 7.48 | 8 |
"""Definition-use analysis for FPy ASTs"""
from typing import TypeAlias
from ..ast.fpyast import *
from ..ast.visitor import DefaultVisitor
from ..utils import default_repr
from .reaching_defs import (
AssignDef,
DefCtx,
Definition,
DefSite,
PhiDef,
PhiSite,
ReachingDefs,
ReachingDefsA... | bksaiki/fpy | fpy2/analysis/define_use.py | .py | bde0e5f7c9553724 | 7.48 | 8 |
"""
Definition analysis.
"""
from typing import TypeAlias
from ..ast.fpyast import *
from ..ast.visitor import DefaultVisitor
_Defs: TypeAlias = set[NamedId]
_DefMap: TypeAlias = dict[StmtBlock, _Defs]
__all__ = [
'DefAnalysis',
]
class _DefAnalysis(DefaultVisitor):
"""Visitor for definition analysis."""
... | bksaiki/fpy | fpy2/analysis/defs.py | .py | 85c6b1f8bf5907d3 | 7.48 | 8 |
"""
Escape summaries: which of a function's list parameters outlive the call.
A caller that hands a list to a callee has to assume the worst — the callee might
keep it — so :mod:`fpy2.analysis.alias` marks any call argument *shared outward*.
That is what makes a compiled-to-compiled boundary keep its handles, and it i... | bksaiki/fpy | fpy2/analysis/escape.py | .py | f878528c04f2bdad | 7.48 | 8 |
"""
Double-rounding soundness: when one rounding may be split into two.
Two families of rule, both mechanised in `mpfx-lean
<https://github.com/bksaiki/mpfx-lean>`_, which is the source of truth:
- :func:`double_round_ok` -- Figure 8 of *When Double Rounding is Correct*
(``Mpfx/DoubleRounding.lean``), which holds f... | bksaiki/fpy | fpy2/analysis/format_infer/double_round.py | .py | fd39ca8602d4366a | 7.48 | 8 |
"""
Partial evaluation.
For each expression and SSA definition, records the statically-known
:data:`Value` (if any) under the active rounding context. Consumed
by :class:`fpy2.transform.ConstFold` as the single source of truth
for "is this expression a known constant?"; also used by
:class:`fpy2.analysis.ArraySizeInf... | bksaiki/fpy | fpy2/analysis/partial_eval.py | .py | a3c51c8a064497ab | 7.48 | 8 |
"""
Pure function analysis.
"""
from ..ast import *
from ..function import Function
from ..number import Context
from ..primitive import Primitive
from .call_graph import CallGraph
from .define_use import AssignDef, DefineUse, DefineUseAnalysis
class _ImpureError(Exception):
"""
Exception raised when an impu... | bksaiki/fpy | fpy2/analysis/purity.py | .py | 53c515c33df60e7a | 7.48 | 8 |
"""
This module defines a reachability analysis.
"""
import dataclasses
from ..ast import *
@dataclasses.dataclass
class _ReachabilityCtx:
is_reachable: bool
@staticmethod
def default():
return _ReachabilityCtx(True)
class ReachabilityError(Exception):
"""Assertion error from a `Reachabil... | bksaiki/fpy | fpy2/analysis/reachability.py | .py | 6011895c1542e9bc | 7.48 | 8 |
"""
Storage inference: one storage format per runtime object.
Format inference bounds an expression by the smallest format its value can take;
storage inference picks, from a distinguished set the target can spell, one
format that *contains* that bound:
e : real fmt(e) = F F <= S
-------------------------... | bksaiki/fpy | fpy2/analysis/storage_infer.py | .py | 68209f61214568b6 | 7.48 | 8 |
"""Syntax checking for the FPy AST."""
from dataclasses import dataclass
from typing import Self
from ..ast.fpyast import *
from ..ast.visitor import Visitor
from .live_vars import LiveVars
class FPySyntaxError(Exception):
"""Syntax error for FPy programs."""
class _Env:
"""Bound variables in the current ... | bksaiki/fpy | fpy2/analysis/syntax_check.py | .py | 568d0fb7fdd35d47 | 7.48 | 8 |
import re
# Standard English stopwords — too common to be useful as FTS/keyword search terms.
# Including them inflates BM25 scores for ANY document containing normal prose,
# causing high-word-count events (pastes, OCR text, seed files) to rank above
# genuine matches.
STOPWORDS: frozenset[str] = frozenset({
"a",... | protocorn/clippy-vision | agent/helpers/keywords.py | .py | 2c2fc00964fc915d | 7.56 | 12 |
import json
import sys
import time
from pathlib import Path
if __package__ in (None, ""):
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from agent.prefetch.topic_search import cosine_similarity
from core.local_embeddings import embed_text
from core.storage import conn
MEMORY_TOP_K = 8
MEMORY_M... | protocorn/clippy-vision | agent/prefetch/memory_query.py | .py | 0bba8dcfcd029e85 | 7.56 | 12 |
"""Grading: deterministic substring checks first, fixed-prompt LLM judge for semantic
cases. Judge calls go through the gateway at temperature 0 and are counted separately
so judging cost never contaminates a strategy's own cost score.
"""
import json
import _paths # noqa: F401
from core.llm_gateway import Priority,... | protocorn/clippy-vision | bench/grader.py | .py | 2902cd966ba902ad | 7.56 | 12 |
"""
Benchmark: Classification Cascade Efficiency
Measures how much the 3-tier cascade reduces LLM inference calls.
"""
import json
import sys
from pathlib import Path
# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))
# Change to parent directory so relative imports work
import os
... | protocorn/clippy-vision | bench/test_classification_cascade.py | .py | a69e9c3a42faf35e | 7.06 | 12 |
"""
Benchmark: Screenshot pHash Dedup
Measures how much perceptual-hash clustering reduces frames to enrich.
"""
import sys
from pathlib import Path
# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))
# Change to parent directory so relative imports work
import os
os.chdir(Path(__fi... | protocorn/clippy-vision | bench/test_screenshot_dedup.py | .py | 4310dca474f9fc53 | 8.06 | 12 |
"""Classification backlog status and automatic catch-up gates.
When capture is off, the API catch-up worker drains stranded ``pending``
(Tier-0/1) then ``deferred`` (Tier-2). When capture is on, live owns pending;
catch-up only runs Tier-2 if the deferred queue is large/old enough.
"""
from __future__ import annotati... | protocorn/clippy-vision | core/backlog.py | .py | 8d7954d24c512357 | 7.56 | 12 |
"""Tiny cross-process state file for desktop and browser status indicators."""
from __future__ import annotations
import json
import time
from pathlib import Path
try:
from core.paths import get_data_dir
except ImportError:
from paths import get_data_dir
def _state_path() -> Path:
# Electron and the bro... | protocorn/clippy-vision | core/capture_state.py | .py | 8c3a086415f19d39 | 7.56 | 12 |
import json
import queue
import threading
import time
import urllib.error
import urllib.request
from itertools import count
import psutil
from core.local_embeddings import embed_text, embed_texts
from core.model_residency import can_load_text, keep_alive_for, text_unavailable_reason
from core.ollama_client import (
... | protocorn/clippy-vision | core/llm_gateway.py | .py | 053ddfb1674238e7 | 7.56 | 12 |
import json
import os
import sqlite3
import sys
import time
from typing import Optional
try:
from core.storage import conn
except ImportError:
# Ensure core/ is on sys.path so 'storage' can be found whether this module
# is imported as 'storage' (from core/) or as 'core.memory_store' (from root).
from ... | protocorn/clippy-vision | core/memory_store.py | .py | 25f3e6927530c1d3 | 7.56 | 12 |
"""Text model residency for the local assistant.
Startup (API): pin the local Ollama text model.
Capture: accessibility text and OCR run without loading a vision model.
Persists to <data>/model_residency.json. Gateway reads policy via keep_alive_for().
"""
from __future__ import annotations
import json
import subpr... | protocorn/clippy-vision | core/model_residency.py | .py | 11fef9e981f17edf | 7.56 | 12 |
from __future__ import annotations
import re
import threading
from pathlib import Path
OCR_MIN_CONFIDENCE = 0.55
OCR_MAX_CHARS = 4000
_engine = None
_engine_lock = threading.Lock()
_engine_error = None
_space_re = re.compile(r"\s+")
def _get_engine():
global _engine, _engine_error
if _engine is not None or... | protocorn/clippy-vision | core/ocr.py | .py | be7ecdff0422672d | 7.56 | 12 |
"""Persist and apply best-effort content crops for screenshot OCR."""
from __future__ import annotations
import json
from pathlib import Path
from PIL import Image
_CROP_VERSION = 1
_MIN_CROP_WIDTH = 160
_MIN_CROP_HEIGHT = 100
def crop_metadata_path(screenshot_path: Path) -> Path:
return screenshot_path.with_s... | protocorn/clippy-vision | core/ocr_crop.py | .py | 433a448365ac14b1 | 7.56 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.