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 os
import json
import pyblish.api
from ayon_core.pipeline import publish
class ExtractClipEffects(publish.Extractor):
"""Extract clip effects instances."""
order = pyblish.api.ExtractorOrder
label = "Export Clip Effects"
families = ["effect"]
def process(self, instance):
item = i... | ynput/ayon-hiero | client/ayon_hiero/plugins/publish/extract_clip_effects.py | .py | 4bc919893c07c67b | 7.42 | 6 |
"""Persistent catalog of (endpoint, dimension-combo) tuples that returned data.
Why: the full cartesian iteration across cancer × age × sex × race × stage ×
areatype (and the equivalents for risk/demographics) attempts ~5x more
combinations than actually exist in the data — pediatric cancers don't
exist for adult ages... | seandavi/state-cancer-profile-scraper | scps/catalog.py | .py | 501e5992714ab8db | 7.42 | 6 |
"""Hugging Face dataset mirror for the vintage archive (SPEC M6).
Additive to Zenodo, never authoritative: no DOI minted here, and the
dataset card leads with the Zenodo concept DOI as the citable identity.
The mirror lives on ``main``; each vintage's commit is tagged
``zenodo-vN`` so history stays git-native instead ... | seandavi/state-cancer-profile-scraper | scps/hf.py | .py | 0a5d6d40300233b5 | 7.42 | 6 |
"""Derived harmonized view across vintages.
This produces a NEW artifact from released files; original release bytes are
never modified (root CLAUDE.md). Harmonization decisions are data
(``data/crosswalks.json``), not code. The defects fixed here are the audit's
list in ``docs/schema-drift.md``:
- ``locale_type`` mi... | seandavi/state-cancer-profile-scraper | scps/normalize.py | .py | 8a9eed0f1da045df | 7.42 | 6 |
"""Scraper for the State Cancer Profiles screening & risk-factor endpoint.
Data source: ``https://statecancerprofiles.cancer.gov/risk/index.php``
The risk endpoint exposes BRFSS-derived prevalence of screening behaviors
(mammograms, colonoscopy, HPV vaccination) and risk factors (binge drinking,
smoking, obesity). Th... | seandavi/state-cancer-profile-scraper | scps/risk.py | .py | 3edacd2adf0522f8 | 7.42 | 6 |
from __future__ import annotations
import logging
import dolfin
try:
import ufl_legacy as ufl
from ufl_legacy.core.expr import Expr
except ImportError:
import ufl
from ufl.core.expr import Expr
from .base_model import BaseModel, Stimulus
logger = logging.getLogger(__name__)
class BidomainModel(Bas... | finsberg/fenics-beat | src/beat/bidomain_model.py | .py | 20d16a9e73c64398 | 7.48 | 8 |
from __future__ import annotations
import dolfin
from typing import NamedTuple
import numpy as np
try:
import ufl_legacy as ufl
except ImportError:
import ufl
def ecg_recovery(
*,
v: dolfin.Function,
mesh: dolfin.Mesh,
sigma_b: dolfin.Constant,
dx: dolfin.Measure | None = None,
point:... | finsberg/fenics-beat | src/beat/ecg.py | .py | 5937283d3a3b1b05 | 7.48 | 8 |
from __future__ import annotations
import logging
from typing import Sequence
import dolfin
try:
import ufl_legacy as ufl
from ufl_legacy.core.expr import Expr
except ImportError:
import ufl
from ufl.core.expr import Expr
from .base_model import BaseModel, Stimulus
logger = logging.getLogger(__name__... | finsberg/fenics-beat | src/beat/monodomain_model.py | .py | 0df71b433ddc7719 | 7.48 | 8 |
import numpy as np
import dolfin
import beat
from mpi4py import MPI as pyMPI
def mpi4py_comm(comm):
"""Get mpi4py communicator"""
try:
return comm.tompi4py()
except AttributeError:
return comm
def peval(f, *x):
"""Parallel synced eval"""
try:
yloc = f(*x)
except Runti... | finsberg/fenics-beat | tests/test_utils.py | .py | 988317942a05dbfe | 7.98 | 8 |
import __init__
from labothappy.component.base_component import BaseComponent
from labothappy.connector.mass_connector import MassConnector
from labothappy.connector.work_connector import WorkConnector
from CoolProp.CoolProp import PropsSI
import CoolProp.CoolProp as CP
class CompressorCstEff(BaseComponent):
"""... | PyLaboThap/LaboThapPy | labothappy/component/compressor/compressor_csteff.py | .py | 591bfef9bf37e821 | 7.6 | 15 |
import json
from dataclasses import dataclass, field
from typing import Dict, List, Optional, TypedDict
from socketdev.fullscans import (
FullScanMetadata,
SocketAlert,
SocketArtifact,
SocketArtifactLink,
SocketManifestReference,
SocketScore,
)
__all__ = [
"Report",
"Score",
"Packa... | SocketDev/socket-python-cli | socketsecurity/core/classes.py | .py | b37dd9e37e1a8f61 | 7.54 | 11 |
"""Lifecycle helpers for a CLI run on the Socket backend.
A "run" represents a single CLI invocation. `register_cli_run` opens it and
returns a server-issued `run_id` when streaming is enabled; `finalize_cli_run`
closes it on exit. The run_id keys the rows that `BatchedLogUploader` POSTs to
`/python-cli-runs/<run_id>/... | SocketDev/socket-python-cli | socketsecurity/core/cli_run.py | .py | 73a49cd929262e6d | 7.54 | 11 |
import markdown
from bs4 import BeautifulSoup, Tag
from bs4.element import NavigableString
import string
class Helper:
@staticmethod
def parse_gfm_section(html_content):
"""
Parse a GitHub-Flavored Markdown section containing a table and surrounding content.
Returns a dict with "before... | SocketDev/socket-python-cli | socketsecurity/core/helper/__init__.py | .py | a0c0356a89ee4d7a | 7.54 | 11 |
"""
Lazy file loading utilities for efficient manifest file processing.
"""
import logging
from typing import List, Tuple, Union, BinaryIO
from io import BytesIO
import os
log = logging.getLogger("socketdev")
class LazyFileLoader:
"""
A file-like object that only opens the actual file when needed for reading... | SocketDev/socket-python-cli | socketsecurity/core/lazy_file_loader.py | .py | febbc4735d02f3ca | 7.54 | 11 |
import logging
def initialize_logging(
level: int = logging.INFO,
format: str = "%(asctime)s: %(message)s",
socket_logger_name: str = "socketdev",
cli_logger_name: str = "socketcli"
) -> tuple[logging.Logger, logging.Logger]:
"""Initialize logging for Socket Security
Returns both the socket a... | SocketDev/socket-python-cli | socketsecurity/core/logging.py | .py | 78d94a8169541486 | 7.54 | 11 |
"""
System resource utilities for the Socket Security CLI.
"""
import logging
import sys
# The resource module is only available on Unix-like systems
resource_available = False
try:
import resource
resource_available = True
except ImportError:
# On Windows, the resource module is not available
pass
lo... | SocketDev/socket-python-cli | socketsecurity/core/resource_utils.py | .py | 4e7a5b0b8a5e5b46 | 7.54 | 11 |
from abc import ABC, abstractmethod
from typing import Dict
from ..classes import Comment
from .client import ScmClient
class SCM(ABC):
def __init__(self, client: ScmClient):
self.client = client
@abstractmethod
def check_event_type(self) -> str:
"""Determine the type of event (push, pr,... | SocketDev/socket-python-cli | socketsecurity/core/scm/base.py | .py | 039d7163d0681a5a | 7.54 | 11 |
from abc import abstractmethod
from typing import Dict
from socketsecurity import USER_AGENT
from ..cli_client import CliClient
class ScmClient(CliClient):
def __init__(self, token: str, api_url: str):
self.token = token
self.api_url = api_url
@abstractmethod
def get_headers(self) -> Dic... | SocketDev/socket-python-cli | socketsecurity/core/scm/client.py | .py | 18390b8c342516ab | 7.54 | 11 |
import json
import os
import sys
from dataclasses import dataclass
from typing import Optional, Union
import requests
from socketsecurity import USER_AGENT
from socketsecurity.core import log
from socketsecurity.core.classes import Comment
from socketsecurity.core.scm_comments import Comments
from socketsecurity.socke... | SocketDev/socket-python-cli | socketsecurity/core/scm/gitlab.py | .py | ad1654b6b0082841 | 7.54 | 11 |
import json
from requests import Response
from socketsecurity.core import log
from socketsecurity.core.classes import Comment, Issue
class Comments:
@staticmethod
def process_response(response: Response) -> dict:
output = {}
try:
output = response.json()
except Exception ... | SocketDev/socket-python-cli | socketsecurity/core/scm_comments.py | .py | 1b801a0e6b700bc6 | 7.54 | 11 |
from dataclasses import dataclass, field
from typing import Dict, Optional
from urllib.parse import urlparse
from typing import Set, List
import os
from socketdev.core.issues import AllIssues
from socketsecurity import __version__
default_exclude_dirs = {
"node_modules", "bower_components", "jspm_packages", # ... | SocketDev/socket-python-cli | socketsecurity/core/socket_config.py | .py | dca612b99f939f4f | 7.54 | 11 |
"""Slack formatter for Socket Facts (reachability analysis) data."""
import logging
from typing import Dict, Any, List
from collections import defaultdict
logger = logging.getLogger(__name__)
# Severity display configuration
SEVERITY_ORDER = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3}
SEVERITY_EMOJI = {
'c... | SocketDev/socket-python-cli | socketsecurity/plugins/formatters/slack.py | .py | e86e6f1fceda9203 | 7.54 | 11 |
import pytest
from socketsecurity.core import Core
from socketsecurity.core.classes import Issue
class TestDiffAlerts:
"""Test alert collection for diff reports"""
def test_get_unchanged_alerts_filters_errors(self):
"""Test that get_unchanged_alerts only returns error/warn alerts"""
alerts_di... | SocketDev/socket-python-cli | tests/core/test_diff_alerts.py | .py | ae6f4b5c5a687c9e | 7.04 | 11 |
"""Tests for the diff-scans polling scan comparison.
The comparison must never hold an idle connection open: it creates a diff-scan
resource and polls the cached endpoint (202 while processing, 200 when ready),
falling back to the legacy streaming diff if the new flow is unavailable.
"""
import pytest
from socketdev.e... | SocketDev/socket-python-cli | tests/core/test_diff_scan_polling.py | .py | 249554019485ac3c | 7.04 | 11 |
"""Tests for brotli compression of the reachability facts file on upload.
The Socket full-scan endpoint transparently decompresses a multipart part named exactly
`.socket.facts.json.br`, so the CLI compresses the facts file before uploading it. These
tests cover the helpers in `Core` that do that rewriting.
"""
import... | SocketDev/socket-python-cli | tests/core/test_facts_compression.py | .py | 57ae4fe5fb43b147 | 8.04 | 11 |
import pytest
from socketdev.exceptions import APIFailure
from socketdev.fullscans import FullScanParams, FullScanStreamResponse
from socketsecurity.config import CliConfig
from socketsecurity.core import Core
from socketsecurity.core.socket_config import SocketConfig
@pytest.fixture
def core(mock_sdk_with_responses... | SocketDev/socket-python-cli | tests/core/test_sdk_methods.py | .py | 463d26e2f86c7787 | 8.04 | 11 |
from socketsecurity.core import Core
from socketsecurity.core.classes import Diff, Issue, Package, Purl
def make_package(**overrides):
base = dict(
id="pkg:npm/test-package@1.0.0",
name="test-package",
version="1.0.0",
type="npm",
release="tar-gz",
diffType="added",... | SocketDev/socket-python-cli | tests/core/test_supporting_methods.py | .py | 73416b02e2488d22 | 8.04 | 11 |
"""Interactive video session example with CLI controls.
This example shows how use Anam as an avatar provider where
the orchetration is bypassed and the avatar is rendered based on input TTS audio.
The videoand audio output are kept in sync. Video is displayed in
a window using OpenCV, while audio is played through so... | anam-org/python-sdk | examples/avatar_audio_passthrough.py | .py | e2989017f8454aae | 7.42 | 6 |
"""Interactive video session example with CLI controls.
This example shows how to display the avatar video stream
in a window using OpenCV while providing CLI controls for
interactive session management, where talk commands will be
spoken directly by the avatar, while text messages mimic
the transcibed audio.
The per... | anam-org/python-sdk | examples/persona_interactive_video.py | .py | a5ccb600f36d2882 | 7.42 | 6 |
"""Recording example - save video/audio to files.
This example demonstrates how to save the avatar's video and audio
streams to files for later processing.
Usage:
# Set environment variables in .env or shell:
export ANAM_API_KEY="your-api-key"
export ANAM_PERSONA_ID="your-persona-id"
# Run with displ... | anam-org/python-sdk | examples/save_recording.py | .py | 07f5bbdd9ed3b1ae | 7.42 | 6 |
"""Text-to-video example - send text and save avatar video response.
This example demonstrates a simple text-to-video function that:
1. Connects to an Anam session with a persona or avatar/voice config
2. Sends text via the talk() command for direct TTS
3. Records the avatar's video and audio response
4. Saves the out... | anam-org/python-sdk | examples/text_to_video.py | .py | 56833e9ed1bdf890 | 7.42 | 6 |
"""Shared utility functions and classes for examples."""
import asyncio
import logging
import wave
from collections import deque
from pathlib import Path
from typing import TYPE_CHECKING, Protocol
import cv2
import numpy as np
from av.audio.frame import AudioFrame
from av.video.frame import VideoFrame
from anam._age... | anam-org/python-sdk | examples/utils.py | .py | 45ab09272df67a80 | 7.42 | 6 |
"""Agent audio input stream for sending PCM audio data to the backend."""
import base64
import logging
from typing import Union
from ._signalling import SignallingClient
from .types import AgentAudioInputConfig, AgentAudioInputPayload
logger = logging.getLogger(__name__)
class AgentAudioInputStream:
"""Stream ... | anam-org/python-sdk | src/anam/_agent_audio_input_stream.py | .py | 89e24cc486a64dad | 7.42 | 6 |
"""Internal API client for Anam services."""
import logging
from typing import Any
import aiohttp
from ._version import __version__
from .errors import AnamError, AuthenticationError, ErrorCode, SessionError
from .types import ClientOptions, PersonaConfig, SessionInfo, SessionOptions
logger = logging.getLogger(__na... | anam-org/python-sdk | src/anam/_api.py | .py | a8c3c988c0a93cc9 | 7.42 | 6 |
"""WebSocket signalling client for Anam services."""
import asyncio
import json
import logging
from enum import Enum
from typing import Any, Awaitable, Callable
import websockets
from websockets.asyncio.client import ClientConnection
from websockets.protocol import State
from .types import AgentAudioInputPayload, Se... | anam-org/python-sdk | src/anam/_signalling.py | .py | 795111313c97d88b | 7.42 | 6 |
"""Talk message stream for sending streaming text to TTS via WebSocket signalling."""
import logging
import uuid
from enum import Enum
from typing import TYPE_CHECKING
from ._signalling import SignallingClient
from .types import AnamEvent
if TYPE_CHECKING:
from .client import AnamClient
logger = logging.getLogg... | anam-org/python-sdk | src/anam/_talk_message_stream.py | .py | 9f9914b6ced7fd98 | 7.42 | 6 |
"""User audio input track for sending raw audio samples to Anam via WebRTC.
This module provides a mechanism for accepting raw audio samples and
converting them to WebRTC-compatible format for transmission.
User audio is real time audio such as microphone audio.
"""
import asyncio
import fractions
import logging
imp... | anam-org/python-sdk | src/anam/_user_audio_input_track.py | .py | 4bd55414273afe1d | 7.42 | 6 |
"""Exception classes for the Anam SDK."""
from enum import Enum
from typing import Any
class ErrorCode(str, Enum):
"""Error codes for Anam SDK errors."""
CONFIGURATION_ERROR = "configuration_error"
AUTHENTICATION_ERROR = "authentication_error"
VALIDATION_ERROR = "validation_error"
CONNECTION_ERR... | anam-org/python-sdk | src/anam/errors.py | .py | 4c69a8331486c140 | 7.42 | 6 |
"""Type definitions for the Anam SDK."""
import math
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Literal
class AnamEvent(str, Enum):
"""Events emitted by the Anam client."""
# Connection events
CONNECTION_ESTABLISHED = "connection_established"
CONNECTION_CL... | anam-org/python-sdk | src/anam/types.py | .py | b7289f50bb43833b | 7.42 | 6 |
'''
Halo data processing
'''
from functools import reduce
import numpy as np
from pynbody.array import SimArray
from AnastrisTNG.TNGgroupcat import haloproperties
from AnastrisTNG.TNGsnapshot import Basehalo
class Halo(Basehalo):
"""
Represents a single halo in the simulation.
This class contains infor... | wx-ys/AnastrisTNG | src/AnastrisTNG/TNGhalo.py | .py | 64dd8ea78e471dc9 | 7.5 | 9 |
"""Lazy-load machinery for TNG snapshots (mirrors pynbody GadgetHDFSnap).
Both the merged Snapshot and the snapshot returned by load_particle are
SimSnap subclasses that override _load_array / loadable_keys. _LazyCtx is the
shared read logic keyed on per-family original file row indices (_loaded_index).
"""
import nu... | wx-ys/AnastrisTNG | src/AnastrisTNG/TNGload.py | .py | 1b0f247194d294d9 | 7.5 | 9 |
'''
Subhalo data processing
'''
from functools import reduce
import numpy as np
from pynbody.array import SimArray
from AnastrisTNG.TNGgroupcat import subhaloproperties
from AnastrisTNG.TNGsnapshot import Basehalo
class Subhalo(Basehalo):
"""
Represents a single subhalo in the simulation.
This class co... | wx-ys/AnastrisTNG | src/AnastrisTNG/TNGsubhalo.py | .py | e777fa1499bfeea2 | 7.5 | 9 |
""" Illustris Simulation: Public Data Release.
groupcat.py: File I/O related to the FoF and Subfind group catalogs. """
from __future__ import print_function
import six
from os.path import isfile,expanduser
import numpy as np
import h5py
def gcPath(basePath, snapNum, chunkNum=0):
""" Return absolute p... | wx-ys/AnastrisTNG | src/AnastrisTNG/illustris_python/groupcat.py | .py | 86eec2c9ee5e124b | 7.5 | 9 |
""" Illustris Simulation: Public Data Release.
lhalotree.py: File I/O related to the LHaloTree merger tree files. """
import numpy as np
import h5py
import six
from .groupcat import gcPath, offsetPath
from os.path import isfile
def treePath(basePath, chunkNum=0):
""" Return absolute path to a LHaloT... | wx-ys/AnastrisTNG | src/AnastrisTNG/illustris_python/lhalotree.py | .py | cf97edf7bf5af266 | 7.5 | 9 |
""" Illustris Simulation: Public Data Release.
sublink.py: File I/O related to the Sublink merger tree files. """
import numpy as np
import h5py
import glob
import six
import os
from .groupcat import gcPath, offsetPath
from .util import partTypeNum
def treePath(basePath, treeName, chunkNum=0):
"""... | wx-ys/AnastrisTNG | src/AnastrisTNG/illustris_python/sublink.py | .py | afc05c91993fe969 | 7.5 | 9 |
from numba import njit, float64, float32
@njit(fastmath=True) # ([float64(float64,float64),float32(float32,float32)])
def ForceKernel(r, h):
"""
Returns the quantity equivalent to (fraction of mass enclosed)/ r^3 for a cubic-spline mass distribution of compact support radius h. Used to calculate the so... | wx-ys/AnastrisTNG | src/AnastrisTNG/pytreegrav/kernel.py | .py | f121ee97e0810545 | 7.5 | 9 |
# -*- coding: utf-8 -*-
import sqlite3
import json
import uuid
import logging
from pathlib import Path
from typing import Dict, Any, Optional, List
from butler.agent.context import AgentContext
from butler.agent.planner import Planner
from butler.agent.executor import Executor
from butler.agent.verifier import Verifier... | HelloEveryboby/Butler | butler/agent/agent.py | .py | b9ade68a4a4411d7 | 7.63 | 17 |
# -*- coding: utf-8 -*-
from typing import List, Dict, Any, Optional
class AgentContext:
"""
保存并维护数字员工在单次任务流转中的运行状态、当前规划和历史结果。
"""
def __init__(self, task_id: str, task_input: str):
self.task_id = task_id
self.task_input = task_input
self.plan_steps: List[Dict[str, Any]] = []
... | HelloEveryboby/Butler | butler/agent/context.py | .py | 4f83a662ce849f57 | 7.63 | 17 |
# -*- coding: utf-8 -*-
import logging
from typing import Dict, Any, Optional
from butler.package_runtime.loader import PackageLoader
logger = logging.getLogger(__name__)
class Executor:
"""
负责依次调起规划步骤。整合了 PackageLoader 用于运行具体的物理 Skill/Agent 包,
若包不存在,则提供逻辑自恰、高拟真的 Mock 模拟运行层,保持逻辑连贯。
"""
def __init_... | HelloEveryboby/Butler | butler/agent/executor.py | .py | 5aea640004d13e3d | 7.63 | 17 |
# -*- coding: utf-8 -*-
import os
import json
import logging
from typing import List, Dict, Any
from package.core_utils.config_loader import config_loader
logger = logging.getLogger(__name__)
class Planner:
"""
负责将最终的任务总目标(Task Goal/Intent)转换为一系列有序的、可执行的子步骤(Sub-steps)。
支持接入 OpenAI, Claude, DeepSeek 并能在无密钥... | HelloEveryboby/Butler | butler/agent/planner.py | .py | bb9dfae97f091254 | 7.63 | 17 |
# -*- coding: utf-8 -*-
import logging
from typing import Dict, Any
logger = logging.getLogger(__name__)
class Verifier:
"""
负责对步骤执行结果、或整个任务规划树的完整执行结果进行自动审查校验。
"""
def verify_step(self, step: Dict[str, Any], result: Dict[str, Any]) -> bool:
"""
验证单个步骤的执行产出是否合法且状态无异常。
"""
... | HelloEveryboby/Butler | butler/agent/verifier.py | .py | c804e6fc988cf857 | 7.63 | 17 |
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass, fields, replace
from typing import Any
class BaseTool(metaclass=ABCMeta):
"""工具的基类。"""
@abstractmethod
def __call__(self, **kwargs) -> Any:
"""使用给定参数执行工具。"""
...
class BaseAnthropicTool(BaseTool, metaclass=ABCMeta)... | HelloEveryboby/Butler | butler/base.py | .py | 024a4658b3e5b469 | 7.63 | 17 |
import asyncio
import os
from typing import ClassVar, Literal
from anthropic.types.beta import BetaToolBash20241022Param
from .base import BaseAnthropicTool, CLIResult, ToolError, ToolResult
class _BashSession:
"""bash shell的一个会话."""
_started: bool
_process: asyncio.subprocess.Process
command: str... | HelloEveryboby/Butler | butler/bash.py | .py | 6ff5360c2821de59 | 7.63 | 17 |
"""增强的 Butler 启动文件 - 集成新的设置和配置系统
这个文件是对原 butler_app.py 的改进,添加了:
1. 启动向导(首次运行)
2. 增强的配置系统
3. 更好的错误处理
4. 配置验证
"""
import os
import sys
import time
import datetime
import json
import re
import threading
import logging
from typing import Dict, Any, List
import tempfile
import shutil
import tkinter as tk
from pathlib impo... | HelloEveryboby/Butler | butler/butler_app_enhanced.py | .py | 556cff133df77762 | 7.63 | 17 |
# -*- coding: utf-8 -*-
"""交互式 AI 提供商配置命令 (`butler config`).
在终端中以问答方式选择 AI 服务商、填写 API 地址/模型/密钥,
并持久化写入 .env。与 GUI 向导、安装脚本共享同一套 PROVIDER_DEFAULTS。
"""
import os
import getpass
from pathlib import Path
from dotenv import set_key, load_dotenv
from butler.core.config_model import PROVIDER_DEFAULTS, PROVIDER_KEY_PATHS
... | HelloEveryboby/Butler | butler/cli/config_cmd.py | .py | 9ee381e3e1ef20ea | 7.63 | 17 |
import os
import json
import subprocess
import logging
import shlex
import shutil
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class CodeExecutionManager:
"""
CodeExecutionManager scans the programs/ directory, compiles multi-language
pro... | HelloEveryboby/Butler | butler/code_execution_manager.py | .py | 89ab7335d92b3a7c | 7.63 | 17 |
"""工具集合管理类"""
from typing import Any
from .base import BaseTool, ToolError, ToolFailure, ToolResult
class ToolCollection:
"""DeepSeek工具集合管理类"""
def __init__(self, *tools: BaseTool):
"""初始化工具集合
参数:
*tools: 可变数量的工具实例
"""
self.tools = tools
# 创建工具名称到工具对象的映射
... | HelloEveryboby/Butler | butler/collection.py | .py | e32d002a5a7b2a02 | 7.63 | 17 |
import asyncio
import base64
import math
import os
import platform
import subprocess
import shlex
import shutil
import tempfile
import time
from enum import StrEnum
from pathlib import Path
from typing import Literal, TypedDict
from uuid import uuid4
# 导入 PyAutoGUI 用于计算机控制
import pyautogui
try:
from deepseek.types... | HelloEveryboby/Butler | butler/computer.py | .py | 1b5042d8c407439d | 7.63 | 17 |
import requests
import json
import logging
import socket
import ipaddress
from urllib.parse import urlparse
from typing import Dict, Any, Optional
from package.core_utils.log_manager import LogManager
logger = LogManager.get_logger("ActionBridge")
def _validate_safe_url(url: str) -> None:
"""校验 URL 安全性,防止 SSRF 攻... | HelloEveryboby/Butler | butler/core/action_bridge.py | .py | 61c7651524cdc718 | 7.63 | 17 |
"""
Headless CLI — 纯命令行入口,不初始化 GUI/语音。
参考架构:
- OpenHands CLI: 纯命令行入口,headless 友好
- Claude Code: CLI 优先设计
使用方式::
# 单次命令
python -m butler.core.agent_runtime.cli "list all Python files"
# 交互模式
python -m butler.core.agent_runtime.cli --interactive
# 指定权限模式
python -m butler.core.agent_ru... | HelloEveryboby/Butler | butler/core/agent_runtime/cli.py | .py | 49a12c0cfc449f92 | 7.63 | 17 |
"""
事件流 — 追加式事件日志 + 确定性重放。
参考架构:OpenHands 的事件溯源(EventStream)架构。
事件日志是"追加唯一的真相源":
- 所有 agent 行为(消息、工具调用、工具结果、权限请求、压缩等)
都通过事件记录
- 支持确定性重放(deterministic replay)
- 支持订阅/发布模式,用于可观测性、调试、自定义日志
事件类型:
- MESSAGE: 用户/助手消息
- TOOL_CALL: 工具调用请求
- TOOL_RESULT: 工具执行结果
- TOOL_ERROR: 工具执行错误
- PER... | HelloEveryboby/Butler | butler/core/agent_runtime/event_stream.py | .py | c1a419206ec128f0 | 7.63 | 17 |
"""
MCP Client — Model Context Protocol 工具服务器集成。
参考架构:OpenHands V1 的 MCP 集成组件。
MCP (Model Context Protocol) 是 Anthropic 提出的标准协议,用于:
- 连接外部工具服务器
- 透明地将 MCP 工具转换为 SDK 工具格式
- 管理服务器生命周期和通信
核心功能:
1. 发现 MCP 服务器上的工具
2. 将 MCP 工具注册到 ToolRegistry
3. 代理工具调用到 MCP 服务器
4. 管理服务器连接生命周期
注意:这是 MCP 客户端的骨架实... | HelloEveryboby/Butler | butler/core/agent_runtime/mcp_client.py | .py | 11713781642204bf | 7.63 | 17 |
"""
子代理管理器 — 隔离上下文子代理委托系统。
参考架构:Claude Code 的 Subagent 系统。
核心特性:
1. 隔离上下文:每个 subagent 拥有全新的上下文窗口,不继承父对话历史
2. 独立系统提示:每个 subagent 可定义自己的系统提示
3. 工具隔离:通过 tools 字段限制 subagent 可用工具
4. 嵌套执行:subagent 可生成自己的子代理(最大 5 层)
5. 摘要返回:仅返回最终消息给父代理,中间工具调用留在子代理记录中
Subagent 定义格式(Markdown + YAML frontmatter):
---... | HelloEveryboby/Butler | butler/core/agent_runtime/subagent_manager.py | .py | 104d7477675a8e7d | 7.63 | 17 |
"""
工具注册表 — JSON Schema 驱动的标准化工具注册系统。
参考架构:
- OpenHands ToolExecutor: 分离工具定义和执行,Pydantic 模型自动生成 JSON Schema
- Claude Code buildTool(): 标准契约(输入/输出 Schema + 权限检查 + 元数据标志)
每个工具注册时声明:
1. JSON Schema 参数定义(供 LLM 自主选择工具)
2. 权限层级(always_allow / require_confirm / never_allow)
3. 元数据标志(is_read_only / is_des... | HelloEveryboby/Butler | butler/core/agent_runtime/tool_registry.py | .py | 8b8240c42e721fe8 | 7.63 | 17 |
"""
Agent Runtime 核心类型定义。
所有类型均为不可变 dataclass(或 Pydantic 模型),遵循 OpenHands V1 的
"默认无状态,单一状态源" 原则。唯一可变实体是 ConversationState。
"""
from __future__ import annotations
import time
import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
try:
from pydantic import BaseModel, Fie... | HelloEveryboby/Butler | butler/core/agent_runtime/types.py | .py | dd2c871187fd6b36 | 7.63 | 17 |
import logging
import threading
import uvicorn
from fastapi import FastAPI, Depends, HTTPException, Security, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses ... | HelloEveryboby/Butler | butler/core/api.py | .py | 51407e4713dc2989 | 7.63 | 17 |
from pathlib import Path
from butler.core.constants import PROJECT_ROOT, DATA_DIR
class AssetLoader:
"""
资源加载器,模拟 STM32 内部/外部 Flash 访问逻辑。
代码逻辑预期在 'Internal Flash',资源文件在 'External Flash'。
"""
def __init__(self):
# 定位项目根目录
self.project_root = PROJECT_ROOT
self.external_flash_b... | HelloEveryboby/Butler | butler/core/asset_loader.py | .py | c4f77d3753dd3c8c | 7.63 | 17 |
import psutil
from package.core_utils.log_manager import LogManager
from butler.resource_manager import PerformanceMode
logger = LogManager.get_logger("battery_manager")
class BatteryManager:
"""
Butler 电池管理器 (Battery Manager)
监控系统电池状态,为低功耗运行提供决策支持。
"""
def __init__(self, low_battery_threshold=20)... | HelloEveryboby/Butler | butler/core/battery_manager.py | .py | f6496ceccf898579 | 7.63 | 17 |
import time
import threading
import logging
from typing import Any, Dict, Optional, List
logger = logging.getLogger("Blackboard")
class BlackboardData:
"""带有生命周期的黑板数据项"""
def __init__(self, value: Any, ttl: float):
self.value = value
self.expires_at = time.time() + ttl
def is_expired(self... | HelloEveryboby/Butler | butler/core/blackboard.py | .py | f1d132f844a54ab0 | 7.63 | 17 |
"""
Butler 服务容器引导模块。
将 Jarvis.__init__ 中的手动服务实例化链替换为声明式 AppContainer 注册。
所有服务通过工厂函数延迟创建,依赖关系由容器按拓扑序解析。
"""
from __future__ import annotations
import logging
import os
import secrets as _secrets
from typing import TYPE_CHECKING
from butler.core.container import AppContainer, ServiceSpec
if TYPE_CHECKING:
from b... | HelloEveryboby/Butler | butler/core/bootstrap.py | .py | 5c5ee726f2a5c2dc | 7.63 | 17 |
"""
Butler 能力诊断报告器 (CapabilityReporter)。
启动时扫描各 capability 的可用性,显式报告而非静默降级。
解决 try/except ImportError 静默降级导致的行为不可见问题。
"""
from __future__ import annotations
import importlib
import logging
from dataclasses import dataclass, field
logger = logging.getLogger(__name__)
@dataclass
class CapabilityStatus:
"""单个能力维... | HelloEveryboby/Butler | butler/core/capability_reporter.py | .py | a8e7dba39f708cae | 7.63 | 17 |
#!/usr/bin/env python
"""Require pyproject, docs conf, and README citation versions to match."""
import re
import sys
from pathlib import Path
ROOT_DIR = Path(__file__).parent.parent
PYPROJECT_PATH = ROOT_DIR / "pyproject.toml"
CONF_PATH = ROOT_DIR / "docs/source/conf.py"
README_PATH = ROOT_DIR / "README.md"
try:
... | 0xideas/sequifier | hooks/correct_docs_version.py | .py | 58c14a7dc3d817ef | 7.66 | 20 |
"""Typed component fields for semantic layer freezing."""
from typing import Optional
from pydantic import (
BaseModel,
ConfigDict,
field_validator,
model_serializer,
model_validator,
)
from sequifier.config.layer_groups import LayerGroup
from sequifier.typechecking import beartype
class LayerF... | 0xideas/sequifier | src/sequifier/config/freezing_config.py | .py | 01f7e1d2a019a5a4 | 7.66 | 20 |
"""Canonical hyperparameter-search configuration.
Hyperparameter search always starts from a canonical authored training config
and applies recursive overrides. Historical self-contained search configs and
flat-schema base configs are intentionally unsupported.
"""
from __future__ import annotations
from typing impo... | 0xideas/sequifier | src/sequifier/config/hyperparameter_search_config.py | .py | 09d1daea9f298b07 | 7.66 | 20 |
import numpy
import yaml
from pydantic import BaseModel
from sequifier.config.train_config import DotDict
from sequifier.helpers import ModelWindowView, StoredWindowLayout
from sequifier.typechecking import beartype
@beartype
def represent_sequifier_object(dumper, data):
"""Represent sequifier config objects as ... | 0xideas/sequifier | src/sequifier/io/yaml.py | .py | a37acdd71ffcf6d8 | 7.66 | 20 |
class Betting:
def __init__(self, client):
self._client = client
self._path = "/betting-tools"
def outright_odds(
self,
market: str,
tour: str = "pga",
odds_format: str = "decimal",
f_format: str = "json",
) -> dict:
"""
Returns the mo... | coreyjs/data-golf-api | data_golf/api/betting.py | .py | eacd23e9c54dd438 | 7.54 | 11 |
from typing import List
class Historical:
def __init__(self, client):
self._client = client
self._path = "/historical-raw-data"
def events(self, f_format: str = "json") -> List[dict]:
"""
Returns a list of all events in the Data Golf database.
:param f_format: (str, op... | coreyjs/data-golf-api | data_golf/api/historical.py | .py | bc8672822ed74aca | 7.54 | 11 |
class LivePrediction:
def __init__(self, client):
self.client = client
self._path = "/preds"
def live_in_play(
self,
tour: str = "pga",
dead_heat: bool = False,
odds_format: str = "percent",
f_format: str = "json",
) -> dict:
"""
Retur... | coreyjs/data-golf-api | data_golf/api/live_prediction.py | .py | 9b8251678cd05030 | 7.54 | 11 |
from data_golf.api.betting import Betting
from data_golf.api.prediction import Prediction
from data_golf.config import DGConfig
from data_golf.http_client import HttpClient
from data_golf.api.general import General
from data_golf.api.live_prediction import LivePrediction
class DGCInvalidApiKey(Exception):
pass
... | coreyjs/data-golf-api | data_golf/client.py | .py | f86a05270089fe8d | 7.54 | 11 |
from typing import Tuple
from data_golf.request_helpers import RequestHelpers
import httpx
import logging
class DGForbidden(Exception):
pass
class DGBadRequest(Exception):
pass
class HttpClient:
def __init__(self, config) -> None:
self._config = config
if self._config.verbose:
... | coreyjs/data-golf-api | data_golf/http_client.py | .py | 8fab488cc2cc1836 | 7.54 | 11 |
# model_utils.py
import torch
import pandas as pd
# Assuming you have your model class defined somewhere, e.g., up_cnn_model.py
from .cnn_train import up_cnn_model
def load_model(model_path):
"""
Load the trained model.
"""
model_cnn = up_cnn_model.CNN_Class()
model_cnn.load_state_dict(torch.load... | faizanurv/ChemEmbed | src/chemembed/model_utils.py | .py | 24fae60477b55679 | 7.54 | 11 |
"""Test fixtures to set up fake database for testing."""
import datetime as dt
import logging
import time
from collections.abc import Generator
import pytest
from pvsite_datamodel.read.model import get_or_create_model
from pvsite_datamodel.read.user import get_user_by_email
from pvsite_datamodel.sqlmodels import (
... | openclimatefix/quartz-api | src/quartz_api/internal/backends/quartzdb/conftest.py | .py | c2ffd6e574d140ff | 8.02 | 10 |
"""Manual eclipse adjustment for national solar forecasts, 12 August 2026.
PVNet has never seen an eclipse in training and ignores the effect, so all models
over-forecast through the eclipse window. Same problem and same fix as 29 March 2025
(openclimatefix/uk-pv-national-gsp-api#404). National only, GB and NL, foreca... | openclimatefix/quartz-api | src/quartz_api/internal/eclipse.py | .py | 19ab2b8214c1adcb | 7.52 | 10 |
"""Middleware to log API requests to the database."""
import logging
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING
from fastapi import FastAPI, Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
if TYPE_CHECKING:
from quartz_api.internal import models
... | openclimatefix/quartz-api | src/quartz_api/internal/middleware/audit.py | .py | 0fe9faaf90644791 | 7.52 | 10 |
"""Authentication dependency for FastAPI using Auth0 JWT tokens."""
import logging
from collections.abc import Awaitable, Callable
from typing import Annotated
from apitally.fastapi import set_consumer
from fastapi import Depends, HTTPException, Request
from fastapi.security import HTTPBearer
from fastapi_plugin.fast... | openclimatefix/quartz-api | src/quartz_api/internal/middleware/auth.py | .py | 05391eb10346dd9e | 7.52 | 10 |
"""Middleware to log API requests to the database."""
from collections.abc import Awaitable, Callable
from fastapi import FastAPI, Request, Response
from fastapi.responses import HTMLResponse
from pyinstrument import Profiler
from starlette.middleware.base import BaseHTTPMiddleware
class ProfilerMiddleware(BaseHTTP... | openclimatefix/quartz-api | src/quartz_api/internal/middleware/profile.py | .py | 8fc6de7e10dcad0c | 7.52 | 10 |
"""Middleware to add user details to sentry for error tracking."""
import logging
from collections.abc import Awaitable, Callable
import sentry_sdk
from fastapi import FastAPI, Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from quartz_api.internal.middleware import auth
from quartz_api.i... | openclimatefix/quartz-api | src/quartz_api/internal/middleware/sentry.py | .py | 381b4e37024c0d16 | 7.52 | 10 |
"""Tests for rate limiting utilities."""
import typing
import jwt
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from pyhocon import ConfigFactory
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from quartz_api.cmd.main import _cre... | openclimatefix/quartz-api | src/quartz_api/internal/middleware/test_ratelimit.py | .py | 2d98414f6534fe56 | 7.02 | 10 |
"""Middleware to log API requests to the database."""
import collections
import logging
import time
import uuid
from collections.abc import Awaitable, Callable
from contextvars import ContextVar
from typing import Any
import grpc.aio
from fastapi import FastAPI, Request, Response
from starlette.middleware.base import... | openclimatefix/quartz-api | src/quartz_api/internal/middleware/trace.py | .py | 5e9b87dfc999e35a | 7.52 | 10 |
"""Defines the domain models for the application."""
import datetime as dt
from enum import StrEnum
from typing import Annotated
from zoneinfo import ZoneInfo
import pandas as pd
from fastapi import Depends, Query
from pydantic import AfterValidator, AwareDatetime, BaseModel, Field
def convert_to_camelcase(snake_st... | openclimatefix/quartz-api | src/quartz_api/internal/models/endpoint_types.py | .py | 98614fd5613378fc | 7.52 | 10 |
""" Simple tests for enpoint types"""
import pandas as pd
from .endpoint_types import get_start_window_shifted_for_uk
def test_get_start_window_shifted_for_uk():
"""Test the get_start_window_shifted_for_uk function."""
# 1. UK/London winter time
result = get_start_window_shifted_for_uk(now=pd.Timestamp(... | openclimatefix/quartz-api | src/quartz_api/internal/models/test_endpoint_types.py | .py | 6a6030e9ae09c21b | 8.02 | 10 |
"""S3 client."""
from datetime import UTC, datetime, timedelta
import fsspec
# Satellite S3 config, populated at startup via configure() from the parsed
# HOCON schema (cmd/server.conf). server.conf is the single source of truth for
# values and defaults; this module just holds whatever it is handed.
_config: dict[st... | openclimatefix/quartz-api | src/quartz_api/internal/s3.py | .py | 291b12e1e077db4a | 7.52 | 10 |
"""Functions to resample data."""
import datetime as dt
import math
from collections import defaultdict
import pandas as pd
from .endpoint_types import ActualPower, PredictedPower
def resample_generation(
values: list[ActualPower],
interval_minutes: int,
) -> list[ActualPower]:
"""Perform binning on th... | openclimatefix/quartz-api | src/quartz_api/internal/service/regions/_resample.py | .py | c2bf2373c835198e | 7.52 | 10 |
"""Pydantic models definining the router's request/response types."""
import datetime as dt
from typing import Annotated
from fastapi import Path
from pydantic import BaseModel, Field
class ActualPower(BaseModel):
"""Defines the data structure for an actual power value returned by the API."""
PowerKW: floa... | openclimatefix/quartz-api | src/quartz_api/internal/service/regions/endpoint_types.py | .py | 097a77c5b8203639 | 7.52 | 10 |
import datetime as dt
import logging
from uuid import uuid4
from zoneinfo import ZoneInfo
import pandas as pd
from quartz_api.internal import models
from ._csv import format_csv_and_created_time
log = logging.getLogger(__name__)
class TestCsvExport:
def test_format_csv_and_created_time(self) -> None:
... | openclimatefix/quartz-api | src/quartz_api/internal/service/regions/test_csv.py | .py | c28b3005a4016b8e | 8.02 | 10 |
"""Sun times for the visible satellite channels' nighttime blackout.
The visible channels carry no signal once the region is dark, so they get zeroed
out at night. Rather than fixed clock times, the window comes from sunrise and
sunset at a reference point, so it follows the seasons: a timestamp is dark when
it falls ... | openclimatefix/quartz-api | src/quartz_api/internal/service/satellite/_blackout.py | .py | 61545890e44ff712 | 7.52 | 10 |
import datetime as dt
import unittest
from ._blackout import apply_buffer, sun_times
# Middle of the UK bounding box used by the ingest.
UK_LON, UK_LAT = -2.725, 54.9
# Lit windows through the year, as the ingest builds them. Everything is UTC, so
# the days either side of a BST switchover must land on the same wind... | openclimatefix/quartz-api | src/quartz_api/internal/service/satellite/test_blackout.py | .py | ca9ea9723285608d | 7.02 | 10 |
"""Endpoint classes for the sites router."""
from uuid import UUID
from pydantic import AwareDatetime, BaseModel, Field, field_validator
class SiteProperties(BaseModel):
"""Properties specific to a site."""
latitude: float | None = Field(
None,
description="The location's latitude",
... | openclimatefix/quartz-api | src/quartz_api/internal/service/sites/endpoint_types.py | .py | 73cf6daead407be7 | 7.52 | 10 |
"""The 'sites' FastAPI router object and associated routes logic."""
import datetime as dt
import logging
import pathlib
from uuid import UUID
import pandas as pd
from fastapi import APIRouter, HTTPException
from starlette import status
from quartz_api.internal import models
from quartz_api.internal.middleware.auth ... | openclimatefix/quartz-api | src/quartz_api/internal/service/sites/router.py | .py | 5a74a58d48b7dbdb | 7.52 | 10 |
from app.common import officer
from app import utils
from math import hypot, ceil, floor
from dataclasses import dataclass
import itertools
import numpy
import app
@dataclass(frozen=True, slots=True)
class ReplayFrame:
delta: int
time: int
x: float
y: float
button_state: int
GAMEPLAY_BUTTONS = ... | osuTitanic/deck | app/helpers/replays.py | .py | f8a39fba5d3f3b36 | 7.52 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.