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
"""Report cosmic-ray survivors with the tests that ran against each. A count is not a report. `lesson-a-mutation-harness-reports-shape-not-just-pass` records the reason: a mutant that kills fewer, or different, tests than expected is itself the finding, and a harness printing only KILLED or SURVIVED hides it. So this ...
nordscope-fi/Discord-stoat-ferry
scripts/mutation_report.py
.py
e9639ad72a8d75b5
7.5
9
"""Server blueprint export, import, and build — portable server structure definitions.""" from __future__ import annotations import json from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any from discord_ferry.core.atomicio import atomic_write_text if TYPE_CHECKING: from pathlib import ...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/blueprint.py
.py
efec623c3f9de52f
7.5
9
"""Entry-point dispatch and console acquisition for the frozen binary. PyInstaller's entry script is gui.py, whose main() never read sys.argv, so the packaged Ferry.exe discarded every argument including --help (issue #123). It is also built with console=False, which means that on Windows sys.stdout and sys.stderr are...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/core/entry.py
.py
723fc96e152b1ba3
7.5
9
"""Always-on file logging with token redaction. Ferry ships its GUI as a windowed PyInstaller binary (``ferry.spec`` sets ``console=False``), which means ``sys.stdout`` and ``sys.stderr`` are ``None``. Nothing in ``src/`` ever attached a logging handler, so the 13 module loggers -- and, worse, NiceGUI's own uncaught-b...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/core/logging_setup.py
.py
0b72e7a34fbcdb6c
7.5
9
"""Async HTTP client for the Discord REST API (guild metadata only).""" from __future__ import annotations import asyncio import json import logging import math from typing import TYPE_CHECKING, Any, cast import aiohttp from discord_ferry.core.http import proxy_error_is_permanent, proxy_hint, tls_hint from discord_...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/discord/client.py
.py
766e4a621b40f0ee
7.5
9
"""Dataclasses for Discord REST API responses.""" from dataclasses import dataclass, field @dataclass class PermissionOverwrite: """A single permission overwrite entry from a Discord channel.""" id: str type: int # 0 = role, 1 = member allow: int # Discord permission bitfield deny: int # Disc...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/discord/models.py
.py
37d2fde92bb9edfd
7.5
9
"""Pure parser for DiscordChatExporter (DCE) stdout lines. Public surface: - parse_dce_line(line: str) -> ParsedDceLine (total, no I/O) - ParsedDceLine = PerChannel | Phase | Success | Banner | StatusDot | Error | Raw This module has zero side effects and zero subprocess interaction. The runner calls parse_dce_l...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/exporter/dce_output.py
.py
ca0a070349923609
7.5
9
"""DCE binary download, verification, and platform detection.""" from __future__ import annotations import asyncio import hashlib import io import json as _json import logging import platform import subprocess import time as _time import zipfile from pathlib import Path from typing import TYPE_CHECKING import aiohtt...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/exporter/manager.py
.py
7690ecff5a7e943e
7.5
9
"""Async subprocess execution for DiscordChatExporter.""" from __future__ import annotations import asyncio import contextlib import logging import os import shutil import signal import subprocess import sys import time from dataclasses import dataclass, field from typing import TYPE_CHECKING import aiohttp from di...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/exporter/runner.py
.py
099cea0b80f68c10
7.5
9
"""Live validation probe for a Stoat instance (read-mostly diagnostics).""" from __future__ import annotations import contextlib import struct import tempfile import zlib from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any import aiohttp # noqa: TCH002 from disco...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/migrator/probe.py
.py
6ce0bc4f6b3940dd
7.5
9
"""String sanitization helpers for Stoat API field limits and filesystem safety.""" from __future__ import annotations import re # Stoat API enforces maxLength: 32 on most name fields. _DEFAULT_MAX_LENGTH = 32 # Emoji names must match ^[a-z0-9_]+$ per OpenAPI spec. _EMOJI_NAME_RE = re.compile(r"[^a-z0-9_]") # Char...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/migrator/sanitize.py
.py
78b802d272b0c3a2
7.5
9
"""Migration report generator.""" from __future__ import annotations import json from datetime import datetime from typing import TYPE_CHECKING from discord_ferry.core.atomicio import atomic_write_text from discord_ferry.core.security import safe_sanitize, sanitize_secrets, scrub_document from discord_ferry.discord....
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/reporter.py
.py
2db7c8b539bc0a6f
7.5
9
"""State-only migration stats summarizer. This module exists to give ``ferry stats <output-dir>`` everything it needs without re-parsing DCE exports or reconstructing FerryConfig. Contract: ``summarize_state`` takes a ``MigrationState`` and returns a typed ``StateSummary`` — no I/O, no external dependencies beyond rep...
nordscope-fi/Discord-stoat-ferry
src/discord_ferry/stats.py
.py
b18a9c922c6bbdfd
7.5
9
#!/usr/bin/env python3 """Print the containing Teamwork checkout root after validating its layout.""" from __future__ import annotations import json import stat from pathlib import Path from typing import Any SUPPORTED_AGENT_HOSTS = frozenset({"codex", "cursor", "claude"}) REQUIRED_CHECKOUT_FILES = { "VERSION",...
JinPLu/Teamwork
scripts/plugin-runtime-root.py
.py
cfafc9f37e41c10a
7.54
11
"""Setup hook for memory-system: directory tree, stub files, yaml edits, optional schedule overlay.""" from __future__ import annotations import io from pathlib import Path from ruamel.yaml import YAML from aegis.config.edit import add_agent as _add_agent from aegis.plugins.install_context import InstallContext from...
apiad/aegis
plugins/memory-system/_install.py
.py
f715a7a758970b16
7.66
20
"""skill-system plugin: replicates Claude-Code's skill-selection on any harness. A pre_turn hook injects a numbered menu of available skills as a system context block. A first-class MCP tool exposes load_skill(name) so the agent can pull the full body when relevant. Skills live as Claude-Code-compatible markdown file...
apiad/aegis
plugins/skill-system/skill_system.py
.py
45f2ae60ddcaa97c
7.66
20
"""Install hook for socks-proxy: prompt for endpoint, generate the conf.""" from __future__ import annotations import shutil from aegis.plugins.install_context import InstallContext CONF_BODY_TEMPLATE = """\ # Generated by the aegis socks-proxy plugin. # # Edit the [ProxyList] entry below to point at your SOCKS end...
apiad/aegis
plugins/socks-proxy/_install.py
.py
6b0caf5b9c727236
7.66
20
"""socks-proxy plugin: tunnel harness subprocesses through a SOCKS proxy. A ``pre_spawn`` hook prepends ``proxychains4 -q -f <conf>`` to the argv of every harness session, so the spawned ``claude`` / ``gemini`` / ``opencode`` process talks to its API endpoint via the configured SOCKS proxy. proxychains4 intercepts ``c...
apiad/aegis
plugins/socks-proxy/socks_proxy.py
.py
c1f130f0e8d955f4
7.66
20
"""Assemble a bounded conversation window for `/btw`. Pure: events in, text out. No LLM, no disk, no bridge — which is why this is the piece worth testing hard. Everything downstream of it is one API call. Two properties are invariants rather than details: - **Newest-first.** The window fills backwards from the newe...
apiad/aegis
src/aegis/btw/window.py
.py
003144567b21d463
7.66
20
"""Compute USD cost from SessionMetrics + price table.""" from __future__ import annotations from dataclasses import dataclass from decimal import Decimal from aegis.budget.prices import lookup _MILLION = Decimal("1000000") @dataclass(frozen=True) class Cost: """A worker's finalized cost, ready to land on a ta...
apiad/aegis
src/aegis/budget/cost.py
.py
e6a723e5ae90c351
7.66
20
"""Typed exceptions for budget rejection.""" from __future__ import annotations from aegis.budget.evaluator import Decision class BudgetExceeded(Exception): """Raised when a queue's budgets reject an enqueue. Carries the full Decision so callers can inspect blocked_by / unblock_at and choose a retry str...
apiad/aegis
src/aegis/budget/errors.py
.py
4ad62b5092a07836
7.66
20
"""Pure markdown section parser/writer for shared canvases. Sections are top-level ``## headings``. Pre-``##`` text goes in the implicit ``_preamble`` section. A file with no ``##`` headings is one big ``body`` section. No I/O here — this module just round-trips text ↔ ordered sections. """ from __future__ import ann...
apiad/aegis
src/aegis/canvas/parser.py
.py
1144a009897d350d
7.66
20
"""``aegis models`` CLI subapp — inspect and manage the model registry. Subcommands: - ``refresh`` — synchronously refetch ``~/.cache/aegis/models.yaml`` from the upstream GitHub raw URL and force the in-memory registry to reload. Use this when you just pushed a new ``models.yaml`` and don't want to wait for th...
apiad/aegis
src/aegis/cli_models.py
.py
0561d9fbc932103f
7.66
20
"""`aegis plugin ...` Typer subapp.""" from __future__ import annotations from pathlib import Path import typer from rich.console import Console from rich.table import Table from aegis.plugins import lockfile from aegis.plugins.install import InstallError, install_plugin from aegis.plugins.uninstall import Uninstall...
apiad/aegis
src/aegis/cli_plugin.py
.py
7b298351ad6d5f17
7.66
20
"""Declarative argument parsing for slash commands. A command declares an ``ArgSpec`` (positionals + flags); ``parse`` turns the raw argument string into a validated ``Args``. Parsing rule: ``--flag`` tokens are recognized anywhere among the non-greedy positionals (so a boolean flag may lead or trail), while positiona...
apiad/aegis
src/aegis/commands/args.py
.py
b47f1b9c12abb4a3
7.66
20
"""`/loop` — arm a looping instruction on this pane's session. The instruction is re-delivered at every turn boundary where the session would otherwise settle idle, until the agent reaps it with aegis_loop_stop, the iteration cap is reached, or the operator stops it. """ from __future__ import annotations from aegis....
apiad/aegis
src/aegis/commands/builtins/loop.py
.py
34018c7ba602ee41
7.66
20
"""``/usage`` — session usage & cost analytics, rendered as a transcript block. Reuses the same engine + renderer as the ``aegis usage`` CLI, so the TUI and web client show identical data. Read-only. /usage dashboard (cost, averages, models, tools, top) /usage tools tool → cos...
apiad/aegis
src/aegis/commands/builtins/usage.py
.py
19b754bf092bf895
7.66
20
#!/usr/bin/env python3 """CI check requiring a CHANGELOG.md update on PRs unless labeled 'no-changelog'.""" from __future__ import annotations import json import os import subprocess import sys from pathlib import Path OPT_OUT_LABEL = "no-changelog" CHANGELOG_FILENAME = "CHANGELOG.md" def get_pr_labels(event_path:...
Rekin226/aquascope
.github/scripts/check_changelog.py
.py
f6209266acff3dd5
7.65
19
""" AquaScope — Open-source water data aggregation and AI-powered research methodology recommender. Collects water-quality, hydrology, and environmental data from Taiwan's open APIs and global sources (USGS, UN SDG 6, GEMStat, WQP), then uses AI to suggest suitable research methodologies for water-related studies. Qu...
Rekin226/aquascope
aquascope/__init__.py
.py
9708071bdc78a30a
7.65
19
"""Daily soil water balance model. Implements the FAO-56 single crop coefficient approach for tracking soil moisture depletion and irrigation scheduling. The water balance equation:: Dr,i = Dr,i-1 - (P - RO)i - Ii - CRi + ETc,i + DPi where: Dr = root zone depletion (mm) P = precipitation RO = runof...
Rekin226/aquascope
aquascope/agri/water_balance.py
.py
796429f289e50938
7.65
19
"""A dependency-free OpenAI-compatible chat client (``urllib`` only). Why: the ``openai`` SDK pulls in a compiled JSON parser and cannot be installed in Pyodide, so the Explorer's browser worker could not run :func:`aquascope.ai_engine.analyst.ask`. This client speaks the same ``/chat/completions`` protocol (messages,...
Rekin226/aquascope
aquascope/ai_engine/llm_transport.py
.py
71ea90b90e0849fc
7.65
19
""" Model recommender — expert-curated decision matrix mapping challenge types to models. Works alongside the existing research-methodology recommender by providing model-specific recommendations for predictive / forecasting tasks. """ from __future__ import annotations import logging from dataclasses import datacla...
Rekin226/aquascope
aquascope/ai_engine/model_recommender.py
.py
e9cb77745fdfcb98
7.65
19
""" Natural-language challenge planner — parses user descriptions into structured challenges. Works entirely offline via keyword matching (no LLM required). """ from __future__ import annotations import logging import re from dataclasses import dataclass, field logger = logging.getLogger(__name__) _CHALLENGE_KEYWO...
Rekin226/aquascope
aquascope/ai_engine/planner.py
.py
3c57d57bdaee21b9
7.65
19
"""The LLM providers AquaScope can talk to, in one place. There used to be three lists that disagreed: :mod:`aquascope.ai_engine.analyst` (the tool loop), :mod:`aquascope.ai_engine.recommender` (the dashboard picker) and ``explorer/app.js`` (the browser). They drifted, and when Groq retired ``llama-3.3-70b-versatile``...
Rekin226/aquascope
aquascope/ai_engine/providers.py
.py
81c67de8ad317b2b
7.65
19
"""Run model-written Python against aquascope, inside limits. The Analyst's ten tools cover the questions we anticipated. The ones we did not anticipate ("decadal maxima", "the ratio of these two records", "the same analysis for every donor") need code, and the whole library is already loaded next to the data: in the ...
Rekin226/aquascope
aquascope/ai_engine/sandbox.py
.py
f07ee2c5b4eeccbf
7.65
19
"""Check an answer against the tool results it was supposed to come from. The Analyst's strongest property is that the Data and Methods sections are assembled from tool output rather than written by the model. The prose in between is still the model's, and that is where a wrong number can appear: a return level quoted...
Rekin226/aquascope
aquascope/ai_engine/verify.py
.py
a66d896c9e82fdb1
7.65
19
""" Exploratory Data Analysis (EDA) module. Auto-profiles water quality datasets and generates summary reports with statistics, distributions, correlations, and coverage maps. """ from __future__ import annotations import logging from dataclasses import dataclass, field import pandas as pd from aquascope.ai_engine...
Rekin226/aquascope
aquascope/analysis/eda.py
.py
a32ded9ee28ff306
7.65
19
"""Extreme-value and flood/drought frequency analysis. Block-maxima frequency analysis for hydrological extremes. Fits the Generalised Extreme Value (GEV), Log-Pearson Type III (LP3) and Gumbel distributions to a series of annual maxima and estimates return levels (design magnitudes) for a set of return periods, with ...
Rekin226/aquascope
aquascope/analysis/extreme_events.py
.py
160db82c4628866d
7.65
19
""" Data quality assessment and preprocessing pipeline. Evaluates completeness, consistency, outliers, and duplicates in collected water data, then applies configurable preprocessing steps. """ from __future__ import annotations import logging from dataclasses import dataclass, field import pandas as pd logger = l...
Rekin226/aquascope
aquascope/analysis/quality.py
.py
48659673a9fb70a5
7.65
19
"""Read the published station catalog (the Archive) without any agency call. ``load_stations()`` downloads ``stations.parquet`` from the Hugging Face dataset once a day into a local cache and returns plain dicts, so the MCP server, the CLI and notebooks can answer "which gauges are near X" in milliseconds. Falls back ...
Rekin226/aquascope
aquascope/archive/catalog.py
.py
7f3266895f41a380
7.65
19
""" Drought challenge handler — SPI-based monitoring, forecasting, and water balance. """ from __future__ import annotations import logging import pandas as pd logger = logging.getLogger(__name__) class DroughtChallenge: """High-level interface for drought monitoring and forecasting. Uses SPI (Standardis...
Rekin226/aquascope
aquascope/challenges/drought.py
.py
9b537e16f00d36e0
7.65
19
""" Flood challenge handler — forecasting, risk assessment, and return-period estimation. """ from __future__ import annotations import logging import pandas as pd logger = logging.getLogger(__name__) class FloodChallenge: """High-level interface for flood forecasting and risk assessment. Combines stream...
Rekin226/aquascope
aquascope/challenges/flood.py
.py
855074bf75f19056
7.65
19
""" Water-quality challenge handler — anomaly detection, WHO guidelines, and trend analysis. """ from __future__ import annotations import logging import pandas as pd logger = logging.getLogger(__name__) WHO_GUIDELINES: dict[str, tuple[float, float]] = { "ph": (6.5, 8.5), "dissolved_oxygen": (5.0, float("i...
Rekin226/aquascope
aquascope/challenges/quality.py
.py
1da0ebc8b3d92bae
7.65
19
#!/usr/bin/env python3 """ MSPlay IPTV - Modern IPTV Channel Scraper and Validator GitHub: https://github.com/januaropik3/msplayiptv """ import logging import sys from pathlib import Path from typing import Optional # Add src to path sys.path.insert(0, str(Path(__file__).parent / "src")) from src import ( scrape...
hirotomasato/msplayiptv
main.py
.py
44da4edf5169bea1
7.52
10
#!/usr/bin/env python3 """ Update README.md with current statistics """ import json import re from pathlib import Path from datetime import datetime, timezone def load_stats(): """Load statistics from stats.json""" stats_file = Path("static/stats.json") if not stats_file.exists(): return None ...
hirotomasato/msplayiptv
scripts/update_readme_stats.py
.py
e5e76e806bdf2916
7.52
10
""" Configuration module for MSPlay IPTV """ from typing import Dict, List from dataclasses import dataclass @dataclass class Config: """Application configuration""" # M3U sources M3U_SOURCES: Dict[str, str] = None # Target categories to include TARGET_CATEGORIES: List[str] = None ...
hirotomasato/msplayiptv
src/config.py
.py
49e50df5045bf53d
7.52
10
""" M3U File Generator and Manager """ from typing import List, Dict from pathlib import Path import logging from datetime import datetime, timezone from .models import Channel, ChannelCategory from .utils import ensure_directory, format_number from .config import config logger = logging.getLogger(__name__) class M3...
hirotomasato/msplayiptv
src/generator.py
.py
215f0b951262ac97
7.52
10
""" Data models for MSPlay IPTV """ from dataclasses import dataclass from typing import Optional, Dict, Any from enum import Enum class ChannelCategory(Enum): """Channel categories""" KIDS = "Kids" MOVIES = "Movies" SPORTS = "Sports" NEWS = "News" MUSIC = "Music" ENTERTAINMENT = "Entertain...
hirotomasato/msplayiptv
src/models.py
.py
8c17ee1ad3a58aa1
7.52
10
""" Utilities for MSPlay IPTV """ import re import time import requests from typing import Optional, Tuple, List from pathlib import Path import logging from .models import Channel, ChannelCategory # Setup logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class CategoryExtractor: ...
hirotomasato/msplayiptv
src/utils.py
.py
791ac58db63d98f8
7.52
10
""" IPTV Channel Validator """ import asyncio import time from typing import List, Tuple from concurrent.futures import ThreadPoolExecutor, as_completed import logging from .models import Channel, ValidationResult, ValidationStats from .utils import StreamValidator, format_time from .config import config logger = log...
hirotomasato/msplayiptv
src/validator.py
.py
93c414e3d895ffbc
7.52
10
#!/usr/bin/env python3 """fleet-boot-gate — two-level "cheap insurance" at boot. Level 1 (APPLICATION): fast weight integrity — size + first/last 1 MiB sha256 of every GGUF against fleet/boot-gate-baseline.json (pinned in the repo next to the full sha256s in models/models.ini). ~2 s for all 5 files vs ~45 s for the fu...
PieBru/Qwen-3.8-27B_Strix-Halo_gfx1151
fleet/fleet-boot-gate.py
.py
f72d335ed56d8a9f
7.5
9
#!/usr/bin/env python3 """fleet-pre-drain — automatic zero-loss drain at shutdown. Runs from fleet-pre-drain.service (SYSTEM unit, Before=shutdown.target, User=piero — see that file for why system-level: user units cannot order against system shutdown targets). Steps: 1. Which halo am I? (halo1=strixy2, halo2=strixy-...
PieBru/Qwen-3.8-27B_Strix-Halo_gfx1151
fleet/fleet-pre-drain.py
.py
66b3f24972a28bdd
7.5
9
#!/usr/bin/env python3 """lane-drain (traddy) — drain the capability lane before this box shuts down. traddy is NOT a VIP member, so "drain" = disable server traddy/traddy on BOTH halos' haproxy (whichever owns the VIP serves traffic; disabling on both is idempotent and covers a failover mid-shutdown), then wait until...
PieBru/Qwen-3.8-27B_Strix-Halo_gfx1151
fleet/traddy/lane-drain.py
.py
77e378979a635098
7.5
9
#!/usr/bin/env python3 """lane-enable (traddy) — bring the capability lane back after boot. Order: ff-pull the clone (deploy discipline), wait for the local router to be healthy (lazy builds can be slow), re-enable traddy/traddy on both halos (undo a shutdown drain — haproxy MAINT survives traddy reboots), then fire a...
PieBru/Qwen-3.8-27B_Strix-Halo_gfx1151
fleet/traddy/lane-enable.py
.py
0d06ce8d22480334
7.5
9
import re import sys import argparse def minify_jinja(content): """ Minifies a Jinja2 template by removing comments and collapsing whitespace. This function is designed to be "safe" for chat templates: 1. It removes all Jinja2 comments. 2. It replaces newlines with spaces to ensure words don't...
PieBru/Qwen-3.8-27B_Strix-Halo_gfx1151
results/froggeric-suite/minify_jinja.py
.py
a963cacff255ff39
7.5
9
#!/usr/bin/env python3 import os os.chdir(os.path.dirname(os.path.abspath(__file__)) + "/..") # repo root (script lives in scripts/) """e4 fill-decode decay battery — re-measures the README fill-decay table. Why: the adversarial audit (2026-08-23) flagged that the original decode-vs- filled table (24.7 -> 9.8 t/s) ha...
PieBru/Qwen-3.8-27B_Strix-Halo_gfx1151
scripts/e4_decay_battery.py
.py
7af86c38ce63c3cb
7.5
9
#!/usr/bin/env python3 """Split README.md into front page + docs/ detail pages (one-shot tool). Keeps in README: Why/TL;DR/headlines/quickstart/repo contents/recipes table + dial, Lessons, Thanks, License. Moves deep chapters to docs/ pages by reader intent. Old external anchors preserved via stub headings in README. ...
PieBru/Qwen-3.8-27B_Strix-Halo_gfx1151
tools/split_readme.py
.py
d37d95dba6f54568
7.5
9
#!/usr/bin/env python """boto3 Bedrock Runtime client traced via braintrust.auto_instrument().""" import os import braintrust braintrust.auto_instrument() braintrust.init_logger(project="example-bedrock") import boto3 # noqa: E402 MODEL = os.getenv("BRAINTRUST_BEDROCK_MODEL", "us.amazon.nova-lite-v1:0") REGION ...
braintrustdata/braintrust-sdk-python
examples/bedrock_runtime/example.py
.py
8c5343b8f3ac08ce
7.63
17
#!/usr/bin/env python """DSPy ReAct agent traced via braintrust.auto_instrument(). Run with: OPENAI_API_KEY=<key> BRAINTRUST_API_KEY=<key> uv run python example.py """ import braintrust # auto_instrument() patches LiteLLM (which DSPy uses internally) and DSPy's # `configure()` so the Braintrust callback is attached...
braintrustdata/braintrust-sdk-python
examples/dspy/example.py
.py
9c1d6a984d91698b
7.63
17
#!/usr/bin/env python3 # type: ignore """ Example showing how to migrate LangSmith evaluate() to Braintrust. This example demonstrates: 1. Setting up the LangSmith wrapper 2. Using client.evaluate() (redirects to Braintrust's Eval) 3. LangSmith-style evaluators working with Braintrust """ import os # Enable LangSmi...
braintrustdata/braintrust-sdk-python
examples/langsmith/eval_example.py
.py
995487bdbed990b7
7.63
17
#!/usr/bin/env python3 """ Example showing how to migrate LangSmith @traceable to Braintrust. This example demonstrates: 1. Setting up the LangSmith wrapper 2. Using @traceable decorated functions (traces go to Braintrust) 3. Nested tracing with multiple functions """ import os # Enable LangSmith tracing (required ...
braintrustdata/braintrust-sdk-python
examples/langsmith/tracing_example.py
.py
c15624c3e9826aa1
7.63
17
#!/usr/bin/env python3 """ Example: Braintrust + OTEL Context Integration This example demonstrates how Braintrust spans automatically capture OTEL context information when created within active OTEL spans, enabling correlation between pure OTEL instrumentation and Braintrust observability. Key concept: No bridge nee...
braintrustdata/braintrust-sdk-python
examples/otel/bt-otel-context.py
.py
e77232ce0a3c63af
7.63
17
#!/usr/bin/env python3 """ Example: Distributed Tracing between Braintrust and OpenTelemetry This example demonstrates how to propagate trace context across service boundaries using Braintrust span.export() and OpenTelemetry. This enables unified distributed tracing where spans can be parents/children across different...
braintrustdata/braintrust-sdk-python
examples/otel/distributed-tracing.py
.py
2f09b948f4727718
7.63
17
import asyncio import os from dataclasses import dataclass from datetime import timedelta import braintrust from temporalio import activity, workflow from temporalio.common import RetryPolicy TASK_QUEUE_NAME = "braintrust-example-task-queue" @dataclass class TaskInput: value: int @activity.defn async def add...
braintrustdata/braintrust-sdk-python
examples/temporal/workflow.py
.py
0c5ed03b9bd77c25
7.63
17
""" An example showing how to use the `wrap_agent`, `wrap_flow`, and `wrap_runner` functions to manually patch the Google ADK classes. In most cases you should consider using `setup_adk`, but this may be helpful in specific cases. """ import asyncio from google.adk import Agent from google.adk.runners import Runner ...
braintrustdata/braintrust-sdk-python
integrations/adk-py/examples/manual.py
.py
06e66dd5b5443aaa
7.63
17
import datetime from typing import Dict from zoneinfo import ZoneInfo from google.adk.agents import LlmAgent from braintrust import traced from braintrust_adk import setup_adk @traced def isNewYork(city: str) -> bool: return city.lower() == "new york" @traced def get_weather(city: str) -> Dict[str, str]: ...
braintrustdata/braintrust-sdk-python
integrations/adk-py/examples/multi_tool_agent/agent.py
.py
0c2e099bfe35f1f2
7.63
17
import hashlib import secrets import string from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from xngin.apiserver import constants from xngin.apiserver.sqla import tables API_KEY_PREFIX = "xat" HASH_PURPOSE = b"xnginapikey1" class BaseApiKeyError(Exception): status_code = 400 ...
agency-fund/evidential-be
src/xngin/apiserver/apikeys.py
.py
e9549d840823a970
7.5
9
import hashlib from pathlib import Path PATH_TO_AMAZON_TRUST_CA_BUNDLE = ( (Path(__file__).resolve().parent / "amazon-trust-ca-bundle.crt").resolve(strict=True).as_posix() ) CERT_FILES_HASHES = { PATH_TO_AMAZON_TRUST_CA_BUNDLE: "36dba8e4b8041cd14b9d60158893963301bcbb92e1c456847784de2acb5bd550", } class Cert...
agency-fund/evidential-be
src/xngin/apiserver/certs/certs.py
.py
f81da0cb013680d1
7.5
9
import inspect import json import logging import sys import traceback import typing from xngin.apiserver.flags import LogFormat if typing.TYPE_CHECKING: from loguru import Message as loguru_Message from loguru import Record as loguru_Record from loguru import logger from xngin.apiserver import flags clas...
agency-fund/evidential-be
src/xngin/apiserver/customlogging.py
.py
f09c400816c5b527
7.5
9
"""Handles SQLAlchemy connections to the application database.""" import contextlib import dataclasses import os from loguru import logger from sqlalchemy import make_url from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from sqlalchemy.ext.asyncio.engine import AsyncEngine from xngin.apiser...
agency-fund/evidential-be
src/xngin/apiserver/database.py
.py
ebffc317693e7b83
7.5
9
import httpx2 from xngin.apiserver import database class CannotFindDatasourceError(Exception): """Error raised when an invalid Datasource-ID is provided in a request.""" def random_seed_dependency(): """Returns None; to be overridden by tests.""" return async def xngin_db_session(): """Returns a ...
agency-fund/evidential-be
src/xngin/apiserver/dependencies.py
.py
9bacd2a818d03bf4
7.5
9
import ipaddress import socket from sys import platform from dns.exception import DNSException from dns.resolver import resolve from loguru import logger from xngin.apiserver.flags import ALLOW_CONNECTING_TO_PRIVATE_IPS DNS_TIMEOUT_SECS = 5 # Sentinel value that unit tests can use to ensure a host is treated as inv...
agency-fund/evidential-be
src/xngin/apiserver/dns/safe_resolve.py
.py
ab66d84c94914cff
7.5
9
"""Unit tests for the SSRF guard in safe_resolve. The session-wide ``safe_resolve_testing_mode`` fixture sets ``ALLOW_CONNECTING_TO_PRIVATE_IPS = True``; these tests override it where they need the production safety checks. """ import pytest from xngin.apiserver.dns import safe_resolve # IPv4 multicast is never a v...
agency-fund/evidential-be
src/xngin/apiserver/dns/test_safe_resolve.py
.py
20e2b00847d315d8
8
9
from sqlalchemy import URL, Engine REDSHIFT_HOSTNAME_SUFFIXES = ("redshift.amazonaws.com", "redshift-serverless.amazonaws.com") def is_redshift(host_or_url: str | URL) -> bool: """ Returns true iff the hostname string or URL indicates that this is connecting to Redshift. Will NOT work with Redshift's cu...
agency-fund/evidential-be
src/xngin/apiserver/dwh/dwh_utils.py
.py
163e817ba119b9bf
7.5
9
"""Methods for converting SQLAlchemy metadata into our application-specific types.""" import sqlalchemy from xngin.apiserver.dwh.inspection_types import FieldDescriptor, ParticipantsSchema from xngin.apiserver.routers.admin.admin_api_types import ( ColumnDeleted, Drift, FieldChangedType, FieldMetadata...
agency-fund/evidential-be
src/xngin/apiserver/dwh/inspections.py
.py
7ff74495a9232a06
8
9
from collections import Counter from collections.abc import Sequence from dataclasses import dataclass from typing import TYPE_CHECKING import numpy as np import sqlalchemy from loguru import logger from sqlalchemy import Float, Integer, Label, String, Table, cast, or_, select from sqlalchemy.orm import Session from ...
agency-fund/evidential-be
src/xngin/apiserver/dwh/participant_metrics_queries.py
.py
769b83804539a662
7.5
9
from collections.abc import Sequence import sqlalchemy from sqlalchemy import ( Float, Integer, Label, Select, Table, cast, distinct, func, select, ) from sqlalchemy.engine.row import RowMapping from sqlalchemy.orm import Session from xngin.apiserver.dwh.inspection_types import Fie...
agency-fund/evidential-be
src/xngin/apiserver/dwh/queries.py
.py
9a24606053c868c1
7.5
9
from collections.abc import Sequence from datetime import date, datetime import sqlalchemy from sqlalchemy import ColumnElement, Table, and_, or_, select, text from xngin.apiserver.routers.common_api_types import Filter, FilterValueTypes from xngin.apiserver.routers.common_enums import DataType, Relation from xngin.a...
agency-fund/evidential-be
src/xngin/apiserver/dwh/query_constructors.py
.py
60556489773dad90
7.5
9
from deepdiff import DeepDiff from sqlalchemy import BigInteger, Column, Double, Integer, MetaData, String, Table from xngin.apiserver.dwh.inspection_types import FieldDescriptor from xngin.apiserver.dwh.inspections import build_proposed_and_drift, create_schema_from_table from xngin.apiserver.routers.admin.admin_api_...
agency-fund/evidential-be
src/xngin/apiserver/dwh/test_inspections.py
.py
0ed6a90f7769c0bb
7
9
"""Tests for queries.py.""" import asyncio import pytest from sqlalchemy import text from sqlalchemy.exc import DataError from xngin.apiserver.conftest import DbType, get_queries_test_uri from xngin.apiserver.dwh.dwh_session import DwhSession from xngin.apiserver.dwh.queries import get_stats_on_metrics from xngin.ap...
agency-fund/evidential-be
src/xngin/apiserver/dwh/test_queries.py
.py
4881b9d4efb8bf15
7
9
from collections.abc import Sequence import psycopg.errors import sqlalchemy from fastapi import Request from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from pydantic import BaseModel, ValidationError from xngin.apiserver.apikeys import BaseApiKeyError from xngin.apiserver.dep...
agency-fund/evidential-be
src/xngin/apiserver/exceptionhandlers.py
.py
34a05c822b26ac2a
7.5
9
class LateValidationError(Exception): """Raised by API request validation failures that can only occur late in processing. Examples: - datetime value validations cannot happen until we know we are dealing with a datetime field, and that information is not available until we have table reflection data. ...
agency-fund/evidential-be
src/xngin/apiserver/exceptions_common.py
.py
3e41e0be6d8b96f2
7.5
9
"""Flags describes values that are read from the environment.""" import enum import os from xngin.apiserver import constants def is_dev_environment(): return os.environ.get("ENVIRONMENT", "") in {"dev", ""} def is_railway() -> bool: return os.environ.get("RAILWAY_SERVICE_NAME", "") != "" def truthy_env(...
agency-fund/evidential-be
src/xngin/apiserver/flags.py
.py
b8075304669c7e18
7.5
9
import os from contextlib import asynccontextmanager import uvicorn from fastapi import FastAPI from loguru import logger from xngin.apiserver import ( customlogging, database, exceptionhandlers, flags, middleware, routes, ) from xngin.apiserver.openapi import custom_openapi, humane_operation_...
agency-fund/evidential-be
src/xngin/apiserver/main.py
.py
9d36ad32e9052a31
7.5
9
import dataclasses from typing import TYPE_CHECKING from fastapi.openapi.utils import get_openapi from fastapi.routing import APIRoute from xngin.apiserver import constants, flags from xngin.apiserver.flags import PUBLISH_ALL_DOCS if TYPE_CHECKING: from fastapi import FastAPI def humane_operation_id(route: API...
agency-fund/evidential-be
src/xngin/apiserver/openapi.py
.py
977fc188c8f02bf6
7.5
9
"""Cursor-based pagination utilities following Google AIP-158.""" import base64 from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass from datetime import UTC, datetime from typing import Annotated, Any, Literal from fastapi import Query from pydantic import BaseModel, ConfigDict, ...
agency-fund/evidential-be
src/xngin/apiserver/pagination.py
.py
508711c9d9fd3843
7.5
9
import json import starlette.datastructures from jsonpath import JSONPointer, JSONPointerError from starlette.datastructures import Headers from starlette.responses import JSONResponse from starlette.types import ASGIApp, Message, Receive, Scope, Send _SUPPORTED_METHODS = {"PATCH", "POST", "PUT"} class RequestEncap...
agency-fund/evidential-be
src/xngin/apiserver/request_encapsulation_middleware.py
.py
7d7835ead8e1c16a
7.5
9
import sqlalchemy from sqlalchemy import select from xngin.apiserver.sqla import tables def is_user_authorized_on_datasource(user: tables.User, datasource_id: str) -> sqlalchemy.Select: """Create a query that checks if a user is authorized to manage a datasource.""" return ( select(tables.Datasource....
agency-fund/evidential-be
src/xngin/apiserver/routers/admin/authz.py
.py
f894922b4a077736
7.5
9
from typing import Optional from optics_framework.common.base_factory import InstanceFallback from optics_framework.common.logging_config import internal_logger from optics_framework.common.optics_builder import OpticsBuilder class AppManagement: """ A high-level API for managing applications. This class...
mozarkai/optics-framework
optics_framework/api/app_management.py
.py
039b4553662018cb
7.52
10
from typing import Optional, Any, List from optics_framework.common.error import OpticsError, Code from optics_framework.common.logging_config import internal_logger from optics_framework.common import utils from optics_framework.common.base_factory import InstanceFallback from optics_framework.common.optics_builder i...
mozarkai/optics-framework
optics_framework/api/verifier.py
.py
95c742342cac118b
7.52
10
from optics_framework.common.events import EventSubscriber, Event, EventStatus, get_event_manager import json import xml.etree.ElementTree as ET #nosec B405 from pathlib import Path from typing import List, Dict, Optional import xml.dom.minidom #nosec B408 import time import logging import threading from optics_framew...
mozarkai/optics-framework
optics_framework/common/Junit_eventhandler.py
.py
99ba79815de8c366
7.52
10
import asyncio import threading from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError from typing import Any, Coroutine from optics_framework.common.logging_config import internal_logger from optics_framework.common.error import OpticsError, Code _persistent_loop: asyncio.AbstractEventL...
mozarkai/optics-framework
optics_framework/common/async_utils.py
.py
d0e0afeef6e9eebe
7.52
10
from typing import Type, Dict, Optional, TypeVar, Generic, Union, List, cast from types import ModuleType import importlib import pkgutil import inspect from pydantic import BaseModel, Field from optics_framework.common.logging_config import internal_logger from optics_framework.common.error import OpticsError, Code T...
mozarkai/optics-framework
optics_framework/common/base_factory.py
.py
131a72ec556fe751
7.52
10
import os from collections.abc import Mapping from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from optics_framework.common.error import OpticsError, Code from optics_framework.common.logging_config import initialize_handlers class DependencyConfig(BaseModel): """Configuration ...
mozarkai/optics-framework
optics_framework/common/config_handler.py
.py
ee7a6003594100ca
7.52
10
from abc import ABC, abstractmethod from typing import Any, Optional, List, Tuple import numpy class ElementSourceInterface(ABC): """ Abstract base class for element source drivers. This interface defines methods for capturing and interacting with screen elements (e.g., images, UI components) within a...
mozarkai/optics-framework
optics_framework/common/elementsource_interface.py
.py
e5a7d99663c24516
7.52
10
"""Structured error definitions and helpers for Optics Framework. This module provides: - ErrorSpec: static registry entries for known error codes. - OpticsError: an exception carrying structured metadata (category, code, http status, details). - helpers: from_code, raise_code and to_response to produce machine-readab...
mozarkai/optics-framework
optics_framework/common/error.py
.py
c1073d53eef53d31
7.52
10
"""Shared on-screen error-detection primitives. Used by both the CLI/TestRunner path (`_capture_end_of_run_artifacts`) and the library `Optics` class (`capture_and_detect`) so the matching logic lives in one place. """ import re import xml.etree.ElementTree as ET # nosec B405 from typing import Dict, List, Optional ...
mozarkai/optics-framework
optics_framework/common/error_detection.py
.py
b1b69e40c498ba40
7.52
10
import asyncio import logging import threading import time from enum import Enum from typing import Union, Optional, Dict, List, Any from abc import ABC, abstractmethod from pydantic import BaseModel, Field internal_logger = logging.getLogger("optics.internal") class EventStatus(str, Enum): """Possible statuses ...
mozarkai/optics-framework
optics_framework/common/events.py
.py
2a16599b06e02822
7.52
10
from typing import Optional from optics_framework.common.logging_config import execution_logger class ExecutionTracer: """ Helper for logging structured strategy attempts into execution_logger. """ @staticmethod def log_attempt(strategy, element: str, status...
mozarkai/optics-framework
optics_framework/common/execution_tracer.py
.py
fadfee1c86301758
7.52
10
from abc import ABC, abstractmethod from typing import Literal, Optional, Tuple, Any class ImageInterface(ABC): """ Abstract base class for image processing engines. This interface defines methods for detecting and locating images or objects within input data (e.g., images or video frames), implement...
mozarkai/optics-framework
optics_framework/common/image_interface.py
.py
6d64c45bc1446d77
7.52
10