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 the history index builder (scripts/build_history_index.py).
Loads the script as a module and monkeypatches its git-shelling functions
(feed_commits/feed_at_commit) with synthetic data, so the sqlite-writing
logic can be exercised without a real git history.
"""
from __future__ import annotations
import i... | PKHarsimran/SwiftIOC-Automated-Threat-Intelligence-Collector | tests/test_build_history_index.py | .py | 78ab6473cff567b0 | 8.07 | 13 |
"""End-to-end tests for swiftioc.cli.main() — the function GitHub Actions
actually invokes every 4 hours.
Every other test in this suite calls individual parsers/writers directly;
none of them exercise argument parsing, diagnostics-path derivation, the
persist-feed/expiry/retention pipeline wiring, or the diagnostics ... | PKHarsimran/SwiftIOC-Automated-Threat-Intelligence-Collector | tests/test_cli.py | .py | 74b82930498d324c | 8.07 | 13 |
"""Tests for the IOC time-machine query tool (scripts/ioc_timeline.py).
Builds a small SQLite index matching the schema build_history_index.py emits,
then exercises the pure query/render logic — no git required.
"""
from __future__ import annotations
import importlib.util
import json
import sqlite3
from datetime impo... | PKHarsimran/SwiftIOC-Automated-Threat-Intelligence-Collector | tests/test_ioc_timeline.py | .py | c1c69f0bc739fb8d | 8.07 | 13 |
import re
class Asset:
"""
Represents a file from the host system that should be copied into the
generated Nix configuration.
"""
def __init__(self, source_path: str, target_filename: str):
self.source_path = source_path
# substitute illegal characters in the /nix/store to -
... | Levizor/nix-scribe | src/nix_scribe/lib/asset.py | .py | a479875de456ef22 | 7.42 | 6 |
from __future__ import annotations
import logging
from pathlib import Path
from nix_scribe.lib.asset import Asset
from nix_scribe.lib.context import SystemContext
from nix_scribe.lib.modularization import ModularizationLevel
from nix_scribe.lib.nix_writer import NixWriter, raw
from nix_scribe.lib.option_block import ... | Levizor/nix-scribe | src/nix_scribe/lib/nixfile.py | .py | 67ed5b6c3e4abdcd | 7.42 | 6 |
from dataclasses import dataclass
from typing import Any
from .asset import Asset
from .nix_writer import raw
def combined_comments(*args: str | None) -> str | None:
"""Combines multiple comments, ignoring Nones and removing duplicates."""
valid_comments = [c for c in args if c]
if not valid_comments:
... | Levizor/nix-scribe | src/nix_scribe/lib/option_block.py | .py | 6bf4b747db7c4e26 | 7.42 | 6 |
import os
from types import FunctionType
from typing import Any
from deepmerge import always_merger
from nix_scribe.lib.context import SystemContext
def normalize_config(config: dict[str, Any]) -> dict[str, Any]:
"""
Traverses a dictionary and normalizes all string values.
"""
normalized = {}
fo... | Levizor/nix-scribe | src/nix_scribe/lib/parsers/parser.py | .py | 13bb592e122f58fe | 7.42 | 6 |
from typing import Any, Callable
from nix_scribe.lib.context import SystemContext
from nix_scribe.lib.option_block import ConfigFragment
_MODULES_REGISTRY: dict[str, "Module"] = {}
ScannerFunc = Callable[[SystemContext], dict[str, Any]]
MapperFunc = Callable[[dict[str, Any]], ConfigFragment | None]
class Module:
... | Levizor/nix-scribe | src/nix_scribe/lib/registry.py | .py | 4606f5f69118060f | 7.42 | 6 |
import logging
from pathlib import Path
from rich.console import Console
from rich.logging import RichHandler
class RichColorFormatter(logging.Formatter):
"""
Wraps log messages in Rich color tags based on the log level.
"""
def format(self, record):
msg = super().format(record)
if r... | Levizor/nix-scribe | src/nix_scribe/logger.py | .py | b57a44bfec4983ec | 7.42 | 6 |
import ezc3d
import numpy as np
import opensim as osim
from abc import ABC
class DataSource(ABC):
"""
Abstract base class for time-series data sources.
Subclasses parse a source file (e.g., a TRC or C3D file) and expose the data as
OpenSim TimeSeriesTables of positions and/or orientations. Tables can... | opensim-org/opensim-fitter | src/osimfit/data_sources.py | .py | 1cf60683cd71970f | 7.42 | 6 |
import numpy as np
import casadi as ca
import opensim as osim
import matplotlib.pyplot as plt
# Load the IK solution and extract the first column.
table = osim.TimeSeriesTable('jump_1_ik_solution.sto')
times = table.getIndependentColumn()
col1 = table.getDependentColumnAtIndex(0).to_numpy()
col2 = table.getDependentCo... | opensim-org/opensim-fitter | src/sandbox/sandbox.py | .py | 00e709c7e3b04284 | 7.42 | 6 |
"""
Unit and end-to-end tests for marker and frame offset optimization in
SplinedKinematicsSolver.
"""
import pytest
import numpy as np
import opensim as osim
from osimfit.data_sources import MarkerSource
from osimfit.solvers import SplinedKinematicsSolver, SplinedKinematicsSolution
from osimfit.model import MarkerOf... | opensim-org/opensim-fitter | tests/test_offsets.py | .py | 7a4b8c5141b5ba6f | 7.92 | 6 |
#!/usr/bin/env python3
"""Assert a Decision-gate choice-A run landed in the decide-complete state.
Locks PR #185's terminal semantics (current_phase complete + run_mode decide +
generate pending) and the decision-pack artifacts (decision-report.html passes
the validator in --mode decision; DECISION.md exists; no Gener... | awslabs/startups | advisor/plugins/aws-startup-advisor/fixtures/gcp-decision-gate/check_expected_decide.py | .py | 8563ee387cbabd59 | 7.62 | 16 |
#!/usr/bin/env python3
"""Assert a Discover run's output against expected-drift.json (scenario B).
Usage:
python3 check_expected_drift.py <migration_run_dir>
Where <migration_run_dir> contains gcp-resource-inventory.json and
gcp-resource-clusters.json produced by a replay of this fixture's scenario B
(live-captur... | awslabs/startups | advisor/plugins/aws-startup-advisor/fixtures/gcp-live-capture/check_expected_drift.py | .py | 0d23c101e47b8313 | 7.62 | 16 |
#!/usr/bin/env python3
"""Assert a Discover run's output against expected-drift.json (scenario B).
Usage:
python3 check_expected_drift.py <migration_run_dir>
Where <migration_run_dir> contains the heroku-resource-inventory.json produced
by a replay of this fixture's scenario B (live-capture/ + workspace-terraform... | awslabs/startups | advisor/plugins/aws-startup-advisor/fixtures/heroku-live-capture/check_expected_drift.py | .py | e0046de230677dd2 | 7.62 | 16 |
#!/usr/bin/env python3
"""Assert an Estimate run's output against expected-estimate.json (scenario C).
Usage:
python3 check_expected_estimate.py <migration_run_dir>
Where <migration_run_dir> contains the estimation-infra.json produced by a
replay seeded from seed-estimate/ (live-discovered inventory, NO billing d... | awslabs/startups | advisor/plugins/aws-startup-advisor/fixtures/heroku-live-capture/check_expected_estimate.py | .py | fb0e8633aaf131a2 | 7.62 | 16 |
#!/usr/bin/env python3
"""Validate startup-program artifacts match preferences.json startup_program_status.
Prevents inferring AWS Activate Founders vs Portfolio when Q27 was skipped or
startup_program_status is unknown.
Usage:
python3 validate-startup-program-artifacts.py --migration-dir /path/to/.migration/RUN_ID... | awslabs/startups | advisor/plugins/aws-startup-advisor/scripts/validate-startup-program-artifacts.py | .py | 2bca2a66c042b864 | 7.62 | 16 |
"""Bedrock model/path recommendation orchestrator for agent-advisor.
Validates the shared input contract, dispatches each workload to its provider
module (anthropic_model_recommendation / openai_model_recommendation; anything
else falls through to the provisional generic path), aggregates per-workload
results with per... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/agent-advisor/scripts/model_recommendation.py | .py | 75a46ae2ab2b56e8 | 7.62 | 16 |
#!/usr/bin/env python3
"""Score every agent_session unit in answers.json and print scoring-result JSON.
Thin driver over scoring.py (which stays a pure function): loops units, merges
system + unit answers, loads run-materialized verification evidence, and mirrors
the primary unit's result at the top level so single-un... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/agent-advisor/scripts/score_units.py | .py | 0fb8d6f9c78b5d92 | 7.62 | 16 |
# scripts/test_collapse_invariant.py
"""Stage-A release gate: a single-unit run is byte-equivalent to the legacy flow
on every Python surface (scoring call, diagram render). Prose surfaces carry the
same invariant via phase _asserts (single-unit: no grouping question, no delta
questions, no unit cards)."""
import build... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/agent-advisor/scripts/test_collapse_invariant.py | .py | 785ae029a4a0480c | 8.12 | 16 |
"""Content lock for references/decision-refs/cost-levers.md.
Cost-optimization levers are the ONLY legal source for discount/lever citations in
agent-advisor estimates and reports. These tests pin the five canonical levers and
verify that estimate.md references cost-levers.md and mentions the drivers[] field.
"""
impo... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/agent-advisor/scripts/test_cost_levers.py | .py | 684d79c52d98bf0e | 8.12 | 16 |
"""Content lock for references/decision-refs/poc-shapes.md.
The POC shapes are markdown-specified deploy contracts. These tests pin the
security- and cost-load-bearing content (create whitelists, auth modes,
fallback rules, the Temporal TLS contract) so a wording "simplification"
cannot silently turn a locked-down POC... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/agent-advisor/scripts/test_poc_shapes.py | .py | c84fc61ece67fff5 | 8.12 | 16 |
"""Content lock for references/decision-refs/temporal.md.
The temporal rules are consumed by the main flow. These tests pin the
load-bearing content (eliminations, rule order, precondition wording, status
labels) so an edit that weakens them fails loudly, in the same spirit as the
model-pool drift tests in test_scorin... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/agent-advisor/scripts/test_temporal_decision_refs.py | .py | 366204881b43d043 | 8.12 | 16 |
"""Content lock for the unit-inventory grouping rules in the Discover phase.
The grouping judgment (in-process agents merge; cross-process split) is prose,
so these tests pin the load-bearing sentences the same way the temporal locks do.
"""
import json
import pathlib
import re
DISCOVER_MD = (pathlib.Path(__file__).p... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/agent-advisor/scripts/test_unit_grouping.py | .py | 419b84d94cbedc90 | 7.12 | 16 |
"""Content lock for references/decision-refs/workload-classes.md.
Non-agent workload units are NOT scored by scoring.py — their verdicts come
from this deterministic table. These tests pin the rule order (first-match-wins)
and the load-bearing verdicts, in the same spirit as test_temporal_decision_refs.
"""
import pat... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/agent-advisor/scripts/test_workload_classes.py | .py | 344d797f053e45e9 | 8.12 | 16 |
# bedrock_pricing.py
"""Look up Amazon Bedrock on-demand token prices.
Primary source is the curated STATIC_FALLBACK table below (checked against the
public pricing page). The live AWS Pricing API is tried as a secondary source
for models not in the table — note its 'model' attribute holds display names
("Claude 3 Hai... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/bedrock_pricing.py | .py | 897e36a7cd3c5175 | 7.62 | 16 |
"""Generate a least-privilege IAM policy for Bedrock model invocation.
Pure module: takes model IDs, region, and account ID — returns a policy dict.
Handles the dual-ARN pattern (foundation-model + inference-profile) required
when cross-region inference profile IDs (us./eu./apac. prefixed) are in use.
"""
import json
... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/iam_policy.py | .py | 87b66a1a70d48de1 | 7.62 | 16 |
# render_report.py
"""Summarize a completed Execute run (C7) for in-chat display.
Two input modes (mutually exclusive, exactly one required):
render_report.py --phase-results <dir> --repo <repo> [--date-suffix YYYY-MM-DD]
Reads rewrite.json + eval.json (+ delta-decisions.json) from the
phase-results dir... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/render_report.py | .py | d2f775fa17c2a977 | 7.62 | 16 |
#!/usr/bin/env python3
"""Resolve a plan-stated source model ID against the live provider catalog.
Usage:
PLAN_MODEL_ID=<id> python resolve_source_model.py <path/to/.source-provider-env>
Prints one JSON object on stdout:
{"status": "exact"|"prefix", "resolved_id": ..., "all_hits": [...]}
{"status": "not_found",... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/resolve_source_model.py | .py | 906462812a676a77 | 7.62 | 16 |
#!/usr/bin/env python3
"""Re-run each golden prompt against the customer's live source model.
Usage:
SOURCE_MODEL_ID=<id> GOLDEN_DATASET_PATH=<jsonl> OUTPUT_PATH=<jsonl> \\
python source_baseline.py <path/to/.source-provider-env>
Writes one JSON record per prompt to OUTPUT_PATH:
{"id": ..., "source_response":... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/source_baseline.py | .py | ca47abd2c77bb9e2 | 7.62 | 16 |
# test_bedrock_pricing.py
import bedrock_pricing as bp
def test_parse_price_dimensions_extracts_per_1k_token_rates():
# Pure parser over a Pricing API PriceList JSON fragment.
fragment = {
"terms": {"OnDemand": {"x": {"priceDimensions": {
"d1": {"unit": "1K tokens", "pricePerUnit": {"USD": ... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/test_bedrock_pricing.py | .py | 9575bfcf353ef825 | 8.12 | 16 |
# test_preflight_bedrock.py
import preflight_bedrock as p
def test_classify_access_denied_maps_to_authz_failure():
# The pure classifier turns a botocore error code into a structured verdict.
v = p.classify_invoke_error("AccessDeniedException", "not authorized to perform bedrock:InvokeModel")
assert v["ok... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/test_preflight_bedrock.py | .py | 86ed18689a09f9d2 | 7.12 | 16 |
"""Content lock for the model-line-sacred resolution rules.
The hard rule: auto-resolution may only pin the SAME model line to a date or
pure version suffix. Cross-line swaps and moving aliases escalate to the user.
"""
import json
import pathlib
import subprocess # nosec B404 — test-only, fixed args
import sys
impor... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/test_resolve_source_model.py | .py | d56a9306f3b4cc9c | 8.12 | 16 |
"""Locks for the baseline runner's request shapes and key hygiene.
The request builders are pure (no network), so the provider API shapes and the
never-key-in-URL rule are pinned here without mocking urllib.
"""
import os
import pathlib
import source_baseline as sb
def _with_keys(**keys):
for k in ("OPENAI_API_... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/llm-to-bedrock/scripts/test_source_baseline.py | .py | 698980ae037d9ac9 | 8.12 | 16 |
"""Tests for validate-terraform-policy.py (tf-best-practices, read-only verdict)."""
from __future__ import annotations
import importlib.util
import json
import subprocess # nosec B404 — test-only, inputs are hardcoded literals
import sys
import tempfile
from pathlib import Path
PLUGIN_SKILL_ROOT = Path(__file__).r... | awslabs/startups | advisor/plugins/aws-startup-advisor/skills/tf-best-practices/scripts/test_validate_terraform_policy.py | .py | a5ab0b0121754d90 | 7.12 | 16 |
"""Проверка окружения: что нужно конвейеру и чего не хватает.
Ставить пакеты сами не берёмся: системный пакет требует прав, а команда,
запускающая от чужого имени `sudo` без спросу, — это то, чего в чужой
машине быть не должно. Поэтому говорим ровно и коротко: чего нет, зачем оно
и какой строкой ставится **на этой** с... | sukamenev/booktrans | src/booktrans/doctor.py | .py | ca5f10c6567228e7 | 7.66 | 20 |
#!/usr/bin/env python3
"""Проверка подстановки переводов в листинги — без обращения к модели.
Комментарии в листингах ищет модель: знаков комментария у языков сотни.
Подставляет перевод программа, и вот её-то ошибка тиха и дорога — в книгу
попадёт сломанный код. Поэтому здесь записано, что подставиться обязано, а
что ... | sukamenev/booktrans | tests/code_check.py | .py | 817610d73f83df71 | 7.16 | 20 |
#!/usr/bin/env python3
"""Проверка, что обложка доходит до сборщика — во всех форматах.
Место под обложку есть у каждого сборщика, а раздаёт её `build_book`, и
раздавал по списку форматов, перечисленных руками. `.fb2` и `.tex` в список
не попали: книга выходила без обложки, и увидеть это можно было только
открыв её. П... | sukamenev/booktrans | tests/cover_check.py | .py | 1589be5171707b80 | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка склейки абзацев, разорванных концом страницы.
Из pdf абзац приходит разрезанным пополам: конец страницы обрывает его на
переносе («слу-» / «шал») или просто посреди фразы («подцепил компас» /
«стрелку»). Метка `+` для этого и есть, но модель ставит её не всегда, и
переводчик получает... | sukamenev/booktrans | tests/glue_check.py | .py | 38970d79991913a9 | 7.16 | 20 |
#!/usr/bin/env python3
"""Проверка чтения отдельного html.
Epub — это zip из xhtml, и разбор документа у них общий. Разница в том, что
отдельный html пишут люди и редакторы: теги не закрыты, атрибуты без кавычек,
`<br>` без слэша. Строгий разбор на таком падает, а книга читается прекрасно.
Картинки — второе отличие: ... | sukamenev/booktrans | tests/html_check.py | .py | dffe496137374af7 | 8.16 | 20 |
#!/usr/bin/env python3
"""Имя, заведённое дважды, — обычно не замысел, а недосмотр.
Два случая, и оба стоили выпуска. Ввоз внутри функции: питон решает, что имя
местное, по всей функции сразу, а не с той строки, где стоит `import`, — и
`from . import extract` в одной ветке делает `extract` местным везде, так что
обращ... | sukamenev/booktrans | tests/imports_check.py | .py | 3d91c4face000b22 | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка языковых папок: одна книга — несколько языков.
Разбор оригинала, разметка и картинки языка не имеют и стоят дороже всего
после самого перевода, поэтому лежат общими. А перевод, редактура, сноски,
справочник и конспект у каждого языка свои и лежат в папке языка: `ru/tr` и `de/tr`.
От... | sukamenev/booktrans | tests/langdirs_check.py | .py | cd918d3c06765ea4 | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка ссылок внутри книги.
Страницу сохраняют целиком, и перекрёстные ссылки в ней записаны полным
адресом: «https://сайт/статья.html#Intro» вместо «#Intro». Разбор видел `http`
и считал такую ссылку внешней — в переведённой книге она уводила читателя на
подлинник, да ещё и в оглавлении, г... | sukamenev/booktrans | tests/link_check.py | .py | 45e6eba8772fc8a2 | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка разметки книг без разметки: цепочка моделей и продолжение.
Два случая, оба стоили целого прогона на толстой книге. Отказ модели разметку
переживала — она приходит пустым ответом, — а сбой поставщика (502) летел
наружу мимо запасной модели. И до конца прохода ничего не сохранялось: па... | sukamenev/booktrans | tests/marks_check.py | .py | 6dcd62c1a7f1a4ef | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка вывода в markdown.
Markdown берут ради текста, который правят руками и кладут в git, поэтому
здесь важно обратное обычному: не потерять разметку книги и не наделать её
там, где в книге просто текст. Абзац, начатый с решётки или дефиса, читается
как заголовок или список; звёздочка пос... | sukamenev/booktrans | tests/md_check.py | .py | 35774367f6f79a82 | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка разбора чисел в разделе «ЧИСЛА».
Проверка сверяет цифры оригинала с цифрами перевода, и два класса из неё
вычтены: подмена буквы цифрой в распознанном тексте и число, слипшееся
дефисом со словом. Оба вычитания опасны в одну сторону — вычтем лишнее, и
настоящая пропажа цифры пройдёт м... | sukamenev/booktrans | tests/numbers_check.py | .py | 8a76d9cc6ae3cb7b | 7.16 | 20 |
#!/usr/bin/env python3
"""Проверка отбора поправок распознавания — без обращения к модели.
Корректор правит оригинал, и ошибка тут дороже прочих: испорченное место
видно, а подменённое нет. Поэтому здесь записано, что принимается, а что
обязано быть отвергнуто.
python3 tests/fix_check.py
"""
import os
import sys
... | sukamenev/booktrans | tests/ocrfix_check.py | .py | 51b27c432c219311 | 7.16 | 20 |
#!/usr/bin/env python3
"""Проверка снятия колонтитулов и номеров страниц — без обращения к модели.
Правило удаляет строки из книги, и ошибка в нём тиха: пропавший абзац
заметят не сразу. Поэтому здесь записано и то, что обязано сниматься, и то,
что трогать нельзя.
Названия книги правило не знает и не спрашивает: коло... | sukamenev/booktrans | tests/pages_check.py | .py | f7dcff5f6c230fe5 | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка профилей: файла с ключами командной строки.
Профиль нужен затем, что строка запуска не помещается в экран: четыре роли,
у каждой цепочка из двух-трёх моделей. Своего синтаксиса у файла нет — те же
ключи, что в строке, — и вставляются они в саму строку, поэтому любой ключ
работает сра... | sukamenev/booktrans | tests/profile_check.py | .py | 70af7da557f54e2a | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка выжимки справочника для куска.
Таблицы имён и терминов — большая часть справочника, а куску нужны из них
считаные строки. В систему уходит костяк без таблиц, к куску приезжают
строки, чьи ключи встречаются в его тексте. Здесь проверяется делёж и отбор:
потерянная строка — разнобой в ... | sukamenev/booktrans | tests/refrows_check.py | .py | 5ce87b6830752ba9 | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка вывода в LaTeX.
Главное здесь — экранирование. У TeX десяток особых знаков, и один из них,
`%`, молча съедает остаток строки: файл соберётся, а текста в нём не будет.
Это ровно та порода ошибки, которую не видно, пока не сверишь с оригиналом.
python3 tests/tex_check.py
"""
impor... | sukamenev/booktrans | tests/tex_check.py | .py | 6e272052c0cf17d3 | 8.16 | 20 |
#!/usr/bin/env python3
"""Проверка записи версии конвейера в рабочую папку.
Папки переживают архивы: перевод сделан одной версией, пересборка другой.
По versions.json спустя год видно, какими версиями что делалось и какие
миграции внутренних форматов нужны.
python3 tests/version_check.py
"""
import json
import os... | sukamenev/booktrans | tests/version_check.py | .py | 9ae8aaaf1f6e6fff | 8.16 | 20 |
import hashlib
from pathlib import Path
from typing import Any
import yaml
from aicage.paths import PROJECTS_DIR
from ._yaml_loader import load_yaml
from .project_config import _ProjectConfig
class _IndentedSafeDumper(yaml.SafeDumper):
def increase_indent(self, flow: bool = False, indentless: bool = False) -> ... | aicage/aicage | src/aicage/config/config_store.py | .py | 7a940c78e2d47148 | 7.45 | 7 |
from enum import Enum
from typing import Optional
import polars as pl
__all__ = (
"ArrayFunctionType",
"BinaryFunctionType",
"BitwiseFunctionType",
"BooleanFunctionType",
"DataType",
"Expr",
"FunctionType", # Include the base class
"ListFunctionType",
"OperatorType",
"StringFu... | Point72/polars-io-tools | polars_io_tools/io_sources/enum.py | .py | 1130a07ea98204de | 7.65 | 19 |
import io
import logging
import polars as pl
import pyarrow as pa
import requests
from .._compat import POLARS_HAS_COLLECT_BATCHES
__all__ = ("sink_clickhouse",)
# Configure logging
log = logging.getLogger(__name__)
def _write_arrow_to_clickhouse(table: str, arrow_table: pa.Table, url: str, params: dict) -> None... | Point72/polars-io-tools | polars_io_tools/io_sources/lazy_clickhouse_writer.py | .py | 1aa7f5920b06c49b | 7.65 | 19 |
import datetime
import warnings
from collections.abc import Iterator
import polars as pl
import portion
from .range_visitor import convert_expr_to_datetime_range
from .util import _convert_interval_to_slices, register_io_source_with_is_pure
__all__ = ("metric_query", "scan_datadog")
def metric_query(query: str, st... | Point72/polars-io-tools | polars_io_tools/io_sources/lazy_datadog_reader.py | .py | 2f4a80e910f5f1ce | 7.65 | 19 |
import logging
from collections.abc import Iterator
import polars as pl
from .util import collect_lf_in_io_source, register_io_source_with_is_pure
log = logging.getLogger(__name__)
__all__ = ("debug",)
def debug(
self: pl.LazyFrame,
log_level: int | None = None,
) -> pl.LazyFrame:
"""
A very simp... | Point72/polars-io-tools | polars_io_tools/io_sources/lazy_debug.py | .py | c3205471d8b0c599 | 7.65 | 19 |
from __future__ import annotations
import logging
from collections.abc import Iterator
from typing import TYPE_CHECKING, Any, cast, overload
import narwhals as nw
import polars as pl
from narwhals.typing import FrameT
if TYPE_CHECKING:
import pyarrow as pa
from .base import AliasNode, BaseExprNode, BinaryExprNo... | Point72/polars-io-tools | polars_io_tools/io_sources/lazy_narwhals_reader.py | .py | c59a0a667d8128b4 | 7.65 | 19 |
import io
from collections.abc import Iterator
from datetime import datetime, timedelta
from typing import Literal
import cloudpickle
import polars as pl
import portion
from tqdm import tqdm
from .range_visitor import convert_expr_to_datetime_range
from .util import _extend_interval
try:
import ray
except Import... | Point72/polars-io-tools | polars_io_tools/io_sources/lazy_ray.py | .py | 7ea46ceb29b7fe64 | 7.65 | 19 |
import logging
from functools import lru_cache
from typing import Any
import polars as pl
from sqlglot import exp, parse_one
from sqlglot.dialects.dialect import Dialect
from .sql_dialects import MSSQL
from .sql_utils import (
apply_polars_io_source_exprs,
fix_three_part_identifiers,
)
from .util import regis... | Point72/polars-io-tools | polars_io_tools/io_sources/lazy_sql_reader.py | .py | e6a572efc4b2deb8 | 7.65 | 19 |
"""
``pushdown_pivot``: a pushdown-friendly wrapper around ``LazyFrame.pivot``.
Polars' lazy ``pivot`` (unstable as of 1.39) is implemented internally as a ``group_by`` followed by ``filter().item()``
aggregations — one per value in ``on_columns``. As a result, predicate and projection pushdown behave like they would ... | Point72/polars-io-tools | polars_io_tools/io_sources/pushdown_pivot.py | .py | 5f745b0f15eff53d | 7.65 | 19 |
"""
``pushdown_unpivot``: a pushdown-friendly wrapper around ``LazyFrame.unpivot``.
Polars' built-in ``unpivot`` blocks several optimization opportunities. In particular:
* A filter on the ``variable`` column (e.g. ``col("variable") == "A"`` or ``col("variable").is_in(["A", "B"])``) can be
rewritten as an upstream ... | Point72/polars-io-tools | polars_io_tools/io_sources/pushdown_unpivot.py | .py | 3f734aec3a2729c6 | 7.65 | 19 |
import logging
from collections.abc import Iterable, Set as AbstractSet
import polars as pl
from .base import (
BaseExprNode,
BinaryExprNode,
CastNode,
ExprVisitor,
FunctionNode,
TernaryNode,
get_parsed_expr,
)
from .enum import (
BooleanFunctionType,
OperatorType,
)
# Configure l... | Point72/polars-io-tools | polars_io_tools/io_sources/restrict_visitor.py | .py | b8a6abcbaef80866 | 7.65 | 19 |
import logging
from typing import Any
import polars as pl
from .base import AliasNode, BaseExprNode, BinaryExprNode, CastNode, ExprVisitor, FunctionNode, extract_column_name, get_parsed_expr
from .enum import BooleanFunctionType, OperatorType
# Configure logging
log = logging.getLogger(__name__)
__all__ = ("convert... | Point72/polars-io-tools | polars_io_tools/io_sources/set_visitor.py | .py | 0cb7653c297d6a4a | 7.65 | 19 |
from __future__ import annotations
import logging
from typing import Literal
import orjson
import polars as pl
from pydantic import BaseModel
from polars_io_tools.io_sources.base import (
BaseExprNode,
BinaryExprNode,
CastNode,
ExprVisitor,
FunctionNode,
LiteralNode,
extract_column_name,
... | Point72/polars-io-tools | polars_io_tools/io_sources/translated_source.py | .py | b43486d00139b6e4 | 7.65 | 19 |
import datetime
import logging
from collections.abc import Callable
import polars as pl
from .pushdown_combine import FilterSpec, pushdown_combine
__all__ = ("ts_with_columns",)
log = logging.getLogger(__name__)
def ts_with_columns(
self: pl.LazyFrame,
*exprs: pl.Expr | list[pl.Expr] | Callable[[pl.LazyF... | Point72/polars-io-tools | polars_io_tools/io_sources/ts.py | .py | 7b5d213ac6155969 | 7.65 | 19 |
"""
Predicate tracking and analysis utilities for testing filter pushdown.
This module provides tools for:
1. Creating IO sources that track pushed-down predicates
2. Analyzing the structure of pushed predicates
3. Extracting filter bounds and values from predicate trees
4. Asserting that predicates are pushed down co... | Point72/polars-io-tools | polars_io_tools/testing/predicate_tracker.py | .py | 7d735c4db92df66e | 7.15 | 19 |
import datetime
import polars as pl
import polars_io_tools as cpl
from polars_io_tools.io_sources.util import _storage_options_for
def exercise_daily_cache_parquet(
cache_root: str,
aws_profile: str | None = None,
partition_format: str | None = "theYear=$year/theMonth=$month/theDay=$day",
) -> tuple[pl.... | Point72/polars-io-tools | polars_io_tools/tests/helpers/cache_parquet_shared.py | .py | 947d97a63f664578 | 7.15 | 19 |
from pathlib import Path
import pyarrow.fs as pa_fs
import pytest
from polars_io_tools.io_sources.util import _storage_options_for
def pytest_addoption(parser):
parser.addoption(
"--aws-profile",
action="store",
default=None,
help="AWS profile to use for S3 integration tests",
... | Point72/polars-io-tools | polars_io_tools/tests/integration/conftest.py | .py | 289ea81dcbb5a525 | 8.15 | 19 |
"""
Integration tests for the lazy Polars ClickHouse reader.
This module contains integration tests that require an actual ClickHouse connection.
These tests verify that scan_clickhouse works correctly against real databases.
Prerequisites:
- Access to coconut_db_sm15896.quote_bar_10m and coconut_db_sm15896.trade_bar... | Point72/polars-io-tools | polars_io_tools/tests/integration/test_clickhouse_reader.py | .py | 2d74e61099ded833 | 7.15 | 19 |
"""
Integration tests for the lazy Polars ClickHouse writer (sink_clickhouse).
This module contains integration tests that require an actual ClickHouse connection.
These tests verify that sink_clickhouse works correctly against real databases,
including roundtrip tests that write data and read it back with scan_clickh... | Point72/polars-io-tools | polars_io_tools/tests/integration/test_clickhouse_writer.py | .py | c09a9d29d1f25cf8 | 8.15 | 19 |
"""
Integration test for cache_parquet using S3.
Requires passing --aws-profile and optionally --bucket via pytest CLI.
Bucket defaults to "polars-io-tools-tests". Root path derives from file name.
"""
import datetime
import pytest
import polars_io_tools as cpl # noqa
from polars_io_tools.tests.helpers.cache_parqu... | Point72/polars-io-tools | polars_io_tools/tests/integration/test_s3_cache_parquet.py | .py | 42b3979a834691ce | 7.15 | 19 |
"""
Integration test for Delta IO on S3.
Requires passing --aws-profile and optionally --bucket via pytest CLI.
Bucket defaults to "polars-io-tools-tests". Root path derives from file name.
"""
import pytest
import polars_io_tools as cpl # noqa
from polars_io_tools.tests.io_sources.test_delta_io import _run_delta_i... | Point72/polars-io-tools | polars_io_tools/tests/integration/test_s3_delta_io.py | .py | 63a4783f8ed42eb5 | 8.15 | 19 |
# These type hints match the ones in polars_io_tools.io_sources.dnf_visitor
# but they are not imported here to fully separate the polars_utils code
# from the general utils tests.
import os
from datetime import date, datetime, timedelta
from typing import Any
import numpy as np
import polars as pl
import pytest
# Im... | Point72/polars-io-tools | polars_io_tools/tests/io_sources/conftest.py | .py | 9dc9886e33b28698 | 8.15 | 19 |
import datetime
import polars as pl
import pytest
from polars.testing import assert_frame_equal
import polars_io_tools as cpl
from .conftest import io_source_assert
def test_concat_named_basic():
"""Test basic functionality of concat_named."""
df1 = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df2 = ... | Point72/polars-io-tools | polars_io_tools/tests/io_sources/test_concat_named.py | .py | bffe29feff7fa2b4 | 7.15 | 19 |
import base64
import os
from datetime import datetime, timedelta
import polars as pl
import pytest
from polars.testing import assert_frame_equal
import polars_io_tools as cpl
from polars_io_tools._compat import POLARS_HAS_COLLECT_BATCHES
from polars_io_tools.io_sources.delta_io import (
_MAPPING_BLOCK_TAG,
_g... | Point72/polars-io-tools | polars_io_tools/tests/io_sources/test_delta_io.py | .py | 762666ff0b194f2a | 7.15 | 19 |
"""Example of how to read HDF5 files generated by the streaming sampler.
The streaming sampler saves results in an HDF5 file with a group-based structure
to accommodate proteins of different lengths.
"""
import h5py
import numpy as np
def read_streaming_results(h5_path: str) -> dict[int, dict[str, np.ndarray]]:
"... | maraxen/aminx | examples/read_h5_streaming.py | .py | c12933cd8324e0a0 | 7.48 | 8 |
"""Tests for tied-position sampling in PrxteinLigandMPNN."""
import jax
import jax.numpy as jnp
import equinox as eqx
from aminx.model.mpnn import PrxteinLigandMPNN
def test_ligand_tied_sampling():
key = jax.random.PRNGKey(0)
model = PrxteinLigandMPNN(
node_features=16,
edge_features=16,
hidden_featur... | maraxen/aminx | scripts/260410/verify_ligand_tied_multistate.py | .py | ad1551ad3bdaade7 | 7.48 | 8 |
"""Tests for weighted multi-state logit combination."""
import jax
import jax.numpy as jnp
import pytest
from aminx.model.multistate_sampling import (
arithmetic_mean_logits,
geometric_mean_logits,
product_of_probabilities_logits,
)
def test_weighted_arithmetic_mean():
logits = jnp.array([
[10.0, 0.0], #... | maraxen/aminx | scripts/260410/verify_weighted_multistate.py | .py | a334f29521dafcfb | 7.48 | 8 |
"""Emit the aminx control-knob matrix: spec field x entry point x hop.
Produced for task_id 260715_aminx-campaign-control-knob-audit.
Every cell is derived by introspecting the *installed* aminx (dataclass fields, Typer
command params) or by AST-parsing aminx source -- never by reading prose or trusting a
summary. Th... | maraxen/aminx | scripts/audit/knob_matrix.py | .py | 58909b7db1ff38fb | 7.48 | 8 |
#!/usr/bin/env python3
"""Performance parity benchmark for InferencePlan decode dispatch.
MR-11: Verifies that InferencePlan.decode() overhead remains small by comparing
it against a minimal baseline that calls the same underlying decode_fn.
This benchmark uses a REAL protein structure fixture to produce valid
Encode... | maraxen/aminx | scripts/benchmarks/bench_inference_plan_latency.py | .py | 242d84e60526a791 | 7.48 | 8 |
"""Automated Docker-wrapped provisioning for functional-account vault registration.
Installed by ``py10x-core`` as the ``xx-functional-account-init`` console script (see
``pyproject.toml``); also runnable directly as
``python -m core_10x.apps.functional_account_init``.
Runs ``xx-user-init --functional-account --outpu... | 10x-software/py10x | core_10x/apps/functional_account_init.py | .py | 249477c0a506b1c7 | 7.63 | 17 |
from core_10x.environment_variables import EnvVars
from core_10x.global_cache import cache
from core_10x.ts_store import TsStore
class BackboneStore:
"""
Backbone Store instance should exist for every build area. It may be run with or without authentication required.
If authentication is required, it must... | 10x-software/py10x | core_10x/attic/backbone/backbone_store.py | .py | a776817de4985f37 | 7.63 | 17 |
from __future__ import annotations
from typing import TYPE_CHECKING
from core_10x.attic.data_domain import GeneralDomain
from core_10x.py_class import PyClass
from core_10x.resource import TS_STORE
if TYPE_CHECKING:
from core_10x.resource import ResourceRequirements
class PackageManifest:
"""
To associ... | 10x-software/py10x | core_10x/attic/package_manifest.py | .py | d2ea4d500ca77694 | 7.63 | 17 |
import pytest
from infra_10x.duckdb_store import DuckDbStore
from core_10x.testlib.fixtures import stub_log_logger
from core_10x.ts_store import TsStore
class TestDuckDbStore(DuckDbStore, resource_name='TEST_DUCK_DB'):
s_supports_add_column_if_not_exists = False
def create_index(self, collection_name, name,... | 10x-software/py10x | core_10x/conftest.py | .py | 897d020ce3565fef | 7.13 | 17 |
"""In-memory-only ``keyring`` backend for unattended functional (service) accounts.
``core_10x.sec_keys.SecKeys`` reads/writes secrets through the ``keyring`` package, which on a
desktop resolves to an OS credential store (macOS Keychain, Windows Credential Manager, or a
Linux Secret Service session). A headless funct... | 10x-software/py10x | core_10x/functional_account_keyring.py | .py | 52252ae0c384f512 | 7.63 | 17 |
import sys
import ctypes
from pathlib import Path
import tccbox
import struct
import re
from core_10x.global_cache import cache
#== TCC — thin ctypes wrapper around libtcc (from tccbox)
class _InMemBinary:
"""Holds a TCC-compiled in-memory binary. Must stay alive as long as the code is called.
tcc_delete i... | 10x-software/py10x | core_10x/jit/tcc_compiler.py | .py | 5014b7c544fe00a1 | 7.63 | 17 |
from __future__ import annotations
import builtins
import ctypes
import inspect
import re
import subprocess
import sys
import sysconfig
import tempfile
import textwrap
from pathlib import Path
from types import ModuleType
import ast
import types, importlib.util
from typing import Callable
from core_10x.trait import T... | 10x-software/py10x | core_10x/jit/trait_getter_cython_compiler.py | .py | 3fb66952d06cdd6f | 7.63 | 17 |
"""
MediaPlanPy Examples - Create Workspace
This script demonstrates how to create workspace configurations using MediaPlanPy SDK v3.0.
Workspaces define where media plans are stored and how they are managed.
v3.0 Features Demonstrated:
- Workspace schema version 3.0
- WorkspaceManager.create() API
- Local filesystem... | planmatic/mediaplanpy | examples/examples_01_create_workspace.py | .py | be1f8fd04535be67 | 7.45 | 7 |
"""
Media Plan OSC - Python SDK for Media Plans.
A lightweight, open-source Python SDK for interacting with the open data
standard for media plans.
"""
# Central Version Definitions - Updated for v3.0
__version__ = '3.0.9' # SDK version
__schema_version__ = '3.0' # Current schema version supported
VERSI... | planmatic/mediaplanpy | src/mediaplanpy/__init__.py | .py | 54562420b8616e24 | 7.45 | 7 |
"""
Excel format handler for mediaplanpy - Updated for v2.0 Schema Support Only.
This module provides the ExcelFormatHandler class for serializing and
deserializing media plans to/from Excel format using v2.0 schema exclusively.
"""
import os
import logging
import tempfile
from typing import Dict, Any, BinaryIO, Text... | planmatic/mediaplanpy | src/mediaplanpy/excel/format_handler.py | .py | a3fea00f0780ce93 | 7.45 | 7 |
"""
Campaign model for mediaplanpy.
This module provides the Campaign model class representing a campaign
within a media plan, following the Media Plan Open Data Standard v2.0.
"""
from datetime import date
from decimal import Decimal
from typing import Any, Dict, List, Optional, Set, ClassVar, Union
from pydantic i... | planmatic/mediaplanpy | src/mediaplanpy/models/campaign.py | .py | 1243437a434be53e | 7.45 | 7 |
"""
Integration of MediaPlan models with Excel functionality.
This module provides an ExcelMixin class with standardized methods for exporting
media plans to Excel format and importing media plans from Excel files.
"""
import os
import logging
import tempfile
from typing import Dict, Any, Optional, List, TYPE_CHECKIN... | planmatic/mediaplanpy | src/mediaplanpy/models/mediaplan_excel.py | .py | 9e5011e931042d19 | 7.45 | 7 |
"""
Formula management methods for MediaPlan.
Provides methods to update formula definitions at the MediaPlan level
with automatic propagation to all lineitems.
"""
from decimal import Decimal
from typing import Dict, Optional, List, Literal
from mediaplanpy.models.metric_formula import MetricFormula
class FormulasM... | planmatic/mediaplanpy | src/mediaplanpy/models/mediaplan_formulas.py | .py | 304bfba13de5da18 | 7.45 | 7 |
"""
Metric Formula model for mediaplanpy schema v3.0.
This module provides the MetricFormula model representing a custom calculation
formula for a metric in a line item.
"""
from typing import Optional
from pydantic import Field, field_validator
from mediaplanpy.models.base import BaseModel
from mediaplanpy.exceptio... | planmatic/mediaplanpy | src/mediaplanpy/models/metric_formula.py | .py | 1e449e44044ff6dd | 7.45 | 7 |
"""
Target Audience model for mediaplanpy schema v3.0.
This module provides the TargetAudience model representing a target audience
segment for a campaign.
"""
from typing import Optional
from pydantic import Field, field_validator
from mediaplanpy.models.base import BaseModel
from mediaplanpy.exceptions import Vali... | planmatic/mediaplanpy | src/mediaplanpy/models/target_audience.py | .py | 6f9cfa2a32af9a8f | 7.45 | 7 |
"""
Target Location model for mediaplanpy schema v3.0.
This module provides the TargetLocation model representing a geographic
target location for a campaign.
"""
from typing import Optional, List
from pydantic import Field, field_validator
from mediaplanpy.models.base import BaseModel
from mediaplanpy.exceptions im... | planmatic/mediaplanpy | src/mediaplanpy/models/target_location.py | .py | 18b70fa02eea21d7 | 7.45 | 7 |
"""
Schema module for mediaplanpy.
This module provides utilities for working with media plan schemas,
including version tracking, validation, and migration. Updated for 2-digit versioning.
"""
import logging
from mediaplanpy.schema.manager import SchemaManager
from mediaplanpy.schema.registry import SchemaRegistry
... | planmatic/mediaplanpy | src/mediaplanpy/schema/__init__.py | .py | 0316e1d1ea4d7748 | 7.45 | 7 |
"""
Storage module for mediaplanpy.
This module provides functionality for reading and writing media plans
to various storage backends in different formats.
"""
import logging
from typing import Dict, Any, Optional, Type, Union
from mediaplanpy.exceptions import StorageError, MediaPlanNotFoundError
from mediaplanpy.... | planmatic/mediaplanpy | src/mediaplanpy/storage/__init__.py | .py | 7d599f17bd4fc18a | 7.45 | 7 |
"""Performance benchmarks for HYXI Cloud sensor lookups."""
# ruff: noqa: E402
# pylint: disable=wrong-import-position
import sys
from unittest.mock import MagicMock
# Mock Home Assistant before any imports
mock_ha = MagicMock()
sys.modules["homeassistant"] = mock_ha
sys.modules["homeassistant.components"] = mock_ha
... | Veldkornet/ha-hyxi-cloud | benchmarks/benchmark_sensor.py | .py | 4210ace6a6a209de | 7.57 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.