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 |
|---|---|---|---|---|---|---|
import json
import re
from datetime import datetime
from pathlib import Path
from typing import Set
import scrapy
from scrapy.http import Response
from nthu_scraper.utils.constants import DATA_FOLDER
from nthu_scraper.utils.file_utils import save_json
# --- 全域參數設定 ---
COMBINED_JSON_FILE = DATA_FOLDER / "newsletters.... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/spiders/nthu_newsletters.py | .py | 47269c051f717b65 | 7.3 | 3 |
"""File and JSON utility functions."""
import json
from pathlib import Path
from typing import Any, Dict, List, Optional
def load_json(file_path: Path) -> Optional[Any]:
"""
載入 JSON 檔案。
Args:
file_path: JSON 檔案路徑。
Returns:
若成功載入則返回 JSON 資料,否則返回 None。
"""
if not file_path.exi... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/utils/file_utils.py | .py | b3057a9e26c9d094 | 7.3 | 3 |
"""Utilities for configuring outgoing HTTP requests."""
from __future__ import annotations
import random
from functools import lru_cache
from typing import Dict
# A small pool of modern desktop and mobile browsers to mimic real usage.
_USER_AGENT_POOL = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/utils/request_utils.py | .py | afe8aca2cdea2e55 | 7.3 | 3 |
"""URL processing utility functions."""
from typing import Dict, List, Optional
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
# 新增:強制 https 的輔助方法
def force_https(url: str) -> str:
"""將 URL 的 scheme 強制為 https(簡單替換 http:// 與 // 開頭情況)"""
if not url:
return url
url = url.strip()
... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/utils/url_utils.py | .py | 64ceda09aad2d6b8 | 7.3 | 3 |
"""Detach a project's billing account when a budget threshold is crossed.
GCP budgets notify; they do not cap. The only hard stop Google offers is
removing the billing account from the project, which stops every billable
resource in it. This is that stop.
WHAT IT ACTS ON COMES FROM THE ENVIRONMENT, NEVER FROM THE MES... | mlorentedev/kubelab | infra/terraform/gcp-bootstrap/function/main.py | .py | 7be7feb81f3ee007 | 7 | 0 |
#!/usr/bin/env python3
"""AUTH-004 R1 / AC4 probe — are Gitea's two signup POSTs honoured or refused?
R1a established that an SSO login parks at `/user/link_account`, and reported that
Gitea renders both branches of that page even though `DISABLE_REGISTRATION = true`.
That report was wrong, and the way it was wrong is... | mlorentedev/kubelab | specs/AUTH-004-identity-and-machine-access/r1_signup_probe.py | .py | 5ecbf0cb70f39c81 | 7.5 | 0 |
#!/usr/bin/env python3
"""AUTH-004 R1a probe — does an SSO login by a non-admin Authelia user
create a Gitea account while Gitea's own registration is disabled?
The password is resolved IN-PROCESS from the SOPS-merged config
(`apps.testing.authelia_test_password`), the same source the e2e suite uses. It is
never place... | mlorentedev/kubelab | specs/AUTH-004-identity-and-machine-access/r1a_sso_probe.py | .py | 763191b9db48b6aa | 7.5 | 0 |
"""Root conftest — shared pytest configuration and fixtures."""
import functools
import shutil
import pytest
@functools.lru_cache(maxsize=1)
def sops_can_decrypt() -> bool:
"""Whether this machine can actually decrypt the SOPS secrets.
True on a workstation with the age key, false on a runner without it. M... | mlorentedev/kubelab | tests/conftest.py | .py | 029cec324412ed11 | 7.5 | 0 |
"""E2E: CrowdSec bouncer and health tests."""
from __future__ import annotations
import httpx
import pytest
from toolkit.features.health_check import ServiceHealthConfig
from .expectations import EXPECTATIONS
pytestmark = pytest.mark.e2e
class TestCrowdSecBouncer:
"""Verify CrowdSec bouncer is not blocking l... | mlorentedev/kubelab | tests/e2e/test_crowdsec.py | .py | 6ae3caabd01bcbc0 | 7.5 | 0 |
"""E2E: Custom error page validation — verifies errors service renders custom pages.
Error-pages middleware intercepts 408, 429, 500-503 (NOT 404 — see ADR decision).
404 is not intercepted to preserve API JSON responses.
The catch-all IngressRoute handles unknown hosts → errors service.
"""
from __future__ import an... | mlorentedev/kubelab | tests/e2e/test_error_pages.py | .py | 19ec8fa206c6b3b0 | 7.5 | 0 |
"""E2E: Health endpoint tests — parametrized over all registered services."""
from __future__ import annotations
import httpx
import pytest
from toolkit.features.health_check import ServiceHealthConfig
from .expectations import (
EXPECTATIONS,
OFFLINE_STATUS,
ServiceExpectation,
backend_reachable,
... | mlorentedev/kubelab | tests/e2e/test_health.py | .py | a8e3efacf1e9d790 | 7.5 | 0 |
"""E2E: Security header validation — parametrized over services with Traefik-managed headers."""
from __future__ import annotations
import httpx
import pytest
from toolkit.features.health_check import ServiceHealthConfig
from .expectations import EXPECTATIONS, on_demand_skip_reason
pytestmark = pytest.mark.e2e
# ... | mlorentedev/kubelab | tests/e2e/test_security_headers.py | .py | 1f7f20bd3ef410bd | 7.5 | 0 |
"""E2E: TLS certificate validity and routing checks — parametrized over all domains."""
from __future__ import annotations
import socket
import ssl
import warnings
import httpx
import pytest
from toolkit.features.health_check import ServiceHealthConfig
from .expectations import EXPECTATIONS
pytestmark = pytest.ma... | mlorentedev/kubelab | tests/e2e/test_tls_routing.py | .py | ca8fad6516a1f590 | 7.5 | 0 |
"""Infrastructure test conftest — shared fixtures for infra tests."""
from __future__ import annotations
import pytest
from .fixtures import VPS_NODE, NodeInfo, load_inventory, tailscale_connected
@pytest.fixture(scope="session")
def require_vpn() -> None:
"""Skip all infra tests if Tailscale is not connected.... | mlorentedev/kubelab | tests/infra/conftest.py | .py | f1b5bc3616919b49 | 7.5 | 0 |
"""Infrastructure test fixtures — SSH helpers, node discovery, connectivity checks."""
from __future__ import annotations
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
import yaml
_REPO_ROOT = Path(__file__).resolve().parents[2]
@dataclass(frozen=True)
class NodeInfo:
"""... | mlorentedev/kubelab | tests/infra/fixtures.py | .py | bc0b539332ed8f4e | 7.5 | 0 |
"""Infrastructure: the external-service pattern, checked against the live cluster.
Services labelled `kubelab.live/location: external` are fronted by K3s Traefik but
served from somewhere else — another node over Tailscale, or bare metal. The
mechanism is a `Service` with **no selector** plus a hand-written `EndpointS... | mlorentedev/kubelab | tests/infra/test_external_services.py | .py | 1937ed58d0f1cb3d | 7.5 | 0 |
"""Infrastructure: Grafana alerting is provisioned from git, not clicked into the UI.
OBS-007. Grafana held zero alert rules and zero contact points when this spec was
written — measured, not assumed — so there was nothing watching certificate
renewal and a five-week staging outage in June 2026 was found by a browser ... | mlorentedev/kubelab | tests/infra/test_grafana_alerting.py | .py | b5116be6601f2908 | 7.5 | 0 |
"""Infrastructure: K3s cluster health — node status, pods, PVCs.
Uses local kubeconfig (~/.kube/kubelab-{env}-config) instead of SSH+sudo
to the K3s server. Requires Tailscale VPN for connectivity.
"""
from __future__ import annotations
import json
import os
import subprocess
import pytest
pytestmark = pytest.mark... | mlorentedev/kubelab | tests/infra/test_k3s.py | .py | ae651924f2efca84 | 7.5 | 0 |
"""Infrastructure: Network connectivity — VPS, Tailscale mesh, DNS resolution."""
from __future__ import annotations
import socket
import subprocess
import pytest
import yaml
from .fixtures import _COMMON, _REPO_ROOT, NodeInfo, node_ssh_run
pytestmark = pytest.mark.infra
_VPS_PUBLIC_IP = _COMMON["networking"]["vp... | mlorentedev/kubelab | tests/infra/test_network.py | .py | 42d82144d519318e | 7.5 | 0 |
"""Infrastructure: quota-watcher emits the numbers OBS-010's alert rules read.
OBS-010. #918 asked for an early signal on namespace quota utilization, so
growth is visible before admission starts rejecting workloads (IDP-031/#811).
Grafana has no metrics datasource in this repo (ADR-028 is Loki-only) and
standing up P... | mlorentedev/kubelab | tests/infra/test_quota_alerting.py | .py | 3bbec1f95f274d3b | 7.5 | 0 |
"""Infrastructure: the SEC-004 rate limit is live on every route in the cluster.
`tests/test_rate_limit_coverage.py` proves the *manifests* carry `rate-limit`.
That is a claim about git, and git was not the thing that failed: on 2026-08-15
prod's `argo.kubelab.live` route ran without the middleware for hours while eve... | mlorentedev/kubelab | tests/infra/test_rate_limit.py | .py | e074e13e51a3d9aa | 7.5 | 0 |
"""VPS production service endpoint tests.
Verifies all Ansible-managed services on the VPS are reachable
and responding correctly via their kubelab.live domains.
Requires Tailscale VPN connection.
"""
from __future__ import annotations
import subprocess
import pytest
from .fixtures import VPS_NODE, _COMMON
pytest... | mlorentedev/kubelab | tests/infra/test_vps_services.py | .py | 811b8ce8936016b0 | 7.5 | 0 |
"""AUTH-004 C6 — the admin identity resolves from `apps.auth.identities`, and from nothing else.
ADR-062 D3 makes `apps.auth.identities` the single declaration of who the
platform's humans are. The map landed in `common.yaml` on 2026-08-23 and, until
this test, **nothing read it**: `grep -rn identities toolkit/ infra/... | mlorentedev/kubelab | tests/test_admin_identity_ssot.py | .py | 0dadb7890f558e83 | 7.5 | 0 |
"""OBS-007: the alert smoke must be able to FAIL, and must always clean up.
A smoke test that cannot report failure is a slogan. These pin the parts that
decide whether it can: the log parsing it judges by, the prod refusal, and the
teardown running even when the rule never fires.
No cluster needed — `kubectl` is inj... | mlorentedev/kubelab | tests/test_alert_smoke.py | .py | 8881ff65024d01a2 | 7.5 | 0 |
"""Helpers for reading benchmark text files with legacy encoding support."""
from contextlib import contextmanager
from io import StringIO
from os import PathLike
from typing import Iterator, Optional, TextIO, Union
Pathish = Union[str, PathLike[str]]
def read_file_with_fallback(path: Pathish) -> str:
"""Read ... | fit-alessandro-berti/llm-dreams-benchmark | file_utils.py | .py | d36f80ab868ab7d0 | 7.15 | 1 |
from typing import Dict, List, Optional, Tuple
import numpy as np
import sys
import os
from pathlib import Path
PERSONALITY_HEADERS = [
"Anxiety and Stress Levels",
"Emotional Stability",
"Problem-solving Skills",
"Creativity",
"Interpersonal Relationships",
"Confidence and Self-efficacy",
... | fit-alessandro-berti/llm-dreams-benchmark | utils/parse_compute_metrics.py | .py | 33d297335bead4d9 | 7.15 | 1 |
from typing import Dict, List
import os
import sys
from pathlib import Path
import re
# Voices/metrics we expect in the markdown tables
REPO_ROOT = Path(__file__).resolve().parent.parent
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from file_utils import read_file_with_fallback
HEADERS =... | fit-alessandro-berti/llm-dreams-benchmark | utils/single_voices_report.py | .py | 7e31d8cc1c396a7d | 7.15 | 1 |
"""Version labels for Casals publish + rollout.
Semver releases (e.g. ``0.4.0``) are cut manually and published with an explicit
version. Main-branch snapshots use the ``main.<unix_ts>.<git_sha>`` channel so
each commit is traceable and sortable without bumping ``version.txt``.
Rollout ``--version main`` (or ``lates... | smart-social-contracts/realms | cli/realms/cli/casals_versions.py | .py | 2aa66879d35aaebc | 7 | 0 |
"""Import command for loading JSON data and codex files into Realms."""
import base64
import json
import math
import sys
import tempfile
from pathlib import Path
from typing import Optional
import typer
from ..constants import MAX_BATCH_SIZE
from ..utils import (
console,
display_error_panel,
display_suc... | smart-social-contracts/realms | cli/realms/cli/commands/import_data.py | .py | 9d674309ccfcfe35 | 7 | 0 |
"""Marketplace CLI commands.
The marketplace canisters (``marketplace_backend`` + ``marketplace_frontend``)
now live in the realms repo proper at ``src/marketplace_backend/`` and
``src/marketplace_frontend/`` and are declared as first-class entries in
the root ``dfx.json``. Deployment is therefore a thin wrapper aroun... | smart-social-contracts/realms | cli/realms/cli/commands/marketplace.py | .py | 8a00ef48d1ca2e76 | 7 | 0 |
"""Test command for running codex tests locally using the mock ggg framework."""
import glob
import os
import sys
import time
import traceback
import typer
from rich.console import Console
console = Console()
def _discover_tests(path):
"""Return sorted list of test file paths."""
if os.path.isfile(path):
... | smart-social-contracts/realms | cli/realms/cli/commands/test.py | .py | d6a482a0989c89d5 | 7.5 | 0 |
"""Logging configuration for Realms CLI."""
import logging
import sys
from pathlib import Path
from typing import Optional
from rich.console import Console
from rich.logging import RichHandler
console = Console()
def setup_logging(
level: str = "INFO", log_file: Optional[str] = None, verbose: bool = False
) ->... | smart-social-contracts/realms | cli/realms/cli/logging_config.py | .py | 60fecc7123b0d9a4 | 7 | 0 |
"""Data models for Realms CLI configuration."""
import re
from typing import Any, Dict, List, Literal, Optional, Union
from pydantic import BaseModel, Field, validator
class RealmMetadata(BaseModel):
"""Realm metadata configuration."""
id: str = Field(..., description="Unique identifier for the realm")
... | smart-social-contracts/realms | cli/realms/cli/models.py | .py | 944a258dfde3a234 | 7 | 0 |
"""
Realms SDK - realm module
Provides async functions for interacting with realms from workstation-side Python code.
Usage:
from realms import realm
folder = await realm.create(deploy=True)
await realm.call("join_realm", '("admin")', folder=folder)
invoices = await realm.db.get("Invoice", folder... | smart-social-contracts/realms | cli/realms/realm.py | .py | f77b1a2330217558 | 7 | 0 |
"""
Codex Testing Framework
=======================
Provides an in-memory mock of the ``ggg`` entity module so that codex files
and their tests can run locally with standard Python — no canister needed.
Usage::
from realms.testing import setup_test_env, reset_registry
setup_test_env() # inject mock... | smart-social-contracts/realms | cli/realms/testing/__init__.py | .py | 6024beaf47037999 | 7.5 | 0 |
"""
Mock ``_cdk`` module.
Provides a minimal ``ic`` object that codex files can use for:
ic.print(...) → forwards to Python print()
ic.caller() → returns a test principal string
ic.time() → returns current time in nanoseconds
ic.id() → returns a mock canister principal
"""
... | smart-social-contracts/realms | cli/realms/testing/cdk_module.py | .py | 9f889d730a4fed27 | 7.5 | 0 |
"""
In-memory Entity base class and registry.
Mirrors the ``ic_python_db.Entity`` API used by all GGG entities:
Entity(**kwargs) → create + auto-assign _id
Entity["alias_value"] → lookup by alias field
Entity.load(id) → lookup by _id
Entity.instances() → list all of this t... | smart-social-contracts/realms | cli/realms/testing/entity.py | .py | 98c78dc0e018e5f2 | 7.5 | 0 |
#!/usr/bin/env python3
"""
@Time : 2025-07-17
@Author : Rey
@Contact : reyxbo@163.com
@Explain : Base methods.
"""
from typing import Any, TypedDict, NoReturn, overload
from http import HTTPStatus
from fastapi import HTTPException
from fastapi.params import Depends
from reydb import rorm, DatabaseEngineAsync
from... | reyxbo/reyserver-py | src/reyserver/rbase.py | .py | 956286a10ab653e7 | 7 | 0 |
#!/usr/bin/env python3
"""
@Time : 2025-10-25
@Author : Rey
@Contact : reyxbo@163.com
@Explain : Cache methods.
"""
from typing import Any, overload
from collections.abc import Callable
from functools import wraps
from asyncio import Lock
from fastapi import Request, Response
from fastapi_cache import FastAPICach... | reyxbo/reyserver-py | src/reyserver/rcache.py | .py | b43e12714d24af6e | 7 | 0 |
#!/usr/bin/env python3
"""
@Time : 2025-10-09
@Author : Rey
@Contact : reyxbo@163.com
@Explain : Client methods.
"""
from typing import TypedDict, Literal, overload
from datetime import datetime as Datetime
from requests import Response, RequestException
from reykit.rbase import copy_type_hints
from reykit.rnet i... | reyxbo/reyserver-py | src/reyserver/rclient.py | .py | 00af4343bcc49c9c | 7 | 0 |
#!/usr/bin/env python3
"""
@Time : 2026-08-07
@Author : Rey
@Contact : reyxbo@163.com
@Explain : Middleware methods.
"""
from starlette.types import Scope, Receive, Send
from fastapi.middleware.gzip import GZipMiddleware as FGZipMiddleware
from . import rserver
__all__ = (
'GZipMiddleware',
)
class GZipMid... | reyxbo/reyserver-py | src/reyserver/rmiddleware.py | .py | 217af01eb2ff0757 | 7 | 0 |
#!/usr/bin/env python3
"""
@Time : 2025-10-21
@Author : Rey
@Contact : reyxbo@163.com
@Explain : Public methods.
"""
from collections.abc import Sequence
from fastapi import APIRouter
from fastapi.responses import HTMLResponse, FileResponse
from reykit.rbase import throw
from reykit.ros import File, Folder
from ... | reyxbo/reyserver-py | src/reyserver/rpublic.py | .py | 8d4a2a3dc19737a1 | 7 | 0 |
"""Maintain the bot's configured Bluesky account blocks."""
from __future__ import annotations
import os
import re
import time
from datetime import datetime, timezone
from atproto import models
from bluesky_common import mask_sensitive, retry_network_call
BLOCK_DIDS_ENV = "BLUESKY_BLOCK_DIDS"
_DID_PATTERN = re.com... | chris-gillatt/thejokebot | bluesky_blocks.py | .py | 5dd47306b0e3db93 | 7 | 0 |
"""Repository-backed denylist helpers for joke suppression."""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
DENYLIST_FILE = Path(__file__).resolve().parent / "resources" / "jokebot_denylist.json"
def _default_payload() -> dict:
return {
"version": 1,
... | chris-gillatt/thejokebot | bluesky_denylist.py | .py | aeb4e2309093912b | 7 | 0 |
"""
Joke provider functions for the joke bot.
Each provider is a callable with signature () -> str that returns a single
joke string (plain text, may contain newlines for two-part jokes) or raises
an exception if the joke cannot be fetched.
Primary providers participate in normal alternating rotation. Backup provider... | chris-gillatt/thejokebot | bluesky_joke_providers.py | .py | 24346f559bee3a04 | 7 | 0 |
import base64
import html
import os
import random
import time
import requests
import atproto_client.exceptions
import regex
import bluesky_denylist
import bluesky_config
import bluesky_joke_providers
import bluesky_state
from bluesky_common import login_client
# Joke memory and posting defaults now come from central... | chris-gillatt/thejokebot | bluesky_post_joke.py | .py | e4377038ea89872a | 7 | 0 |
"""
Update provider health check state.
This script is called by the provider_health_check.yml workflow after running
health tests. It records check results (success/failure) and tracks consecutive
failures to detect provider outages.
"""
import os
import sys
import time
import bluesky_joke_providers
import bluesky_... | chris-gillatt/thejokebot | scripts/update_provider_health.py | .py | 8360712300cb5748 | 7 | 0 |
"""Base classes and helper utilities for log adapters."""
from __future__ import annotations
import abc
from collections.abc import Iterable
from datetime import datetime
from pathlib import Path
from zscripts.schemas import NormalizedLog
if False: # pragma: no cover - for type checkers only
from scripts.sandb... | Nobodyworld/dev-logger-zscripts | adapters/base.py | .py | c988693fbfc08ad5 | 7.15 | 1 |
"""Continuous integration adapter for CI pipeline logs."""
from __future__ import annotations
from adapters.base import LogAdapter
from adapters.structured import parse_structured_log
from zscripts.schemas import NormalizedLog
class CIAdapter(LogAdapter):
"""Adapter that parses CI job logs."""
identifier =... | Nobodyworld/dev-logger-zscripts | adapters/ci/__init__.py | .py | 528c85bafc100363 | 7.15 | 1 |
"""Docker adapter for container build logs."""
from __future__ import annotations
from adapters.base import LogAdapter
from adapters.structured import parse_structured_log
from zscripts.schemas import NormalizedLog
class DockerAdapter(LogAdapter):
"""Adapter that parses docker build output."""
identifier =... | Nobodyworld/dev-logger-zscripts | adapters/docker/__init__.py | .py | 5271a15deb3bd2fe | 7.15 | 1 |
""".NET adapter for dotnet build and test logs."""
from __future__ import annotations
from adapters.base import LogAdapter
from adapters.structured import parse_structured_log
from zscripts.schemas import NormalizedLog
class DotNetAdapter(LogAdapter):
"""Adapter that parses dotnet CLI output."""
identifier... | Nobodyworld/dev-logger-zscripts | adapters/dotnet/__init__.py | .py | a29cfd053a0c1422 | 7.15 | 1 |
"""Go adapter for go test and go build logs."""
from __future__ import annotations
from adapters.base import LogAdapter
from adapters.structured import parse_structured_log
from zscripts.schemas import NormalizedLog
class GoAdapter(LogAdapter):
"""Adapter that parses Go tooling output."""
identifier = "go"... | Nobodyworld/dev-logger-zscripts | adapters/go/__init__.py | .py | dfca00ef5454a782 | 7.15 | 1 |
"""Java adapter for Maven or Gradle build logs."""
from __future__ import annotations
from adapters.base import LogAdapter
from adapters.structured import parse_structured_log
from zscripts.schemas import NormalizedLog
class JavaAdapter(LogAdapter):
"""Adapter that parses Maven-style logs."""
identifier = ... | Nobodyworld/dev-logger-zscripts | adapters/java/__init__.py | .py | bbc0975ea81d87a2 | 7.15 | 1 |
"""JavaScript and TypeScript adapter for Node-based tooling."""
from __future__ import annotations
from adapters.base import LogAdapter
from adapters.structured import parse_structured_log
from zscripts.schemas import NormalizedLog
class JavaScriptAdapter(LogAdapter):
"""Adapter that parses Jest test logs."""
... | Nobodyworld/dev-logger-zscripts | adapters/javascript/__init__.py | .py | 02e1160697dc6d7a | 7.15 | 1 |
"""Python ecosystem adapter for pytest and build logs."""
from __future__ import annotations
from adapters.base import LogAdapter
from adapters.structured import parse_structured_log
from zscripts.schemas import NormalizedLog
class PythonAdapter(LogAdapter):
"""Adapter that parses pytest-oriented structured log... | Nobodyworld/dev-logger-zscripts | adapters/python/__init__.py | .py | 552c363a2c977fac | 7.15 | 1 |
"""Rust adapter for cargo build and test logs."""
from __future__ import annotations
from adapters.base import LogAdapter
from adapters.structured import parse_structured_log
from zscripts.schemas import NormalizedLog
class RustAdapter(LogAdapter):
"""Adapter that parses Cargo output."""
identifier = "rust... | Nobodyworld/dev-logger-zscripts | adapters/rust/__init__.py | .py | 9b0f4c8d250747a0 | 7.15 | 1 |
"""Data models backing the sample project service layer."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from uuid import uuid4
def _now() -> datetime:
"""Return the current timestamp as a timezone-naïve :class:`datetime`."""
return datetime.now(... | Nobodyworld/dev-logger-zscripts | examples/sample_project/backend/models.py | .py | 402815b7ecd285d7 | 7.15 | 1 |
"""Service layer for task and project management."""
from __future__ import annotations
from dataclasses import dataclass, field
from .models import Project, Task, User
@dataclass(slots=True)
class TaskService:
"""Service for managing tasks and projects."""
tasks: dict[str, Task] = field(default_factory=d... | Nobodyworld/dev-logger-zscripts | examples/sample_project/backend/service.py | .py | 9de55bd2633032fb | 7.15 | 1 |
"""Presentation helpers that emulate REST-style views for the sample project."""
from __future__ import annotations
from collections.abc import Mapping
from typing import cast
from .service import TaskService
class TaskView:
"""REST-style view for task operations."""
def __init__(self, service: TaskServic... | Nobodyworld/dev-logger-zscripts | examples/sample_project/backend/views.py | .py | 93a8d1722983aeed | 7.15 | 1 |
"""CLI entry point for managing the sample project's in-memory database."""
from __future__ import annotations
import argparse
import logging
import sys
from collections.abc import Callable
from pathlib import Path
from typing import cast
PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(PROJECT_ROOT) not in... | Nobodyworld/dev-logger-zscripts | examples/sample_project/scripts/manage_db.py | .py | d096fe98240b5594 | 7.15 | 1 |
"""Automation entry points for linting and testing zscripts."""
from __future__ import annotations
import nox
PYTHON_VERSIONS = ["3.11"]
@nox.session(python=PYTHON_VERSIONS)
def tests(session: nox.Session) -> None:
"""Run the pytest suite."""
session.install("-e", ".", "pytest")
session.run("pytest")
... | Nobodyworld/dev-logger-zscripts | noxfile.py | .py | 8152d686a69477a9 | 7.15 | 1 |
"""Detect files containing NUL bytes (binary markers)."""
from __future__ import annotations
import os
import sys
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
IGNORE_DIRS = {
".git",
"__pycache__",
".mypy_cache",
".pytest-tmp",
".pytest_cache",
".ruff_cache",
".ve... | Nobodyworld/dev-logger-zscripts | scripts/no_binaries.py | .py | 9dba0964aec94ad7 | 7.15 | 1 |
"""Secret redaction utilities."""
from __future__ import annotations
import re
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
@dataclass
class Redactor:
"""Apply regular-expression based redaction to text."""
patterns: Sequence[str] = field(default_factory=list)
... | Nobodyworld/dev-logger-zscripts | scripts/redaction.py | .py | cc6feacaef3d31cb | 7.15 | 1 |
"""Sandboxed subprocess utilities with sensible guardrails."""
from __future__ import annotations
import os
import subprocess
from collections.abc import MutableMapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
try: # pragma: no cover - platform specific bran... | Nobodyworld/dev-logger-zscripts | scripts/sandbox.py | .py | ee3d03b3bc50da1c | 7.15 | 1 |
"""CLI utility that scaffolds extensions or health check modules."""
from __future__ import annotations
import argparse
import sys
from collections.abc import Callable
from pathlib import Path
from string import Template
from textwrap import dedent
from typing import cast
from zscripts.extensions.scaffolding import ... | Nobodyworld/dev-logger-zscripts | scripts/scaffold_module.py | .py | b12ad8647c0d2100 | 7.15 | 1 |
"""Starter template for implementing a crawler extension."""
from __future__ import annotations
from helpers.web_crawl import BaseCrawlerExtension, CrawledPage, CrawlEvent, FetchResult
class SampleExtension(BaseCrawlerExtension):
"""Document the behaviour of your extension here."""
name = "sample"
def... | Nobodyworld/dev-logger-zscripts | templates/web_crawl_extension.py | .py | 4dfe45865a62e653 | 7.15 | 1 |
"""capture.py – poll live network connections via psutil (no root required)."""
from __future__ import annotations
import ipaddress
from dataclasses import dataclass, field
from typing import List, Optional
import psutil
# Private / link-local ranges we do NOT want to geolocate
_PRIVATE_NETS = [
ipaddress.ip_ne... | Estemobs/NetMapGuard | capture.py | .py | 9240a8497242d6e1 | 7.15 | 1 |
"""main.py – entry point: python main.py"""
from __future__ import annotations
import argparse
import logging
import os
import platform
import shutil
import socket
import subprocess
import sys
import webbrowser
import uvicorn
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(n... | Estemobs/NetMapGuard | main.py | .py | b0e8df5c9f11cd31 | 7.15 | 1 |
"""Tests for ``src/zephyrus/collision.py``.
Exercises the giant-impact atmospheric mass-loss scaling law of Kegerreis
et al. (2020), ApJL 901, L31: closed-form pins of their Eqn. 1 with
wrong-formula discrimination guards, the density-weighted interacting mass
of Eqn. B1 against the interacting-volume simplification o... | FormingWorlds/ZEPHYRUS | tests/test_collision.py | .py | 9ea73d4ff66d4d60 | 7.85 | 4 |
"""Property-based tests for ``src/zephyrus/collision.py``.
Companion to ``tests/test_collision.py`` holding the Hypothesis-driven
property checks, in a separate module so the ``importorskip`` keeps the
closed-form pins running when Hypothesis is absent (for example under a
``pip install --no-deps`` image). The physica... | FormingWorlds/ZEPHYRUS | tests/test_collision_properties.py | .py | 248092932a63f152 | 7.85 | 4 |
"""Tests for ``src/zephyrus/constants.py``.
``constants.py`` is a utility source (physical constants and unit
conversions), so it is exempt from the physics-invariant requirement, but a
wrong constant is a silent physics error: every downstream rate inherits it.
These tests pin the shipped values and, more importantly... | FormingWorlds/ZEPHYRUS | tests/test_constants.py | .py | ba0b648456580c60 | 7.85 | 4 |
"""Tests for ``src/zephyrus/escape.py``.
Exercises the energy-limited (EL) atmospheric-escape mass-loss rate and its
tidal correction. The physical invariants under test:
- Conservation / closed form: the EL rate equals
``epsilon * pi * R^3 * Fxuv / (G * Mp * K_tide)`` for the selected radius
scaling, pinned agai... | FormingWorlds/ZEPHYRUS | tests/test_escape.py | .py | 78aad5a0f510f99c | 7.85 | 4 |
"""Property-based tests for ``src/zephyrus/escape.py``.
Companion to ``tests/test_escape.py`` holding the Hypothesis-driven property
checks. These live in a separate module because Hypothesis is a develop-extra
dependency: confining the ``importorskip`` to this file keeps the closed-form
pins and the error-contract gu... | FormingWorlds/ZEPHYRUS | tests/test_escape_properties.py | .py | 86c4ad91c2d1ac20 | 7.85 | 4 |
"""Tests for the MORS-to-escape flux hand-off used by the PROTEUS coupling.
Mocks the MORS stellar-luminosity lookup so the coupling recipe runs in the
fast unit tier without downloading evolution tracks. The real-lookup version
lives in ``tests/test_earth.py`` (integration tier). Invariants under test:
- Unit bounda... | FormingWorlds/ZEPHYRUS | tests/test_mors_coupling.py | .py | 04a36fe51c90c41e | 7.85 | 4 |
"""Tests for ``tools/nightly_data_cache.py``.
The nightly caches the FWL data tree under a key this script resolves. A key
that stops tracking the data does not fail anything: the nightly stays green
and either refetches every run or, worse for ZEPHYRUS, serves a stale grid
forever, because the Spada tracks land in an... | FormingWorlds/ZEPHYRUS | tests/test_nightly_data_cache.py | .py | 85576aa814e6a84a | 7.85 | 4 |
"""Tests for ``src/zephyrus/planets_parameters.py``.
``planets_parameters.py`` is a utility source (star-planet system constants),
so it is exempt from the physics-invariant requirement. A wrong parameter is a
silent physics error, so these tests pin the shipped values, bracket their
physical magnitude, and assert the... | FormingWorlds/ZEPHYRUS | tests/test_planets_parameters.py | .py | 737196ab2c9ca0c9 | 7.85 | 4 |
"""Generate shields.io endpoint-badge JSON files for ZEPHYRUS test counts.
The script invokes ``pytest --collect-only -q`` per marker expression to
count tests without executing them, then writes one JSON file per badge
under the ``--out`` directory in the shields.io endpoint-badge schema:
{"schemaVersion": 1, "l... | FormingWorlds/ZEPHYRUS | tools/generate_test_badges.py | .py | e7e27ea1ff23930a | 7.85 | 4 |
#!/usr/bin/env python3
"""Cache key and restore check for the FWL data tree the nightly caches.
Two subcommands, both used by ``.github/workflows/nightly.yml``::
python tools/nightly_data_cache.py key
python tools/nightly_data_cache.py check
ZEPHYRUS reaches one dataset through its ``fwl-mors`` dependency: t... | FormingWorlds/ZEPHYRUS | tools/nightly_data_cache.py | .py | 4de1d7912209ae36 | 7.35 | 4 |
#!/usr/bin/env python3
"""Automatically ratchet coverage thresholds for fast and full test suites.
This script implements a coverage ratcheting mechanism: the required coverage
threshold for a given suite can only increase or stay the same, never
decrease. It supports two modes:
* full - updates `[tool.coverage.repo... | FormingWorlds/ZEPHYRUS | tools/update_coverage_threshold.py | .py | 2c98f1a6db032798 | 7.35 | 4 |
"""One-time local migration: ROI-count CSVs -> zstd parquet.
``pull_dataset`` now writes ``_roi_count_df.parquet`` (~5x smaller than the
CSV). This script converts CSVs that already exist on disk from older pulls,
verifies the round-trip, and only then deletes the CSV. Readers keep CSV
fallback, so skipping or interru... | Swida-Alba/Drosophila-cross-dataset-connectome-analysis | scripts/ConvertRoiCountToParquet.py | .py | 805e219a7eb7d31d | 7.24 | 2 |
import os
import pandas as pd
try:
from .flywire_ids import canonicalize_flywire_id_expr, normalize_flywire_id_columns
except ImportError:
from flywire_ids import canonicalize_flywire_id_expr, normalize_flywire_id_columns
try:
from .utils.flywire_readiness import print_download_instructions
except ImportE... | Swida-Alba/Drosophila-cross-dataset-connectome-analysis | src/BANC_file_converter.py | .py | 93288e0704c57760 | 7.24 | 2 |
"""Regenerate the bundled neuron indexes shipped with the repository.
The app-owned ``neuron_indexes/`` directory doubles as the runtime index
store: the pull pipeline builds every dataset's index there, and a few
bundled datasets ship committed "seed" indexes so auto-suggestions and the
available-neurons viewer work ... | Swida-Alba/Drosophila-cross-dataset-connectome-analysis | src/build_seed_indexes.py | .py | 1683883ab139901c | 7.24 | 2 |
from dotenv import load_dotenv
import os
import requests
from openai_util import OpenAIUtil
class DiscordUtil:
def __init__(self, webhook_url=None):
"""discord utilの初期化
Args:
webhook_url (str, optional): Discord webhook URL. If not provided, uses DISCORD_WEBHOOK_URL from env.
... | MidraLab/arxiv-bot | source/discord_util.py | .py | 1813cf196d443988 | 7 | 0 |
import urllib.parse
from datetime import datetime, timedelta
import requests
import time
import os
import json
from discord_util import DiscordUtil
from arxiv import fetch_feed
JSON_FILE_DIR = "opt"
def save_latest_entry(latest_entry, json_file_path):
"""最新のエントリ(IDや公開日など)を保存する"""
if not os.path.exists(JSON_... | MidraLab/arxiv-bot | source/fetch_arxiv_papers.py | .py | 6e59dbdc01da83ed | 7 | 0 |
from openai import OpenAI
from dotenv import load_dotenv
import os
class OpenAIUtil:
def __init__(self):
load_dotenv()
self.client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
def translate(self, text) -> str:
"""
Translate English text to Japanese using OpenAI GPT-5 nano... | MidraLab/arxiv-bot | source/openai_util.py | .py | c28e26f6762a84bc | 7 | 0 |
import numpy as np
import torch
def faster_dice(x, y, labels, fudge_factor=1e-8):
"""Faster PyTorch implementation of Dice scores.
:param x: input label map as torch.Tensor
:param y: input label map as torch.Tensor of the same size as x
:param labels: list of labels to evaluate on
:param fudge_fac... | Mmasoud1/MeshFL | app/code/executor/dice.py | .py | 362192dc267db6c5 | 7.39 | 5 |
import sqlite3
import torch
import zlib
import json
import os
import numpy as np
class Scanloader(torch.utils.data.Dataset):
def __init__(self, db_file, label_type='label', num_cubes=1, use_split_file=False, split_file="splits.json", subset="train", logger=None):
"""
A dataset class for loading and... | Mmasoud1/MeshFL | app/code/executor/loader.py | .py | 1f792c40ebdff1a2 | 7.39 | 5 |
from collections import OrderedDict
import gc
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.functional import jvp
from torch.utils.checkpoint import checkpoint_sequential
import json
import copy
def set_channel_num(config, in_channels, n_classes, channels):
# in... | Mmasoud1/MeshFL | app/code/executor/meshnet.py | .py | 9b0cb1ac6aba32c1 | 7.39 | 5 |
from nvflare.apis.fl_constant import FLContextKey
from nvflare.apis.fl_context import FLContext
import os
def get_data_directory_path(fl_ctx: FLContext) -> str:
"""Determine and return the data directory path based on the available paths."""
site_name = fl_ctx.get_prop(FLContextKey.CLIENT_NAME)
# # Pr... | Mmasoud1/MeshFL | app/code/executor/paths.py | .py | 38f5844e9303712b | 7.39 | 5 |
import pytest
import torch
from app.code.executor.dice import dice, faster_dice
def test_dice_identical_arrays():
"""
If x and y are identical, dice score should be 1.0.
"""
x = torch.tensor([1, 1, 1, 1], dtype=torch.float32)
y = torch.tensor([1, 1, 1, 1], dtype=torch.float32)
score =... | Mmasoud1/MeshFL | tests/test_dice.py | .py | d28104316cec109f | 7.89 | 5 |
import os
import tempfile
import torch
import logging
import numpy as np
import pytest
from app.code.executor.dist import training, GenericLogger
# ----------------------------
# Dummy implementations
# ----------------------------
# Dummy MeshNet: A minimal network that uses a single Conv3d.
class Dummy... | Mmasoud1/MeshFL | tests/test_dist.py | .py | 05fb429a63021ca9 | 7.89 | 5 |
import os
import sqlite3
import zlib
import json
import numpy as np
import torch
import pytest
from app.code.executor.loader import Scanloader
def create_dummy_data(shape=(32, 32, 32), value=1.0):
"""
Create a dummy numpy array of the given shape and value,
then compress it with zlib.
"""
... | Mmasoud1/MeshFL | tests/test_loader.py | .py | 7180620566326053 | 7.89 | 5 |
import os
import pytest
from app.code.executor.paths import (
get_data_directory_path,
get_output_directory_path,
get_parameters_file_path,
)
# ----------------------------
# Dummy FLContext for Testing
# ----------------------------
class DummyFLContext:
def __init__(self, client_name, job... | Mmasoud1/MeshFL | tests/test_paths.py | .py | ea4eb079a17367f9 | 7.89 | 5 |
# Copyright 2024 Canonical Ltd.
# Licensed under the Apache2.0. See LICENSE file in charm source for details.
"""Library for the nginx-route relation.
This library contains the require and provide functions for handling
the nginx-route interface.
Import `require_nginx_route` in your charm, with four required keyword ... | canonical/livepatch-k8s-operator | lib/charms/nginx_ingress_integrator/v0/nginx_route.py | .py | 509c6119f9b4abfb | 7.3 | 3 |
# Copyright 2024 Canonical Ltd.
# Licensed under the Apache2.0. See LICENSE file in charm source for details.
"""## Overview.
This document explains how to use the `JujuTopology` class to
create and consume topology information from Juju in a consistent manner.
The goal of the Juju topology is to uniquely identify a... | canonical/livepatch-k8s-operator | lib/charms/observability_libs/v0/juju_topology.py | .py | a77a0ccfc374a3c5 | 7.3 | 3 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Module containing logic for converting from the legacy machine charm config to new config format."""
from typing import Any, Dict, List
import yaml
# Config map for converting from old reactive charm configs to the modern config format.
CO... | canonical/livepatch-k8s-operator | src/legacy_constants.py | .py | ee8454e306cff72a | 7.3 | 3 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Utils module."""
import csv
import json
import os
import platform
import tempfile
import typing as t
import requests
DEFAULT_CONTRACTS_URL = "https://contracts.canonical.com"
RESOURCE_NAME = "livepatch-onprem"
def map_config_to_env_vars(... | canonical/livepatch-k8s-operator | src/utils.py | .py | fec90e4cf5f97c0f | 7.3 | 3 |
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
import glob
import logging
from pathlib import Path
from pytest_operator.plugin import OpsTest
logger = logging.getLogger(__name__)
async def fetch_charm(ops_test: OpsTest) -> str:
"""
Uses an existing charm in the directory or build... | canonical/livepatch-k8s-operator | tests/integration/charm_utils.py | .py | 231a915f0bc9c905 | 7.8 | 3 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Common pytest configuration and fixtures for integration tests."""
import juju.utils
def _patch_libjuju_series_map() -> None:
"""Patch python-libjuju's series map to include newer Ubuntu releases not yet in its lookup table."""
mis... | canonical/livepatch-k8s-operator | tests/integration/conftest.py | .py | 8cb6d52be78310a7 | 7.8 | 3 |
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
import re
import uuid
from pathlib import Path
from typing import Literal, Union
import yaml
from ops.model import ActiveStatus, BlockedStatus, WaitingStatus
from pytest_operator.plugin import OpsTest
logger = logging.getLogger(... | canonical/livepatch-k8s-operator | tests/integration/helpers.py | .py | d7e81eb3e752b91e | 7.8 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.