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 |
|---|---|---|---|---|---|---|
"""Content models for multimodal ATIF trajectories.
Added in ATIF-v1.6 to support multimodal content (images) in trajectories.
"""
from typing import Literal
from pydantic import BaseModel, Field, model_validator
class ImageSource(BaseModel):
"""Image source specification for images stored as files or at remot... | existential-birds/daydream | daydream/atif/models/content.py | .py | f7ebfb9d0d77969d | 7.66 | 20 |
"""Subagent trajectory reference model for ATIF trajectories."""
from typing import Any
from pydantic import BaseModel, Field, model_validator
class SubagentTrajectoryRef(BaseModel):
"""Reference to a delegated subagent trajectory.
A subagent reference is resolved by one of two mechanisms:
1. **Embedd... | existential-birds/daydream | daydream/atif/models/subagent_trajectory_ref.py | .py | 207388b30eec20aa | 7.66 | 20 |
# daydream/backends/__init__.py
"""Backend abstraction layer for daydream.
Defines the unified event stream, Backend protocol, and factory function.
Backends yield AgentEvent instances that the UI layer consumes without
knowing which backend produced them.
Event vocabulary (members of the ``AgentEvent`` TypeAlias uni... | existential-birds/daydream | daydream/backends/__init__.py | .py | 3e67ed416a72ee20 | 7.66 | 20 |
# daydream/backends/_subprocess.py
"""Shared subprocess lifecycle helpers for the CLI backends (codex, pi)."""
from __future__ import annotations
import asyncio
import logging
import math
import os
import signal
import anyio
logger = logging.getLogger(__name__)
# Idle-stall detection for the CLI backends' stdout s... | existential-birds/daydream | daydream/backends/_subprocess.py | .py | a8ebc3feea658582 | 7.66 | 20 |
"""Harbor ``BaseAgent`` that reviews a frozen private-PR snapshot in-container (issue #780).
``DaydreamReviewAgent`` runs host-side: it guarantees the Pi/OpenRouter backend, builds
a fail-closed allowlist child environment, and invokes the controlled
in-container entrypoint (``daydream.benchmark.harbor.entrypoint``) v... | existential-birds/daydream | daydream/benchmark/harbor/agent.py | .py | dc6fefc2a93358c1 | 7.66 | 20 |
"""Candidate artifact builder for the privacy-safe Harbor review agent (issue #780).
Pure, stdlib-only, host-testable: converts the deep pipeline's canonical
``merged-items.json`` entries into the strict §9 candidate artifact. No Harbor
import; the verifier's own ``verifier_core`` derivation and caps are reused so
the... | existential-birds/daydream | daydream/benchmark/harbor/candidate.py | .py | a95c74c5fea8b5ee | 7.66 | 20 |
"""Ledger-backed cleanup of a Harbor benchmark workspace (issue #782).
A sibling of :mod:`daydream.benchmark.harbor.run` that removes exactly what the
workspace recorded it created: the disposable ``cache/`` clone + build stage
(``--cache``), contained ``agent/trajectory.json`` files in ledgered job dirs
(``--trajecto... | existential-birds/daydream | daydream/benchmark/harbor/clean.py | .py | df185411ecf062ed | 7.66 | 20 |
"""Controlled in-container runner for the privacy-safe Harbor review agent (issue #780).
Invoked inside the Harbor task container (``python -m
daydream.benchmark.harbor.entrypoint``) by :class:`DaydreamReviewAgent`'s
``run`` via ``environment.exec``. Owns the fail-closed review surface: it maps
only the ``DAYDREAM_REV... | existential-birds/daydream | daydream/benchmark/harbor/entrypoint.py | .py | 4e8defe9c2568023 | 7.66 | 20 |
#!/usr/bin/env -S uv run --script
"""Self-contained corpus micro-metric aggregation for the Harbor verifier image.
Stdlib only, never imports daydream (or the bundled verifier_core): the
aggregation body is inlined at build time so a compiled task's ``metric.py``
needs nothing but the stdlib. Reads one JSONL line per ... | existential-birds/daydream | daydream/benchmark/harbor/templates/metric.py | .py | c3131c3f39ab5d5f | 7.66 | 20 |
"""progressive_optimize demo — dielectric block transmission.
NOT a cross-validation. Minimal API demo that shows how
``rfx.progressive_optimize`` runs inverse design at a sequence of
increasing mesh resolutions, upsampling the latent between stages.
Moved out of the cross-validation tree (now ``validation/crossval/`... | bk-squared/rfx | examples/inverse_design/progressive_demo.py | .py | d305ecf5cfdd66a7 | 7.45 | 7 |
"""ADI solver -- trade wavelength-scale accuracy for a larger timestep.
The default ``solver="yee"`` is an explicit scheme: its timestep is bounded by
the Courant (CFL) limit, which is set by the *smallest* cell in the mesh. A
thin layer -- a substrate a few cells thick, a coating, a narrow gap -- forces a
tiny times... | bk-squared/rfx | examples/tutorials/adi_solver_demo.py | .py | 8a301dd50299c9ca | 7.45 | 7 |
"""Short-dipole far field -- place the Huygens box before trusting a pattern.
One rule matters most for near-to-far-field work: keep every monitor face at
least half the shortest monitored wavelength from radiating or scattering
structures. A closer face samples the reactive near field, so its pattern and
directivity... | bk-squared/rfx | examples/tutorials/antenna_farfield_pattern.py | .py | fbc6d7f65f477c2b | 7.45 | 7 |
"""Create a shareable rfx artifact bundle (scene + mesh + report) without running FDTD.
Use this when you want to hand a design to a colleague or archive a setup:
it exports the native scene, mesh/preflight metadata, a Markdown review
report, and a manifest. Run:
python examples/tutorials/artifact_report_demo.py
... | bk-squared/rfx | examples/tutorials/artifact_report_demo.py | .py | e809e3175434a4c5 | 7.45 | 7 |
"""Materials and dispersion — choose what the fields travel through.
This tutorial makes one material decision at a time:
* Use a library name when a standard material already fits the job.
* Register a custom dielectric when you have measured permittivity or loss.
* Add Debye or Lorentz poles when permittivity chang... | bk-squared/rfx | examples/tutorials/materials_and_dispersion.py | .py | cf6fe3d1b68d7144 | 7.45 | 7 |
"""Patch antenna end to end: multi-mode ring-down, far-field mode ID, honest error budget.
Geometry: the openEMS "Simple Patch Antenna" tutorial — a 32 x 40 mm patch on a
1.524 mm, eps_r = 3.38, tan_delta = 1e-3 substrate over a 60 x 60 mm finite
ground plane, probe-fed 6 mm off centre. Running the identical geometry... | bk-squared/rfx | examples/tutorials/patch_antenna_demo.py | .py | a2273fc2a8e17710 | 7.45 | 7 |
"""Ports and S-parameters -- match the port to the structure.
A port is both an excitation and a field measurement. Its field shape must
match the transmission structure, or the reported reflection includes the
bad launch as well as the device response.
This tutorial runs two very small single-cell-port S11 calculat... | bk-squared/rfx | examples/tutorials/ports_and_sparams_101.py | .py | 04d9b5b1faf5627c | 7.45 | 7 |
"""PEC-sphere RCS -- subtract the empty reference before reading a pattern.
Radar cross section turns the scattered far field into an equivalent area.
This tutorial makes one important measurement decision: remove the incident
field from the collection box before interpreting any angle.
Always pass ``subtract_inciden... | bk-squared/rfx | examples/tutorials/rcs_scattering.py | .py | 0e65ffbfd03b93f2 | 7.45 | 7 |
"""Cavity ring-down -- choose the expected mode before reading its frequency.
A closed rectangular PEC cavity stores electromagnetic energy. With vacuum
inside and no resistive load, the field rings forever because there is nowhere
for the energy to go. That is the physics. A frequency extracted from a
finite recor... | bk-squared/rfx | examples/tutorials/resonance_harminv.py | .py | 35ff3b4d08381e66 | 7.45 | 7 |
"""Run control and fields -- choose when a simulation should finish.
This tutorial applies all three run controls to one small open simulation:
* ``n_steps`` executes an exact number of FDTD updates.
* ``num_periods`` converts periods at ``freq_max`` to an update count.
* ``until_decay`` continues until total interio... | bk-squared/rfx | examples/tutorials/run_control_and_fields.py | .py | f7afe7a1d5e3318d | 7.45 | 7 |
"""Broadband R(f)/T(f) of a dielectric slab — the recommended flux-monitor path.
This is the runnable companion to ``docs/agent/recipe-rt-measurement.mdx``. It
demonstrates the *correct* way to measure broadband reflection and transmission
spectra in rfx:
add_flux_monitor + two-run reference subtraction (field-... | bk-squared/rfx | examples/tutorials/slab_rt_flux_monitor.py | .py | f5ab7dc2a4ee834b | 7.45 | 7 |
"""Thin artifact-export mixin for :class:`rfx.api.Simulation`.
This module must remain a leaf/transitional mixin: do not import the package
root or ``rfx.api`` here. Policy lives in ``rfx.artifacts`` and is imported
inside methods to keep the high-level API wiring additive and cycle-safe.
"""
from __future__ import ... | bk-squared/rfx | rfx/api/_artifacts.py | .py | 5ea8a68e6522b92d | 7.45 | 7 |
"""Perfect Electric Conductor (PEC) boundary condition.
Zeros tangential E-field at boundary faces.
"""
from __future__ import annotations
import jax.numpy as jnp
from rfx.core.yee import _shift_bwd, _shift_fwd
def apply_pec(state, axes: str = "xyz") -> object:
"""Apply PEC (E_tan = 0) at domain boundaries.
... | bk-squared/rfx | rfx/boundaries/pec.py | .py | 4b72a42132533ed0 | 7.45 | 7 |
"""Uniaxial PML (UPML) with D/B-equivalent formulation.
Two corrections over the original implementation:
1. **Half-cell offset**: σ_E evaluated at Yee E-positions (half-cell inside),
σ_H evaluated at Yee H-positions (cell boundary). Prevents impedance
mismatch inside PML that causes spurious reflections.
2. *... | bk-squared/rfx | rfx/boundaries/upml.py | .py | 128a30c2e689627f | 7.45 | 7 |
from __future__ import annotations
import shutil
from pathlib import Path
from setuptools import setup
from setuptools.command.build_py import build_py
class CleanBuildPy(build_py):
"""Prevent ignored stale build/lib files from leaking into wheels."""
def run(self) -> None:
build_lib = Path(self.bu... | adamcohen8/orbital-engagement-lab | setup.py | .py | 5647840fb0b8612d | 7.07 | 13 |
"""Optional compiled scalar kernels for the MSIS-86 atmosphere model."""
from __future__ import annotations
import math
from sim.acceleration.optional import njit_or_identity
@njit_or_identity(cache=True, fastmath=False)
def _zeta_kernel(zz: float, zl: float, re_km: float) -> float:
return (zz - zl) * (re_km +... | adamcohen8/orbital-engagement-lab | sim/acceleration/kernels/msis86.py | .py | 9253e2bb2b801cbc | 7.57 | 13 |
"""Base quirk definition."""
from abc import ABC, abstractmethod
from collections.abc import Callable
from dataclasses import dataclass
import inspect
import json
import pathlib
from typing import TYPE_CHECKING, Any, Self
from tuya_sharing import CustomerDevice, DeviceFunction, DeviceStatusRange
from tuya_device_han... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/builder/device_quirk.py | .py | cbc4ce49a6bc4cb6 | 7.65 | 19 |
"""Constants for Tuya device handlers."""
from __future__ import annotations
from enum import IntFlag, StrEnum
# Dictionary to track logged warnings to avoid spamming logs
# Keyed by device ID
DEVICE_WARNINGS: dict[str, set[str]] = {}
# Aliases for temperature units to handle variations in device reporting
CELSIUS_... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/const.py | .py | daad2e5382079cc8 | 7.65 | 19 |
"""Tuya alarm control panel definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.alarm_control_panel import (
AlarmActionWrapper,
Ala... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/alarm_control_panel.py | .py | ecd4c8a03ef9d343 | 7.65 | 19 |
"""Tuya binary sensor definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.binary_sensor import (
DPCodeBitmapBitWrapper,
DPCodeInSet... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/binary_sensor.py | .py | a512641f93a65ac1 | 7.65 | 19 |
"""Tuya button definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import DPCodeBooleanWrapper
from .base import BaseEntityQuirk
@... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/button.py | .py | 36de8aaf1ca7af24 | 7.65 | 19 |
"""Tuya camera definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import DPCodeBooleanWrapper
from .base import BaseEntityQuirk
@... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/camera.py | .py | e34b5762e046cfc2 | 7.65 | 19 |
"""Tuya climate definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.const import CELSIUS_ALIASES, FAHRENHEIT_ALIASES
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapp... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/climate.py | .py | 913d20edbfdbe3f3 | 7.65 | 19 |
"""Tuya cover definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import (
DPCodeTypeInformationWrapper,
)
from tuya_device_handl... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/cover.py | .py | aceda941da94088c | 7.65 | 19 |
"""Tuya event definition."""
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import (
DPCodeTypeInformationWrapper,
)... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/event.py | .py | 723a3b9f80f9dc8d | 7.65 | 19 |
"""Tuya fan definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import (
DPCodeBooleanWrapper,
DPCodeEnumWrapper,
)
from tuya... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/fan.py | .py | 7505bf20bbe61408 | 7.65 | 19 |
"""Tuya humidifier definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import (
DPCodeBooleanWrapper,
DPCodeEnumWrapper,
)
fr... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/humidifier.py | .py | aeb8af77583e9bae | 7.65 | 19 |
"""Tuya light definition."""
from collections.abc import Callable
from dataclasses import dataclass
from enum import StrEnum
import json
from typing import Any, cast
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common i... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/light.py | .py | a943374f23b4e705 | 7.65 | 19 |
"""Tuya number definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import DPCodeIntegerWrapper
from .base import BaseEntityQuirk
@... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/number.py | .py | 79734491d631e9ae | 7.65 | 19 |
"""Tuya select definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import DPCodeEnumWrapper
from .base import BaseEntityQuirk
@dat... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/select.py | .py | 2078954bea3f4a32 | 7.65 | 19 |
"""Tuya sensor definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import (
DPCodeEnumWrapper,
DPCodeIntegerWrapper,
DPCo... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/sensor.py | .py | f6da2df3673e27ea | 7.65 | 19 |
"""Tuya siren definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import DPCodeBooleanWrapper
from .base import BaseEntityQuirk
@d... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/siren.py | .py | 525b010ada34d639 | 7.65 | 19 |
"""Tuya switch definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import DPCodeBooleanWrapper
from .base import BaseEntityQuirk
@... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/switch.py | .py | 3cf98f4f3b2db11a | 7.65 | 19 |
"""Tuya vacuum definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import DPCodeEnumWrapper
from tuya_device_handlers.device_wrapper.... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/vacuum.py | .py | 58c45c73be4f2001 | 7.65 | 19 |
"""Tuya valve definition."""
from collections.abc import Callable
from dataclasses import dataclass
from tuya_sharing import CustomerDevice
from tuya_device_handlers.device_wrapper import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import DPCodeBooleanWrapper
from .base import BaseEntityQuirk
@d... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/definition/valve.py | .py | 2dc0cf76b332d3b1 | 7.65 | 19 |
"""Tuya device wrapper."""
import base64
from typing import Any
from tuya_sharing import CustomerDevice
from tuya_device_handlers.helpers.homeassistant import (
TuyaAlarmControlPanelAction,
TuyaAlarmControlPanelState,
)
from tuya_device_handlers.type_information import EnumTypeInformation
from .common impor... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/alarm_control_panel.py | .py | 77d15906ad175b28 | 7.65 | 19 |
"""Tuya device wrapper."""
from typing import Any
from tuya_sharing import CustomerDevice
class DeviceWrapper[T]:
"""Base device wrapper."""
native_unit: str | None = None
suggested_unit: str | None = None
max_value: float
min_value: float
value_step: float
options: list[str]
def... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/base.py | .py | 4a728566a02420e2 | 7.65 | 19 |
"""Tuya device wrapper."""
from typing import Self
from tuya_sharing import CustomerDevice
from tuya_device_handlers.type_information import BitmapTypeInformation
from .common import DPCodeBitmapWrapper, DPCodeWrapper
class DPCodeBitmapBitWrapper(DPCodeBitmapWrapper[bool]):
"""Simple wrapper for a specific bi... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/binary_sensor.py | .py | 1b9d483e8c20aa47 | 7.65 | 19 |
"""Tuya device wrapper."""
import collections
from dataclasses import dataclass
from typing import Any, Self
from tuya_sharing import CustomerDevice
from tuya_device_handlers.helpers.homeassistant import (
TuyaClimateHVACMode,
TuyaClimateSwingMode,
)
from tuya_device_handlers.type_information import EnumType... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/climate.py | .py | 0c6e91e51be7e9ef | 7.65 | 19 |
"""Tuya device wrapper."""
from typing import Any, Self
from tuya_sharing import CustomerDevice
from tuya_device_handlers.type_information import (
BitmapTypeInformation,
BooleanTypeInformation,
EnumTypeInformation,
IntegerTypeInformation,
JsonTypeInformation,
PrepareSetValueError,
RawTyp... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/common.py | .py | 99952cf6d56972cf | 7.65 | 19 |
"""Tuya device wrapper."""
from tuya_sharing import CustomerDevice
from tuya_device_handlers.helpers.homeassistant import TuyaCoverAction
from tuya_device_handlers.type_information import EnumTypeInformation
from .common import DPCodeBooleanWrapper, DPCodeEnumWrapper
from .extended import DPCodePercentageWrapper
c... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/cover.py | .py | 72c491d1c151d29e | 7.65 | 19 |
"""Tuya device wrapper."""
from typing import Any
from tuya_sharing import CustomerDevice
from tuya_device_handlers.type_information import IntegerTypeInformation
from tuya_device_handlers.utils import RemapHelper
from .common import DPCodeBooleanWrapper, DPCodeIntegerWrapper
class DPCodeRoundedIntegerWrapper(DPC... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/extended.py | .py | 62a64358b29b136c | 7.65 | 19 |
"""Tuya device wrapper."""
from typing import Any
from tuya_sharing import CustomerDevice
from tuya_device_handlers.helpers.homeassistant import TuyaFanDirection
from tuya_device_handlers.type_information import (
EnumTypeInformation,
IntegerTypeInformation,
)
from .common import DPCodeEnumWrapper
from .ext... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/fan.py | .py | 8a1a0e10f781de29 | 7.65 | 19 |
"""Device quirks for Tuya devices."""
import base64
from enum import IntFlag
from typing import Any, Literal, TypedDict
from tuya_sharing import CustomerDevice
from tuya_device_handlers.type_information import RawTypeInformation
from .base import DeviceWrapper
from .common import DPCodeRawWrapper
class FeederSche... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/service_feeder_schedule.py | .py | ebd00b33f209c6c4 | 7.65 | 19 |
"""Tuya device wrapper."""
from typing import Any, Self
from tuya_sharing import CustomerDevice
from tuya_device_handlers.helpers.homeassistant import (
TuyaVacuumAction,
TuyaVacuumActivity,
)
from .base import DeviceWrapper
from .common import DPCodeBooleanWrapper, DPCodeEnumWrapper
class VacuumActivityW... | home-assistant-libs/tuya-device-handlers | src/tuya_device_handlers/device_wrapper/vacuum.py | .py | 5d8bcd448ef9b640 | 7.65 | 19 |
"""
小市值择时模块
================
判断当前市场是否适合小市值风格,动态调整 small_cap 因子权重。
核心逻辑:
1. 计算"小市值相对强度" = 小市值组合收益 / 大市值组合收益(滚动N日)
2. 计算"小市值溢价" = 小市值因子 IC 的滚动均值
3. 综合得分 = 0.6 × 相对强度分位数 + 0.4 × IC溢价分位数
4. 权重映射:small_cap_weight = base_weight × (1 + sensitivity × score)
参考:聚宽"基于市场存量状态择时的小市值策略"、BigQuant"分时段择优小市值策略"
"""
import numpy as np
... | fkchaos/a-share-quant-sim | core/archive/small_cap_timer.py | .py | 6c6f0a4126c87d82 | 7.48 | 8 |
"""
Panel data loader for backtesting.
Reads daily K-line CSVs and builds aligned panels (DataFrames) of shape (dates × stocks)
for each price/volume field required by factor calculation.
Used by run_backtest.py — NOT used by sim_daily (which uses sim_daily's own single-stock loading).
"""
import os
import sys
impor... | fkchaos/a-share-quant-sim | core/data.py | .py | 3565b5d4fdfc32ba | 7.48 | 8 |
#!/usr/bin/env python3
"""域分割器 - 按市值分割股票池为多个域"""
import sqlite3
import pandas as pd
import numpy as np
from typing import Dict, List, Optional
from datetime import datetime
class DomainSplitter:
"""
域分割器
将股票池按市值分割为多个域:
- 大盘域:市值 > 500亿(沪深300级别)
- 中盘域:市值 100-500亿(中证500级别)
- 小盘域:市值 < 100亿(中... | fkchaos/a-share-quant-sim | core/domain_splitter.py | .py | 671b78ca6a7c1078 | 7.48 | 8 |
"""
P1_7: 业绩预告事件因子 — 计算信号
逻辑:
1. 读取 DB 中 earnings_preview 表的业绩预告事件
2. 正面预告(预增/预盈)→ 漂移效应(预告后短期看涨)
3. 负面预告(预减/预亏)→ 规避(预告后短期下跌压力)
4. 信号衰减:预告日 +N 天内逐步衰减
核心函数:
compute_earnings_signal(panel) → pd.Series
返回每只股票的业绩预告信号(正=利好,负=利好,0=无事件)
earnings_signal_mask(panel, lookback=30) → pd.Series
返回 bool Seri... | fkchaos/a-share-quant-sim | core/earnings_preview.py | .py | b572d88dbd1b1480 | 7.48 | 8 |
"""
v48 — 事件驱动因子计算模块
三类事件因子:高管增持、限售解禁、分红。
"""
import numpy as np
import pandas as pd
import sqlite3
def compute_insider_factor(trade_date: str, lookback_days: int = 90,
db_path: str = 'data/quant_stocks.db') -> pd.Series:
"""
计算高管增持因子。
逻辑:最近 lookback_days 天内高管净增持金额(增持-减持),
... | fkchaos/a-share-quant-sim | core/event_factors.py | .py | bba5e4e204e5e3aa | 7.48 | 8 |
"""
行业轮动策略模块。
核心逻辑:
1. 行业动量:过去 20 日行业收益排名前 N 的行业
2. 行业反转:过去 5 日行业收益排名后 N 的行业(避免追高)
3. 行业轮动评分 = 动量分 - 反转分
4. 在 top 行业内选股(用 v13 量价因子)
用法:
from industry_rotation import IndustryRotation
rot = IndustryRotation(close_panel, industry_map)
top_industries = rot.get_top_industries(date, top_n=5)
industry_scor... | fkchaos/a-share-quant-sim | core/industry_rotation.py | .py | 21864239a726b98e | 7.48 | 8 |
"""
v47 — ML 因子计算模块
用随机森林从价量特征预测横截面收益率,输出为独立因子分数。
"""
import numpy as np
import pandas as pd
def compute_ml_factor_from_panels(panels: tuple, n_train: int = 252, retrain_freq: int = 5) -> pd.Series:
"""
从 load_panel_from_db 返回的面板数据计算 ML 因子。
Parameters
----------
panels : tuple
(close,... | fkchaos/a-share-quant-sim | core/ml_factor.py | .py | 3e29938038cda2ff | 7.48 | 8 |
"""
Position — 单一持仓的领域模型。
替代裸 dict {'shares': int, 'cost_price': float, 'entry_date': str},
提供类型安全、IDE 补全、封装加权平均成本计算。
"""
from dataclasses import dataclass
from typing import Optional
@dataclass
class Position:
code: str
shares: int
cost_price: float
entry_date: str
@property
def is_empty(s... | fkchaos/a-share-quant-sim | core/position.py | .py | 040395f60bfc5165 | 7.48 | 8 |
"""数据源管理器
支持:
- primary: 主数据源
- backup: 备用数据源(primary失败时fallback)
- override: 手动指定(优先级最高)
"""
import os
import yaml
from enum import Enum
from typing import Optional, List, Dict
import pandas as pd
from core.data_provider import DataProvider
class ProviderRole(Enum):
PRIMARY = "primary"
BACKUP = "backup"
... | fkchaos/a-share-quant-sim | core/provider_manager.py | .py | c0461a1802a11faf | 7.48 | 8 |
"""BaoStock 数据源 Provider
特点:
- 免费、无需注册
- 有 turn(换手率)、tradestatus(停牌)、isST(ST标记)
- 成交量单位:股(标准单位)
- 代码格式:sh.600519 → 需转换为 600519
"""
import pandas as pd
from typing import Optional, List
from core.data_provider import DataProvider
# 延迟导入 baostock,避免未安装时报错
_bs = None
def _get_bs():
"""懒加载 baostock"""
global _b... | fkchaos/a-share-quant-sim | core/providers/baostock.py | .py | a8bb36f184cacb37 | 7.48 | 8 |
#!/usr/bin/env python3
"""舆情数据获取模块 - 从东方财富获取新闻数据"""
import sqlite3
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional
import time
import os
class SentimentDataFetcher:
"""舆情数据获取器"""
def __init__(self, db_path: str = 'data/sentiment.db'... | fkchaos/a-share-quant-sim | core/sentiment/data_fetcher.py | .py | c232e2151147f81d | 7.48 | 8 |
"""
core/streak_factor.py — 连板辨识度因子
计算每只股票的"连板记忆效应":历史上连板次数越多、距离越近,
二次启动的概率越高。
接口:
compute_streak_factor(panel, date) -> pd.Series
compute_streak_risk(panel, date) -> pd.Series
"""
import numpy as np
import pandas as pd
def compute_streak_factor(panel, date=None, decay_days=252):
"""
连板辨识度因子:过去N日内最大... | fkchaos/a-share-quant-sim | core/streak_factor.py | .py | 1d81edb04b9c5bd7 | 7.48 | 8 |
# -*- coding: utf-8 -*-
"""
core/trading.py — 交易门面层
==============================
统一的交易入口,兼容两种模式:
1. 直接调用模式(现有代码,account_runner.py)
2. Provider模式(新代码,QMT移植时使用)
Python 3.6.8 兼容。
"""
import logging
logger = logging.getLogger(__name__)
# 全局provider实例(可选)
_global_provider = None
def set_provider(provider):
"""设置... | fkchaos/a-share-quant-sim | core/trading.py | .py | 10dae6b0e05db356 | 7.48 | 8 |
#coding:gbk
"""
data.py - QMT Market Data -> Our Format
Converts QMT K-line data to our standard format.
NOTE: Runs in QMT built-in Python 3.6, must be 3.6.8 compatible.
"""
import pandas as pd
import numpy as np
from datetime import datetime
def qmt_to_our_format(klines, period='1d'):
"""
Convert QMT K-line... | fkchaos/a-share-quant-sim | qmt_deploy/qmt_adapter/data.py | .py | 59678c121a030e34 | 7.48 | 8 |
#coding:gbk
# QMT_RUNNER v2 - set_risk_debug added
#coding:gbk
"""
qmt_runner.py - QMT Common Runner
Encapsulates QMT environment init, global state, risk control etc.
Strategy files only need to implement stock selection logic.
"""
import sys
_qmt_initialized = False
_risk_debug = False
def set_risk_debug(flag):
... | fkchaos/a-share-quant-sim | qmt_deploy/qmt_adapter/qmt_runner.py | .py | d33bc279bcb5d3a8 | 7.48 | 8 |
#coding:gbk
"""
v61c_strategy.py - V61C Strategy Logic
Low turnover + small cap factors.
Turnover = volume / float_shares (QMT volume is in shares, not lots)
5-day average turnover + market cap, equal weight 50/50 rank scoring.
Per-stock rebalance: each stock sells independently when hold_days >= REBALANCE_DAYS.
No u... | fkchaos/a-share-quant-sim | qmt_deploy/qmt_adapter/v61c_strategy.py | .py | 20c37960e226d2dc | 7.48 | 8 |
#coding:gbk
"""
v75j_strategy.py - V75J Strategy Logic
Tech trend + liquidity factor + breadth filter.
- Tech filter: electronic/computer/communication/media sectors
- Liquidity: 20-day average trading amount (higher = more liquid)
- Breadth: % of tech stocks above 20-day MA
- Linear position scaling in breadth neutra... | fkchaos/a-share-quant-sim | qmt_deploy/qmt_adapter/v75j_strategy.py | .py | 640184ee33ea2cb9 | 7.48 | 8 |
#coding:gbk
"""v61c_qmt.py - V61C entry point (dual trigger mode)
MODE = 'BACKTEST' -> handlebar callback (backtest + live universal)
MODE = 'LIVE' -> schedule_run timer (live only, supports call auction etc)
Business logic lives in v61c_strategy.on_signal(), shared by both modes.
"""
# ========== CONFIG ======... | fkchaos/a-share-quant-sim | qmt_deploy/v61c_qmt.py | .py | 4e17161173216f7a | 7.48 | 8 |
#coding:gbk
"""v75j_qmt.py - V75J entry point (dual trigger mode)
MODE = 'BACKTEST' -> handlebar callback (backtest + live universal)
MODE = 'LIVE' -> schedule_run timer (live only, supports call auction etc)
Business logic lives in v75j_strategy.on_signal(), shared by both modes.
"""
# ========== CONFIG ======... | fkchaos/a-share-quant-sim | qmt_deploy/v75j_qmt.py | .py | 4ca2f335af7a06b5 | 7.48 | 8 |
#!/usr/bin/env python3
"""Hebrew LLM eval runner.
Loads a benchmark from HuggingFace, calls a model endpoint, writes raw
outputs to disk. This is a reference implementation: for production runs,
wire it to your preferred orchestration (Airflow, Ray, LangChain, etc.).
Usage:
python run_eval.py --benchmark heq --mo... | skills-il/developer-tools | hebrew-llm-eval-suite/scripts/run_eval.py | .py | 0e7fda1abbb267a3 | 7.52 | 10 |
#!/usr/bin/env python3
"""Score raw eval outputs from run_eval.py into per-benchmark metrics.
Handles Hebrew-specific normalization (sofit forms, nikud removal,
whitespace collapse) required for fair HeQ scoring.
Usage:
python score_results.py --input eval-results/
python score_results.py --input eval-results... | skills-il/developer-tools | hebrew-llm-eval-suite/scripts/score_results.py | .py | fbaa735a2cc85cef | 7.52 | 10 |
#!/usr/bin/env python3
"""
Hebrew Speech-to-Text Demo
Demonstrates Hebrew STT using OpenAI Whisper. Can transcribe existing
Hebrew audio files or generate a test audio file using TTS and then
transcribe it back to verify the pipeline.
Usage:
# Transcribe an existing Hebrew audio file
python hebrew-stt-demo.py... | skills-il/developer-tools | hebrew-voice-bot-builder/scripts/hebrew-stt-demo.py | .py | 54edaa43785aae8c | 7.52 | 10 |
#!/usr/bin/env python3
"""Validate, format, and convert Israeli phone numbers.
Notes:
- Mobile Number Portability (MNP) has been live in Israel since 2007. The carrier
inferred from the prefix is the *issuing* carrier, not necessarily the current one.
- 056 (Wataniya) and 059 (Jawwal) are Palestinian territories car... | skills-il/developer-tools | israeli-phone-formatter/scripts/validate_phone.py | .py | fa6f2a67b5e75596 | 7.52 | 10 |
#!/usr/bin/env python3
"""Scaffold a new skills-il skill folder with correct structure and templates.
Creates the complete folder structure for a new skill:
<skill-name>/
├── SKILL.md # Template with minimal frontmatter (name, description, license)
├── SKILL_HE.md # Hebrew companion stub
├── met... | skills-il/developer-tools | skills-il-skill-creator/scripts/scaffold-skill.py | .py | e712c19b17892884 | 7.52 | 10 |
"""
Custom alpaca interface unit tests
Copyright (C) 2021 Emerson Dove
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your opt... | Quivnex/blankly-finance | Blankly-test-rsi/exchanges/interfaces/alpaca/test_alpaca_interface.py | .py | e3f6eb7b657cce2d | 8.06 | 12 |
"""
Custom alpaca unit tests
Copyright (C) 2021 Emerson Dove
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any l... | Quivnex/blankly-finance | Blankly-test-rsi/exchanges/interfaces/alpaca/test_alpaca_interface_functional.py | .py | 9d3f49b9a5494b5a | 8.06 | 12 |
"""
Oanda interface custom unit tests.
Copyright (C) 2021 Emerson Dove
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your opt... | Quivnex/blankly-finance | Blankly-test-rsi/exchanges/interfaces/oanda/test_oanda_interface.py | .py | 114042b1e76ef5e1 | 8.06 | 12 |
"""
Comparison utilities for tests
Copyright (C) 2021 Emerson Dove
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option)... | Quivnex/blankly-finance | Blankly-test-rsi/helpers/comparisons.py | .py | bd5f22fd357c3984 | 8.06 | 12 |
"""
Simple utility functions that enable more robust testing
Copyright (C) 2021 Emerson Dove
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the Licens... | Quivnex/blankly-finance | Blankly-test-rsi/testing_utils.py | .py | 6ce172842a668817 | 8.06 | 12 |
"""
Functions for managing Exchange API Keys
Copyright (C) 2022 Matias Kotlik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at yo... | Quivnex/blankly-finance | blankly/deployment/keys.py | .py | f671337b3f89b819 | 7.56 | 12 |
"""
Functions for blankly login/logout commands
Copyright (C) 2022 Matias Kotlik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at... | Quivnex/blankly-finance | blankly/deployment/login.py | .py | d86e217fefc871ac | 7.56 | 12 |
"""
Base Exchange object.
Copyright (C) 2022 Matias Kotlik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | Quivnex/blankly-finance | blankly/exchanges/abc_base_exchange.py | .py | 1d9932f2a7027249 | 7.56 | 12 |
"""The AquaBle integration."""
from __future__ import annotations
import hashlib
import logging
from pathlib import Path
from homeassistant.components.http import StaticPathConfig
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ADDRESS, CONF_NAME, Platform
from homeassistant... | caleb-venner/AquaBle | custom_components/aquable/__init__.py | .py | 3617609a4f07af83 | 7.45 | 7 |
"""Lovelace card resource registration for AquaBle custom dashboard cards.
The card JS must be registered as a Lovelace resource rather than loaded via
frontend.add_extra_js_url. add_extra_js_url injects the module into the
index page's <script type="module">, which runs at page load — before HA
lazily installs @webco... | caleb-venner/AquaBle | custom_components/aquable/card_resources.py | .py | 0c97c2a7b48aa018 | 7.45 | 7 |
"""Config flow for AquaBle integration."""
from __future__ import annotations
import logging
import re
from typing import Any
import voluptuous as vol
from homeassistant.components.bluetooth import (
BluetoothServiceInfoBleak,
async_discovered_service_info,
)
from homeassistant.config_entries import ConfigFl... | caleb-venner/AquaBle | custom_components/aquable/config_flow.py | .py | f0f1a8ab673549d2 | 7.45 | 7 |
"""DataUpdateCoordinator for AquaBle devices."""
from __future__ import annotations
import asyncio
import logging
from datetime import timedelta
from typing import Any
from bleak import BleakClient
from bleak.exc import BleakError
from bleak_retry_connector import establish_connection
from homeassistant.components i... | caleb-venner/AquaBle | custom_components/aquable/coordinator.py | .py | bcbad12cc008e13e | 7.45 | 7 |
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass(slots=True)
class LightSchedule:
"""A single auto-program schedule decoded from a device status payload.
Corresponds to one entry added via create_add_auto_setting_command.
"""
sunrise_hour: int
sunrise_minut... | caleb-venner/AquaBle | custom_components/aquable/domain/light/status.py | .py | db0d11aaffeb3dfd | 7.45 | 7 |
"""Schedule calculation utilities for light devices."""
from datetime import datetime, time
def get_weekday_str() -> str:
"""Get the current day of the week as a lowercase string."""
return datetime.now().strftime("%A").lower()
def time_to_minutes(time_obj: time) -> int:
"""Convert a time object to min... | caleb-venner/AquaBle | custom_components/aquable/domain/schedules.py | .py | d662f13a6b5c44c5 | 7.45 | 7 |
"""Base entity for AquaBle."""
from __future__ import annotations
from homeassistant.const import CONF_NAME
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .config_flow import match_device_model
from .const import DOMAIN
from .c... | caleb-venner/AquaBle | custom_components/aquable/entity.py | .py | 1dcb1f8941e90f0c | 7.45 | 7 |
"""Build hook that ships the published JSON Schemas inside the wheel.
The migration loader validates against these at runtime, so an installed
``theurian`` that lacks them cannot read a migration at all.
The schemas live at the repository root because they are the shared contract
between Core and every client (ADR-00... | theurian/theurian | packages/theurian-core/hatch_build.py | .py | 45c91f1851956974 | 7.42 | 6 |
"""Rebuilding the review-finding store from git history (ADR-0029 phase-2 slice-2).
A **standalone** rebuild service, ``f(source) -> store``: it reads every
``Review-Finding:`` trailer a :class:`ReviewFindingSource` resolves and lands them
wholesale in a :class:`ReviewFindingStore`. Shaped like
:class:`~theurian.appli... | theurian/theurian | packages/theurian-core/src/theurian/application/findings_builder.py | .py | 1be009b45cc7add2 | 7.42 | 6 |
"""Source ingestion (FR-S1 .. FR-S6, ADR-0010).
Walks a project's knowledge directory, dispatches each file to a parser, and
normalizes the result into the Canonical Layer.
Two properties shape the design:
**Failure is per document.** A malformed YAML file among two hundred must not
make the other 199 unavailable, s... | theurian/theurian | packages/theurian-core/src/theurian/application/ingestion_service.py | .py | a03c1f90cd28358d | 7.42 | 6 |
"""Alias/item-id collision guard over a migration set (SEC-13, T-21).
A static, whole-set check that no ``addAlias`` key equals the id of an item whose
final status is anything but ``deprecated``. Pure function of a ``MigrationSet``:
it touches no store, opens no transaction, and reads nothing from disk.
``MigrationEn... | theurian/theurian | packages/theurian-core/src/theurian/application/migration_alias_guards.py | .py | bbbf237463a5455b | 7.42 | 6 |
"""Body-file guards over a migration set (issue #210).
The static, whole-set checks about how ``upsertRevision`` operations reference
their body files -- extracted from ``migration_engine`` to keep that module under
its size ceiling. Each is a pure function of a ``MigrationSet``: they touch no
store, open no transacti... | theurian/theurian | packages/theurian-core/src/theurian/application/migration_body_guards.py | .py | cdf28228a9f8c680 | 7.42 | 6 |
"""What a shared setup report may say about things Theurian did not write (O-3, SEC-6).
``doctor --report`` is redacted two ways, and only one of them lives in the CLI.
``cli/setup_commands._redacted`` substitutes the paths the local
:class:`SetupContext` holds -- an allowlist, so by construction it reaches only
value... | theurian/theurian | packages/theurian-core/src/theurian/application/setup_withholding.py | .py | d9f69e3068c9d087 | 7.42 | 6 |
"""``theurian auth`` — explicit token rotation (ADR-0011, SEC-4).
Rotation is a deliberate act and never a side effect. Setup mints a token only
when there is none, and nothing regenerates one silently, because replacing a
token breaks every configured client at once with no explanation.
The awkward part is that rota... | theurian/theurian | packages/theurian-core/src/theurian/cli/auth_commands.py | .py | ab2226c936e844fa | 7.42 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.