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 ipaddress
from typing import Any
class FilterModule:
@staticmethod
def ensure_domain(name: str, domain: str) -> str:
"""
Ensure that `name` ends with the given `domain`.
- If already a FQDN under `domain`, return unchanged.
- If no dot in name, append domain.
- ... | ednz-cloud/ansible-collection-hashistack | plugins/filter/ensure_domain.py | .py | 54d0a735663090ab | 7.52 | 10 |
"""Go2rtc client exceptions."""
from __future__ import annotations
from functools import wraps
from typing import TYPE_CHECKING, Any
from aiohttp import ClientError
from mashumaro.exceptions import (
ExtraKeysError,
InvalidFieldValue,
MissingDiscriminatorError,
MissingField,
SuitableVariantNotFou... | home-assistant-libs/python-go2rtc-client | go2rtc_client/exceptions.py | .py | 3bf563c253cd9767 | 7.42 | 6 |
"""Client library for go2rtc."""
from __future__ import annotations
from functools import lru_cache
import logging
from typing import TYPE_CHECKING, Any, Final, Literal
from aiohttp import ClientError, ClientResponse, ClientSession, ClientTimeout
from aiohttp.client import _RequestOptions
from awesomeversion import ... | home-assistant-libs/python-go2rtc-client | go2rtc_client/rest.py | .py | 926664f79cbaa8e3 | 7.42 | 6 |
"""Websocket client for go2rtc server."""
import asyncio
from collections.abc import Callable
import logging
from typing import TYPE_CHECKING, Any
from urllib.parse import urljoin
from aiohttp import ClientSession, ClientWebSocketResponse, WSMsgType
from go2rtc_client.exceptions import handle_error
from .messages i... | home-assistant-libs/python-go2rtc-client | go2rtc_client/ws/client.py | .py | 6ef1f98865e9a354 | 7.42 | 6 |
"""Go2rtc websocket messages."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Annotated, Any, ClassVar
from mashumaro import field_options
from mashumaro.config import BaseConfig
from mashumaro.mixins.orjson import DataClassORJSONMixin
from mashumaro.types import Dis... | home-assistant-libs/python-go2rtc-client | go2rtc_client/ws/messages.py | .py | 05b0cbcd20f0bf35 | 7.42 | 6 |
"""Asynchronous Python client for go2rtc."""
from pathlib import Path
from aiohttp import ClientTimeout
type RequestTimeouts = dict[tuple[str, str], list[ClientTimeout | None]]
def assert_request_timeout(
request_timeouts: RequestTimeouts,
method: str,
url: str,
*,
timeout: ClientTimeout | None... | home-assistant-libs/python-go2rtc-client | tests/__init__.py | .py | f097daa8abf43293 | 7.92 | 6 |
"""Asynchronous Python client for go2rtc."""
from collections.abc import AsyncGenerator
from typing import Any
from aiohttp import ClientSession
from aiointercept import aiointercept
import pytest
from syrupy import SnapshotAssertion
from go2rtc_client import Go2RtcRestClient
from . import URL, RequestTimeouts
from... | home-assistant-libs/python-go2rtc-client | tests/conftest.py | .py | f9fe24602ba5785b | 7.92 | 6 |
"""Asynchronous Python client for go2rtc."""
from __future__ import annotations
from dataclasses import asdict, is_dataclass
from typing import TYPE_CHECKING, Any
from syrupy.extensions import AmberSnapshotExtension
from syrupy.extensions.amber import AmberDataSerializer
if TYPE_CHECKING:
from syrupy.types impo... | home-assistant-libs/python-go2rtc-client | tests/syrupy.py | .py | 557002557308c997 | 7.92 | 6 |
#!/usr/bin/env python3
"""
Test wheel import functionality in isolation.
Tests that installed wheels work correctly without source code contamination.
"""
import sys
import os
def main():
"""Test wheel import functionality."""
print('=== Wheel Import Test ===')
print(f'Python: {sys.executable}')
print... | PlantSimulationLab/PyHelios | .github/scripts/test_wheel_import.py | .py | e2c67e7e226066db | 7.07 | 13 |
#!/usr/bin/env python3
"""
Wheel content validation script for PyHelios CI.
Validates that wheels contain both Python modules and native libraries.
"""
import zipfile
import sys
import os
from pathlib import Path
def validate_wheel(wheel_path):
"""Validate wheel contents."""
print(f"Validating: {Path(wheel_pa... | PlantSimulationLab/PyHelios | .github/scripts/validate_wheel.py | .py | 2b5856ad309d3dae | 7.57 | 13 |
"""
Shared output-directory helper for the PyHelios examples.
Examples that write files (images, movies, XML, text exports) put them under
``docs/examples/output/<name>/`` rather than the current working directory, so
running an example never scatters files across the project root. Everything an
example produces can b... | PlantSimulationLab/PyHelios | docs/examples/example_output.py | .py | 18ff78b33a7d8370 | 7.57 | 13 |
"""
PlantArchitecture File I/O Example
This example demonstrates the file input/output capabilities of the PlantArchitecture
plugin, including:
1. Saving and loading plant structures (XML format)
2. Exporting mesh vertices for external processing
3. Exporting TreeQSM cylinder format for biomechanical analysis
4. Commo... | PlantSimulationLab/PyHelios | docs/examples/plantarch_file_io_sample.py | .py | c11a9788e0c2cf40 | 7.57 | 13 |
"""Customize nested plant architecture (phytomer) parameters.
Demonstrates the typed parameter model: load a library species, pull its shoot
parameters as a typed object, mutate nested phytomer/leaf-prototype fields, define
a new shoot type, and build a plant that uses it. Also shows setting the flat
carbohydrate mode... | PlantSimulationLab/PyHelios | docs/examples/plantarch_phytomer_parameters_sample.py | .py | 7c1d291b203adf73 | 7.57 | 13 |
#!/usr/bin/env python3
"""
PlantArchitecture Plugin Sample
This example demonstrates the PyHelios PlantArchitecture plugin for procedural
plant modeling and plant library functionality. The PlantArchitecture plugin
provides access to 30 plant models with time-based growth simulation.
Requirements:
- PyHelios built wi... | PlantSimulationLab/PyHelios | docs/examples/plantarchitecture_sample.py | .py | dc712da46e569ab7 | 7.57 | 13 |
"""
PyHelios Primitive Data Example
Demonstrates the primitive data API for attaching user-defined key-value data to
geometric primitives.
Setters are type-specific -- there is no generic `setPrimitiveData()`. Pick the
setter matching the value you are storing:
setPrimitiveDataInt setPrimitiveDataUInt set... | PlantSimulationLab/PyHelios | docs/examples/primitive_data_sample.py | .py | 858ef849907cc0bb | 7.57 | 13 |
#!/usr/bin/env python3
"""
PyHelios Visualizer Demo
This example demonstrates the core functionality of the PyHelios Visualizer
plugin for 3D visualization of plant models and simulation results.
The example shows:
1. Basic Context and geometry creation
2. Tree generation using WeberPennTree
3. Interactive 3D visuali... | PlantSimulationLab/PyHelios | docs/examples/pyhelios_visualizer_demo.py | .py | a5091b0b80462eb7 | 7.57 | 13 |
#!/usr/bin/env python3
"""
PyHelios RadiationModel Camera Example: Spectrally-Resolved Apple Imagery
Renders a physically-based synthetic photograph of an apple tree and exports
per-apple YOLO bounding boxes -- the kind of dataset used to train fruit
detection and yield-estimation models.
What makes the image physica... | PlantSimulationLab/PyHelios | docs/examples/radiation_camera_example.py | .py | 8f7f019298844d25 | 7.57 | 13 |
"""
WeberPennTree Sample
Builds procedural trees and inspects their geometry:
1. Querying trunk / branch / leaf primitives separately
2. Controlling mesh detail with the resolution setters
The UUID accessors return lists of primitive IDs, which for a mature tree run to
tens of thousands of entries. This example repo... | PlantSimulationLab/PyHelios | docs/examples/wpt_sample.py | .py | 61654042b18244c1 | 7.57 | 13 |
"""
High-level BoundaryLayerConductanceModel interface for PyHelios.
This module provides a user-friendly interface to the boundary layer conductance modeling
capabilities with graceful plugin handling and informative error messages.
"""
import logging
from typing import List, Optional
from .plugins.registry import ... | PlantSimulationLab/PyHelios | pyhelios/BoundaryLayerConductance.py | .py | 31bc4ae8a26de6ed | 7.57 | 13 |
"""
Format output of `pacman -Qi ...` as a table having four columns (Name, Version, Dependency Of,
Description) string-separated fields using a user provided separator.
"""
import argparse
import re
import sys
from collections import defaultdict
_VAL_RE = re.compile(r"\s*([^:]+?)\s*:\s*(.*?)\s*")
_WS_RE = re.compi... | sumwale/ybox | src/ybox/conf/distros/arch/list_fmt_long.py | .py | 5acf4cb7d08a227c | 7.48 | 8 |
"""
Format output of `dpkg-query -W -f '${binary:Package}<sep>${Version}<sep>${Provides}<sep>\
${Pre-Depends}<sep>${Depends}<sep>${Recommends}<sep>${Suggests}<sep>${Description}\n\n'`
into four columns ${binary:Package}<sep>${Version}<sep>${Dependency Of}<sep>${Description}
where <sep> is a user provided separator.... | sumwale/ybox | src/ybox/conf/distros/deb-generic/list_fmt_long.py | .py | ebab0e0b4533bf99 | 7.48 | 8 |
"""
Defines some constants used by other modules.
"""
import re
from typing import Iterable
class Consts:
"""
Defines fixed file/path and other names used by ybox that are not configurable.
"""
# standard system executable paths
_SYS_BIN_DIRS = ("/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/lo... | sumwale/ybox | src/ybox/consts.py | .py | a3939493ecd7553e | 7.48 | 8 |
"""
Helper class for file locking with timeout support.
"""
import errno
import fcntl
import time
from datetime import datetime
from io import IOBase
class FileLock:
"""
A simple file locker class that takes an `fcntl()` lock on given file with polling and timeout.
The lock file should always be separate... | sumwale/ybox | src/ybox/filelock.py | .py | a81f1eeab05d2d27 | 7.48 | 8 |
"""
Utility classes and methods to print in color on terminal/console.
"""
import os
import shutil
import sys
from dataclasses import dataclass
from typing import IO
# define color names for printing in terminal
@dataclass(frozen=True)
class TermColors:
"""basic ASCII color strings for terminals"""
black: st... | sumwale/ybox | src/ybox/print.py | .py | a5d340be9a40b9de | 7.48 | 8 |
"""
Code for the `ybox-cmd` script that is used to execute programs in an active ybox container.
"""
import argparse
import os
import sys
from ybox.cmd import parser_version_check, populate_exec_cmdline, run_command
from ybox.env import get_docker_command
def main() -> None:
"""main function for `ybox-cmd` scri... | sumwale/ybox | src/ybox/run/cmd.py | .py | 7cabc57784536a7e | 7.48 | 8 |
"""
Code for the `ybox-launch` script that is used to launch an existing ybox container.
"""
import argparse
import os
import sys
from pathlib import Path
from ybox.cmd import parser_version_check, run_command
from ybox.consts import Consts
from ybox.env import Environ
from ybox.print import print_error, print_info
f... | sumwale/ybox | src/ybox/run/launch.py | .py | 34cbd60aa3954726 | 7.48 | 8 |
"""
Code for the `ybox-logs` script that is used to show the podman/docker logs of an active
ybox container.
"""
import argparse
import sys
from ybox.cmd import check_ybox_exists, parser_version_check, run_command
from ybox.env import get_docker_command
from ybox.print import print_info
def main() -> None:
"""m... | sumwale/ybox | src/ybox/run/logs.py | .py | a4874c5a0341365f | 7.48 | 8 |
"""
Code for the `ybox-ls` script that is used to show the active or stopped ybox containers.
"""
import argparse
import sys
from ybox.cmd import YboxLabel, parser_version_check, run_command
from ybox.env import Environ, get_docker_command
def main() -> None:
"""main function for `ybox-ls` script"""
main_ar... | sumwale/ybox | src/ybox/run/ls.py | .py | d1b5e5209b5a92b5 | 7.48 | 8 |
"""
Script to create a test database for migration tests for older versions of the product.
To use this script, checkout the older version of the product, then copy and run this
script from the top-level directory. Something like:
```
# for "v0.9.6" substitute the required version below
git clone -b v0.9.6 https://gi... | sumwale/ybox | tests/create_migration_db.py | .py | 0715b4db219812d5 | 7.98 | 8 |
"""Unit tests for `ybox/config.py`"""
import os
import subprocess
from pathlib import Path
import pytest
from ybox.config import StaticConfiguration as static_conf
from ybox.consts import Consts
from ybox.env import Environ
_TEST_DISTRIBUTION = "ybox-distro"
_TEST_CONTAINER = "ybox-test"
@pytest.fixture(name="env... | sumwale/ybox | tests/unit/test_config.py | .py | 4c1161a1977fe1f1 | 7.98 | 8 |
"""Unit tests for `ybox/filelock.py`"""
import errno
import fcntl
import multiprocessing
import os
import time
from datetime import datetime
from multiprocessing.context import ForkProcess
from multiprocessing.synchronize import Event
from pathlib import Path
from unittest.mock import patch
from uuid import uuid4
imp... | sumwale/ybox | tests/unit/test_filelock.py | .py | 300c674467d49fdd | 7.98 | 8 |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
from typing import Callable, Dict, Optional, Union
import fvcore.nn.weight_init as weight_init
from detectron2.layers import Conv2d, ShapeSpec, get_norm
from torch import nn
from torch.nn import functional as F
from ..transformer_decoder.position_encod... | UARK-AICV/GazeSearch | src/chestsearch/pixel_decoder/fpn.py | .py | 972785b553d7ea19 | 7.5 | 9 |
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import sys
# Import from sibling directory
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
from typing import Callable, Dict, List, Optional, Union
import fvcore.nn.weight_init as weight_init
import numpy as np
import torch
from detectr... | UARK-AICV/GazeSearch | src/chestsearch/pixel_decoder/msdeformattn.py | .py | 2df2f7c0142b2cd4 | 7.5 | 9 |
# Copyright (c) Facebook, Inc. and its affiliates.
# Modified by Bowen Cheng from: https://github.com/facebookresearch/detr/blob/master/models/detr.py
import logging
from typing import Optional
import fvcore.nn.weight_init as weight_init
import torch
from detectron2.config import configurable
from detectron2.layers im... | UARK-AICV/GazeSearch | src/chestsearch/transformer_decoder/mask2former_transformer_decoder.py | .py | 94aded5dab1cdef1 | 7.5 | 9 |
# Copyright (c) Facebook, Inc. and its affiliates.
# # Modified by Bowen Cheng from: https://github.com/facebookresearch/detr/blob/master/models/position_encoding.py
"""
Various positional encodings for the transformer.
"""
import math
import torch
from torch import nn
class PositionEmbeddingSine(nn.Module):
""... | UARK-AICV/GazeSearch | src/chestsearch/transformer_decoder/position_encoding.py | .py | 7a7fb05587648621 | 7.5 | 9 |
import datetime
import json
import os
class JsonConfig(dict):
"""
The configures will be loaded and dumped as json file.
The Structure will be maintained as json.
[TODO]: Some `asserts` can be make by key `__assert__`
"""
Indent = 2
def __init__(self, *argv, **kwargs):
super().__... | UARK-AICV/GazeSearch | src/common/config.py | .py | bc8784e04cba2a22 | 7.5 | 9 |
import matplotlib as mpl
import matplotlib.pylab as plt
import numpy as np
import torch
import torch.nn.functional as F
from torchvision.transforms import ToPILImage
from torchvision.utils import make_grid
mpl.rcParams["pdf.fonttype"] = 42
mpl.rcParams["ps.fonttype"] = 42
from scipy.stats import norm
def img_cortica... | UARK-AICV/GazeSearch | src/common/cort_magnif_tfm.py | .py | 1321b005816020fb | 7.5 | 9 |
import math
from typing import Optional, Tuple
import numpy as np
import torch
import torch.nn as nn
class PositionalEncoding2D(nn.Module):
"""
Helper Module that adds positional encoding to the token
embedding to introduce a notion of word order.
"""
def __init__(
self,
pa,
... | UARK-AICV/GazeSearch | src/common/position_encoding.py | .py | f085bf126bffa363 | 7.5 | 9 |
"""
.. Part of GazeParser package.
.. Copyright (C) 2012-2015 Hiroyuki Sogo.
.. Distributed under the terms of the GNU General Public License (GPL).
Evaluating simirality between two fixation sequences with ScanMatch algorithm,
proposed by Cristino, Mathot, Theeuwes and Gilchrist (2010).
Example
------------
Followin... | UARK-AICV/GazeSearch | src/common/scanmatch.py | .py | b7776bbebed7d778 | 7.5 | 9 |
import torch
import torch.nn as nn
import torch.nn.functional as F
# Adapted from https://github.com/gpeyre/SinkhornAutoDiff
class SinkhornDistance(nn.Module):
r"""
Given two empirical measures each with :math:`P_1` locations
:math:`x\in\mathbb{R}^{D_1}` and :math:`P_2` locations :math:`y\in\mathbb{R}^{D_... | UARK-AICV/GazeSearch | src/common/sinkhorn.py | .py | e5a888a2f6704b9c | 7.5 | 9 |
"""Registration information for OAuth2 providers."""
# ruff: file-ignore[hardcoded-password-func-arg]
from __future__ import annotations
from dataclasses import dataclass
__all__ = ('registrations',)
@dataclass
class Registration:
"""Generic data class for an OAuth2 provider."""
authorize_endpoint: str
... | Tatsh/mutt-oauth2 | mutt_oauth2/registrations.py | .py | dc2a2c1e760ad978 | 7.54 | 11 |
from __future__ import annotations
import numpy as np
from typing import Tuple
from tmg_hmc.utils import Array, to_scalar
from tmg_hmc.gpu_utils import _TORCH_AVAILABLE
from tmg_hmc.constraints.base import Constraint, pis, eps
import warnings
@Constraint.register
class LinearConstraint(Constraint):
r"""
Const... | erik-a-bensen/tmg_hmc | src/tmg_hmc/constraints/linear.py | .py | 8cf51d2d7b64e59e | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from collections.abc import Sequence, Mapping
from typing import Any
from .. import config
from ..database import Agent
from ..config_model.ai import AgentLike
async def get_sysprompt(id: s... | ECSDevs/QwenBotQ | qwenbotq/ai/tools.py | .py | c3ed74aeb67085c9 | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"The config module of QwenBotQ."
from pydantic import BaseModel
from yaml import safe_load
from nonebot import get_driver
from .ai import LLMConfig
from .database import DatabaseConfig
fro... | ECSDevs/QwenBotQ | qwenbotq/config_model/__init__.py | .py | 4f8f596cf026893f | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"大模型配置模型"
from pydantic import BaseModel
class AgentLike(BaseModel):
prompt: str
temperature: float = 1.0
frequency_penalty: float = 0.0
presence_penalty: float = 0.0
ma... | ECSDevs/QwenBotQ | qwenbotq/config_model/ai.py | .py | 666f0113cdb510c5 | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from collections.abc import Sequence, Callable, Awaitable
from motor.motor_asyncio import AsyncIOMotorClient
from nonebot.log import logger
from nonebot import get_driver
from beanie import D... | ECSDevs/QwenBotQ | qwenbotq/database/core.py | .py | af75a9ae015fb40f | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"已撤回图片读取进度数据模型"
from beanie import Document
from pydantic import Field
from .utils import noid
class RecallOffset(Document):
"已撤回图片读取进度(按超管用户记录)"
id: str = Field(default_factory=n... | ECSDevs/QwenBotQ | qwenbotq/database/recalloffset.py | .py | 9302f0220f2faa03 | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"撤回图片监听会话数据模型"
from beanie import Document
from pydantic import Field
from .utils import noid
class RecallSessions(Document):
"待监听的撤回图片会话ID集合"
id: str = Field(default_factory=noid... | ECSDevs/QwenBotQ | qwenbotq/database/recallsess.py | .py | 4c01e9f98abbdf3c | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"本子搜索结果状态数据模型(下一页依赖会话记忆)"
from beanie import Document
from pydantic import Field
from .utils import noid
class SearchState(Document):
"本子搜索结果状态(按会话ID记录)"
id: str = Field(default_f... | ECSDevs/QwenBotQ | qwenbotq/database/searchstate.py | .py | 46adc9f5a33791a8 | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"会话智能体绑定数据模型"
from beanie import Document
from pydantic import Field
from .utils import noid
class SessionAgent(Document):
"会话智能体绑定(按会话ID记录)"
id: str = Field(default_factory=noid)... | ECSDevs/QwenBotQ | qwenbotq/database/sessionagent.py | .py | d88040331c53aa4d | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"会话上下文(AI 对话历史)数据模型"
from beanie import Document
from pydantic import Field
from .utils import noid
class SessionContext(Document):
"会话持久化 AI 上下文(按会话ID记录)"
id: str = Field(default... | ECSDevs/QwenBotQ | qwenbotq/database/sessioncontext.py | .py | 178ccff4502b4719 | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from typing import Annotated
from datetime import datetime, date, timedelta
from pydantic import BaseModel, Field, field_validator
from beanie import Document
from .utils import noid
class... | ECSDevs/QwenBotQ | qwenbotq/database/user.py | .py | dcaa1864a5abdf2f | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from datetime import date, timedelta
from time import time
from pydantic import Field
from beanie import Document
from .utils import noid
# VIP 检查结果进程内缓存秒数(购买/续费时自动失效,容忍到期判定最多延迟一个 TTL)
_VIP... | ECSDevs/QwenBotQ | qwenbotq/database/vip.py | .py | f68c939b81a9b451 | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"图片缓存功能"
# standard imports
import asyncio
import os
import time
import zipfile
from os.path import isdir, isfile
from uuid import uuid4
# external imports
import httpx
from nonebot import g... | ECSDevs/QwenBotQ | qwenbotq/imagecache.py | .py | 0f3c4e4632ec377f | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"日志告警:将 WARNING 及以上级别日志自动转发到所有超管私聊"
# standard imports
import asyncio
from collections import deque
from time import time
# external imports
from nonebot import get_bot, get_driver
from none... | ECSDevs/QwenBotQ | qwenbotq/lognotice.py | .py | bc3e948fafbf0cfc | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"抽奖模块"
import re
from random import randint
from datetime import date, datetime, timedelta, time
from typing import Annotated
from arclet.alconna import Alconna, Args
from nonebot_plugin_alc... | ECSDevs/QwenBotQ | qwenbotq/lottery.py | .py | 84a098edcf6666f7 | 7.42 | 6 |
# Copyright (c) 2026 originalFactor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"从 models.dev 自动补全未填充的模型元数据"
from json import dump, load
from os import makedirs
from os.path import dirname, getmtime, isfile
from time import time
from typing import Any
from httpx import ... | ECSDevs/QwenBotQ | qwenbotq/models_dev.py | .py | 73c87744b0a3cb2b | 7.42 | 6 |
from typing import Tuple
import numpy as np
import tensorflow as tf
from ..logging import logger
class AnalysisData: # Parent used to create BayesianModel object
def __init__(
self,
x: np.ndarray,
nchunks: int = 128,
fmax_for_analysis: float = 128,
fs: float = 2048.0,
... | nz-gravity/sgvb_psd | src/sgvb_psd/backend/analysis_data.py | .py | 73df394c4a33a12a | 7.42 | 6 |
"""Module to compute the spectral density given the best surrogate posterior parameters and samples"""
import numpy as np
import tensorflow as tf
from typing import Tuple, List
from scipy.stats import median_abs_deviation
def compute_psd(
Xmat_delta:tf.Tensor,
Xmat_theta:tf.Tensor,
p_dim:int,
... | nz-gravity/sgvb_psd | src/sgvb_psd/backend/compute_psd.py | .py | 386986d302604280 | 7.42 | 6 |
from typing import Tuple
import numpy as np
import tensorflow as tf
from ..logging import logger
class EigenbasisAnalysisData:
def __init__(
self,
x: np.ndarray,
nchunks: int = 128,
fmax_for_analysis: float = 128,
fs: float = 2048.0,
N_theta: int = 15,
N_d... | nz-gravity/sgvb_psd | src/sgvb_psd/backend/eigenbasis_analysis_data.py | .py | 6809a920074fda91 | 7.42 | 6 |
import warnings
import matplotlib.pyplot as plt
import numpy as np
from typing import List, Optional
warnings.filterwarnings(
"ignore", message="Attempt to set non-positive ylim on a log-scaled axis"
)
def plot_psd(
psdq: List[np.ndarray],
true_psd: Optional[List[np.ndarray]] = None,
pdg... | nz-gravity/sgvb_psd | src/sgvb_psd/postproc/plot_psd.py | .py | 1fb6a545c510a348 | 7.42 | 6 |
import itertools
from typing import List, Optional
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import median_abs_deviation
def plot_triangle_psd_coherence(
psd_q: np.ndarray,
freqs: np.ndarray,
true_psd: Optional[np.ndarray] = None,
channel_labels: Optional[List[str]] = None,
... | nz-gravity/sgvb_psd | src/sgvb_psd/postproc/plot_triangle_psd_coherence.py | .py | e679915b847d9e63 | 7.42 | 6 |
import time
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
from hyperopt import fmin, hp, tpe
from .backend import (
BayesianModel,
EigenbasisViRunner,
FactorizedViRunner,
ViRunner,
)
from .logging import logger
from .postproc import plot_coherence
from .postproc.plot_loss... | nz-gravity/sgvb_psd | src/sgvb_psd/psd_estimator.py | .py | c4b06798dd74a0c8 | 7.42 | 6 |
from typing import Tuple
import numpy as np
from scipy import signal
from scipy.signal import csd
def get_periodogram(x, fs, **kwargs) -> Tuple[np.ndarray, np.ndarray]:
n, p = x.shape
x = x
periodogram = np.zeros((n // 2, p, p), dtype=complex)
for row_i in range(p):
for col_j in range(p):
... | nz-gravity/sgvb_psd | src/sgvb_psd/utils/periodogram.py | .py | dfa563021ffe308a | 7.42 | 6 |
import matplotlib.pyplot as plt
import numpy as np
from ..postproc.plot_psd import format_axes, plot_peridogram, plot_single_psd
from ..utils.periodogram import get_periodogram, get_welch_periodogram
class SimVARMA:
"""
Simulate Vector Autoregressive Moving Average (VARMA) processes and compute related spect... | nz-gravity/sgvb_psd | src/sgvb_psd/utils/sim_varma.py | .py | 1df6630312e7aedb | 7.42 | 6 |
"""Set up an environment to use to contribute to this package.
This script will run through the commands listed in the CONTRIBUTING.md file.
"""
from __future__ import annotations
import glob
import os
import platform
import shlex
import subprocess
import sys
from pathlib import Path
RUNNING_ON_LINUX = platform.sy... | tektronix/tm_data_types | scripts/contributor_setup.py | .py | d2fd8bfbccf82470 | 7.45 | 7 |
"""FastFrame multi-frame analog waveform types and TekHSI-compatible API."""
from __future__ import annotations
from typing import Any, TYPE_CHECKING
import numpy as np
from tm_data_types.datum.data_types import PossibleTypes, RawSample
from tm_data_types.datum.waveforms.analog_waveform import AnalogWaveform
from t... | tektronix/tm_data_types | src/tm_data_types/datum/waveforms/fastframe_analog_waveform.py | .py | 40bdda4c51da9a2c | 7.45 | 7 |
"""Shared FastFrame types and mixin logic for analog and digital waveforms."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, TYPE_CHECKING
from tm_data_types.helpers.enums import SummaryFrameType
if TYPE_CHECKING:
import numpy as np
@dataclass
class FrameTimingIn... | tektronix/tm_data_types | src/tm_data_types/datum/waveforms/fastframe_common.py | .py | 9670bfea17706a88 | 7.45 | 7 |
"""FastFrame multi-frame digital waveform types and TekHSI-compatible API."""
from __future__ import annotations
from typing import Any, TYPE_CHECKING
import numpy as np
from tm_data_types.datum.data_types import PossibleTypes, RawSample
from tm_data_types.datum.waveforms.digital_waveform import DigitalWaveform
fro... | tektronix/tm_data_types | src/tm_data_types/datum/waveforms/fastframe_digital_waveform.py | .py | 5378a199233529f2 | 7.45 | 7 |
"""Read and extract files from TSS (Tektronix Signal Suite) archives.
TSS files are ZIP archives containing waveform files (``.wfm``) and other associated files.
"""
import contextlib
import shutil
import sys
import tempfile
import zipfile
from collections.abc import Iterator
from pathlib import Path
from types impo... | tektronix/tm_data_types | src/tm_data_types/files_and_formats/tss/tss_reader.py | .py | fbf9326f2f0fb88f | 7.45 | 7 |
"""Helpers used to find what type of format needs to be used to write to/read from the file."""
from enum import Enum
from typing import Dict, List, Type
from tm_data_types.datum.datum import Datum
from tm_data_types.datum.waveforms.analog_waveform import AnalogWaveform
from tm_data_types.datum.waveforms.digital_wave... | tektronix/tm_data_types | src/tm_data_types/helpers/class_lookup.py | .py | c6380e49d76e2632 | 7.45 | 7 |
#!/usr/bin/env python3
"""Add a filled GND copper pour to a KiCad PCB, on whichever side is the better
ground layer.
Ergogen emits no copper zones, so the generated boards have no ground plane. A
pour gives the TVS data-line clamp a low-impedance return, a clean reference for
the split serial link, and auto-connects e... | andornaut/splinter-keyboard | scripts/add-gnd-zone.py | .py | c06f967a0f1a2191 | 7.45 | 7 |
#!/usr/bin/env python3
"""Add copper keepout rule areas to a KiCad PCB: two perimeter rings just inside
the board edge and a disk around each screw boss.
Three kinds of zone, all rule areas (keepouts) on F.Cu + B.Cu. Pads and
footprints stay allowed at the rule-area level (the rule-area pad keepout cannot
tell plated ... | andornaut/splinter-keyboard | scripts/add-keepout-zones.py | .py | 7e6991988ebfc17e | 7.45 | 7 |
#!/usr/bin/env python3
"""Idempotently ensure custom KiCad project settings (net class + DRC floors)
and the keepout DRC custom-rules file.
These live only in the .kicad_pro project JSON (not in the .kicad_pcb or the
ergogen config), so ergogen-generated and freshly-opened projects start without
them, plus a sibling `... | andornaut/splinter-keyboard | scripts/apply-project-settings.py | .py | a8c28504c4cf5126 | 7.45 | 7 |
#!/usr/bin/env python3
"""Delete the copper a finished route does not use, and merge what it split.
The generated footprints emit routing aids the finished routing does not always
use: with `include_traces_vias`, diode_sod123 (and r_0805, sod-123fl) puts a short
stub and a via at every pad, exposing that pad's net on ... | andornaut/splinter-keyboard | scripts/cleanup-tracks.py | .py | 898f4ce77bf24629 | 7.45 | 7 |
#!/usr/bin/env python3
"""Copy teardrop zones from a source PCB onto a destination PCB.
kb_ergogen_helper's `copy-traces` copies only PCB_TRACK objects (segments, arcs,
vias) via GetTracks(); teardrops are stored as ZONE objects (IsTeardropArea()),
so copy-traces alone never carries them across. This complements it: i... | andornaut/splinter-keyboard | scripts/copy-teardrops.py | .py | 717f6bdf8195cb68 | 7.45 | 7 |
"""Shared copper geometry: does anything touch this point, and may copper go here?
cleanup-tracks.py deletes the copper nothing connects to, and add-gnd-zone.py
must not score a pour layer on copper cleanup is about to delete. Both ask the
same question, so both ask it here and get the same answer.
tidy-slivers.py an... | andornaut/splinter-keyboard | scripts/lib/pcb_copper.py | .py | 2666976d30e42688 | 7.45 | 7 |
"""Shared helpers for the PCB provenance stamp.
The stamp is one string written into each generated PCB's title_block comment 1
at build time (see stamp-provenance.py) and checked by validate-provenance.py. Its
purpose is to detect when kicad/unrouted or kicad/routed have drifted from the
current ergogen config.yaml. ... | andornaut/splinter-keyboard | scripts/lib/provenance.py | .py | d7037595f75a13be | 7.45 | 7 |
"""The two board stages, and the argument every validator uses to scope itself.
`unrouted/` is where routing is done and `routed/` holds the masters fab exports
from. Every validator runs over both by default and takes an optional positional
argument naming one, so this is the vocabulary plus the wiring that reads it.... | andornaut/splinter-keyboard | scripts/lib/stages.py | .py | f271c6cbe64e2bd4 | 7.45 | 7 |
#!/usr/bin/env python3
"""Combine the routed boards into one JLCPCB panel with KiKit.
Lays the input boards out in a single left-to-right row inside a frame, joins
each board to the frame with mouse-bite tabs, and adds corner fiducials and
tooling holes for assembly. Each board's references and nets are prefixed with
... | andornaut/splinter-keyboard | scripts/panelize.py | .py | 44846074d67b606a | 7.45 | 7 |
#!/usr/bin/env python3
"""Translate a KiCad PCB so its Edge.Cuts bounding box is centered on the page.
Ergogen lays both halves out in one shared coordinate space, so each half's own
.kicad_pcb opens off to one side of the sheet. This recenters each board in its
own file. The applied translation is snapped to whole mi... | andornaut/splinter-keyboard | scripts/recenter.py | .py | c0f0a49eec3e0e81 | 7.45 | 7 |
#!/usr/bin/env python3
"""Autoroute a KiCad PCB with Freerouting via the Specctra DSN/SES round-trip.
Routes in place: reads and writes the given working .kicad_pcb (the kicad/unrouted/
copy). It deliberately never touches kicad/routed/ -- promoting a routed board is a
manual step (npm run copy:unrouted-to-routed).
T... | andornaut/splinter-keyboard | scripts/route.py | .py | a3c3db658b52f606 | 7.45 | 7 |
#!/usr/bin/env python3
"""Write the provenance stamp into a generated PCB's title block and silkscreen.
Sets title_block comment 1 to a stamp derived from the active config.yaml (see
provenance.py for the format), and also draws the stamp onto silkscreen (both
F.SilkS and B.SilkS) in the top corner on the pinky (outer... | andornaut/splinter-keyboard | scripts/stamp-provenance.py | .py | e5d30fed9baf97d3 | 7.45 | 7 |
#!/usr/bin/env python3
"""Collapse the segments a hand edit left that are shorter than they are wide.
Dragging a track in KiCad can leave a segment a few microns long where two runs
meet: a lateral jog between two nearly-collinear traces, or a stub between a via
and the run leaving it. It is copper the route does not ... | andornaut/splinter-keyboard | scripts/tidy-slivers.py | .py | 87edb1f043aba338 | 7.45 | 7 |
#!/usr/bin/env python3
"""Check the generated PCBs against each other and against the QMK firmware.
Two gates, because the MCU pin mapping is the one design error no other check in
this repo can see. A board whose matrix nets land on the wrong MCU header pin
is fully routed, shorts nothing, and passes provenance, DRC ... | andornaut/splinter-keyboard | scripts/validate-firmware.py | .py | 3ac5658729b7bca5 | 7.45 | 7 |
#!/usr/bin/env python3
"""Assert kicad/unrouted and kicad/routed were built from the current config.yaml.
Reads the provenance stamp (title_block comment 1) from every working board and
runs two checks over it. Either failing exits nonzero, and fab runs this as a gate.
CURRENT. Each board's config= hash must equal a ... | andornaut/splinter-keyboard | scripts/validate-provenance.py | .py | 8a529587abd549ff | 7.45 | 7 |
"""Pentair config flow."""
from __future__ import annotations
import logging
from typing import Any
from pypentair import Pentair, PentairAuthenticationError
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.d... | natekspencer/hacs-pentair | custom_components/pentair_cloud/config_flow.py | .py | cd84769fbe8673b5 | 7.63 | 17 |
"""Pentair coordinator."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
from deepdiff import DeepDiff
from pypentair import Pentair
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.... | natekspencer/hacs-pentair | custom_components/pentair_cloud/coordinator.py | .py | 4b0b3f58796b56b0 | 7.63 | 17 |
"""Pentair entities."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from homeassistant.helpers.entity import DeviceInfo, EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import PentairDeviceDataUpdateCoo... | natekspencer/hacs-pentair | custom_components/pentair_cloud/entity.py | .py | f23c7bda2422b2e1 | 7.63 | 17 |
"""Helpers."""
from __future__ import annotations
from datetime import datetime
import logging
from time import time
from typing import Any
from pypentair.utils import get_api_field_name_and_value
from homeassistant.util.dt import UTC
_LOGGER = logging.getLogger(__name__)
def convert_timestamp(_ts: float) -> dat... | natekspencer/hacs-pentair | custom_components/pentair_cloud/helpers.py | .py | 7c15b2cd5d3fd59a | 7.63 | 17 |
# MIT License
# Copyright Dave Lage (rockerBOO)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... | rockerBOO/sd-ext | clip_iqa.py | .py | 5ac610c024714b7c | 7.5 | 9 |
import argparse
from pathlib import Path
import torch
import re
from safetensors.torch import save_file
from safetensors import safe_open
def should_drop_key(key, patterns):
"""Check if a key should be dropped based on exact match, partial match, or regex."""
for pattern in patterns:
# Try exact match... | rockerBOO/sd-ext | drop_keys.py | .py | 7c6eeefc019f6a04 | 7.5 | 9 |
import argparse
import re
from safetensors import safe_open
from safetensors.torch import load_file, save_file
def convert_module_ids(
safetensors_file,
input_start_block,
input_end_block,
output_start_block,
output_file,
):
"""
Converts the module IDs of a Safetensors file from one block... | rockerBOO/sd-ext | flex_to_flux_lora.py | .py | c2d58d33879c6564 | 7.5 | 9 |
#!/usr/bin/env python3
import argparse
import re
import sys
import time
from pathlib import Path
import torch
from safetensors.torch import load_file, save_file
LOKR_SUFFIX_RE = re.compile(r"\.(lokr_w1|lokr_w1_a|lokr_w1_b|lokr_w2|lokr_w2_a|lokr_w2_b|alpha)$")
DEFAULT_RANK = 32
def get_device():
if torch.cuda.is... | rockerBOO/sd-ext | lokr_to_lora.py | .py | 36d3577216171149 | 7.5 | 9 |
from pathlib import Path
from typing import List, Union
import torch
from safetensors import safe_open
from safetensors.torch import save_file
def get_files(
file_or_dir: Union[str, Path, list[str], list[Path]],
file_ext: List[Union[str, Path]] = [],
recursive=True
) -> List[Path]:
files = []
if ... | rockerBOO/sd-ext | sd_ext/files.py | .py | c0aac2a8c2842e9b | 7.5 | 9 |
import torch
from safetensors.torch import save_file
from lokr_reduce import _svd_w2, apply_lokr_effective_rank, apply_lokr_svd, group_modules_lokr
def test_group_modules_lokr_full_format():
tensors = {
"diffusion_model.blocks.0.attn.wk.lokr_w1": None,
"diffusion_model.blocks.0.attn.wk.lokr_w2": ... | rockerBOO/sd-ext | test_lokr_reduce.py | .py | 950a0d96d9e116f3 | 7 | 9 |
import dataclasses
import datetime
from . import changeover
from . import tickers
from . import utils
@dataclasses.dataclass
class Split:
date: datetime.date
secid: str
mult: float
def get_splits() -> list[Split]:
"""Return all splits on moex"""
response = utils.json_api_call("https://iss.moex.... | kventinel/moexapi | moexapi/splits.py | .py | ff7a01c684a81645 | 7.42 | 6 |
#!/usr/bin/env python3
"""
make_isoquant_matrix.py
This script generates single-cell count matrices (Matrix Market Format) from spl-IsoQuant output.
It processes `*.allinfo` files, which contain read-to-isoform assignments and their classification (known/novel/etc.).
By default, the script mimics spl-IsoQuant's stric... | ConesaLab/SQANTI-single-cell | scripts/make_isoquant_matrix.py | .py | a391e7629551b665 | 7.48 | 8 |
#!/usr/bin/env python3
"""
make_pacbio_matrix.py
This script generates single-cell count matrices (Market Exchange Format) from PacBio Iso-Seq data.
It requires two inputs per sample:
1. `*.group.txt`: Output from Iso-Seq collapse (maps isoforms to molecules).
2. `*.bam`: Unmapped BAM (uBAM) containing deduplicated ... | ConesaLab/SQANTI-single-cell | scripts/make_pacbio_matrix.py | .py | fe548d055e94b108 | 7.48 | 8 |
#!/usr/bin/env python3
"""
process_ont_bam.py
This script processes ONT single-cell BAM files for SQANTI-sc.
It performs the following steps for each sample:
1. Runs `umi_tools dedup` with specific flags for ONT single-cell data.
2. Runs `spliced_bam2gff` to convert the processed BAM to GFF format.
Usage:
# Sin... | ConesaLab/SQANTI-single-cell | scripts/process_ont_bam.py | .py | a127168f20d90c41 | 7.48 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.