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
"""Small path-profile helpers shared by the MPC core and examples.""" import math def constant_speed_profile(course_x, target_speed): return [target_speed] * len(course_x) def smooth_yaw(yaw): for index in range(len(yaw) - 1): difference = yaw[index + 1] - yaw[index] while difference >= mat...
fanghaow/STTRL-DVO
mag_robot_nav/planners/mpc_utils.py
.py
fce05ad0ffce6f17
7.45
7
import argparse from copy import deepcopy import os from pathlib import Path from typing import Callable, Tuple import gymnasium as gym import numpy as np import torch as th from torch import nn from stable_baselines3 import PPO from stable_baselines3.common.callbacks import BaseCallback from stable_baselines3.common....
fanghaow/STTRL-DVO
scripts/train.py
.py
c90a3c118efa4c81
7.45
7
import math import torch import torch.nn as nn import torchrl.networks.init as init class STTRL_DVO_Backbone(nn.Module): def __init__( self, encoder, time_step, token_dim, state_input_shape, lidar_input_shape, transformer_params=(), append_hidden_shapes=(), appe...
fanghaow/STTRL-DVO
torchrl/networks/nets.py
.py
325fa23c451a17f3
7.45
7
from importlib import resources as impresources import importlib.util import inspect import os from pathlib import Path import pkgutil import shutil import subprocess import typer from typing import List, Tuple import brom_drake def generate_all_discoverable_docs( output_dir: Path, package_dir: Path = Path("...
kwesiRutledge/brom_drake-py
docs/generate_docs.py
.py
dbc71fb082474cbf
7.59
14
from importlib import resources as impresources import numpy as np from pathlib import Path from pydrake.all import ( RigidTransform, RollPitchYaw, Simulator, ) import subprocess import trimesh # Internal Imports from brom_drake.watchers.port_watcher.port_watcher_options import FigureNamingConvention from ...
kwesiRutledge/brom_drake-py
examples/productions/helpful_for_debugging/grasping/attempt_grasp/with_puppeteer_wrist/suggested_use2/attempt.py
.py
0420b3b67c0083b5
7.59
14
import sys from pathlib import Path import numpy as np import matplotlib.pyplot as plt # Drake imports from pydrake.all import ( RotationMatrix, RigidTransform, CoulombFriction, HalfSpace, RollPitchYaw, AddMultibodyPlantSceneGraph, Parser, AddModel, MultibodyPlant, DiagramBuild...
kwesiRutledge/brom_drake-py
examples/tutorial1/tutorial.py
.py
eeeec3220e478847
7.59
14
from pydrake.math import RollPitchYaw, RigidTransform, RotationMatrix from pydrake.multibody.math import SpatialVelocity from pydrake.multibody.parsing import Parser from pydrake.multibody.plant import MultibodyPlant, CoulombFriction from pydrake.multibody.tree import ModelInstanceIndex from pydrake.systems.framework i...
kwesiRutledge/brom_drake-py
src/brom_drake/control/ideal_joint_position_controller.py
.py
877b36816dd002c9
7.59
14
from importlib import resources as impresources from pydrake.math import RollPitchYaw, RigidTransform, RotationMatrix from pydrake.multibody.math import SpatialVelocity from pydrake.multibody.parsing import Parser from pydrake.multibody.plant import MultibodyPlant, CoulombFriction from pydrake.systems.framework import...
kwesiRutledge/brom_drake-py
src/brom_drake/example_helpers/block_handler_system.py
.py
1e8ce712a7ff4277
7.59
14
# Add flag to check if the first message is recieved and if not do nothing from launch import LaunchContext, LaunchDescription, Substitution from launch.actions import DeclareLaunchArgument, RegisterEventHandler, IncludeLaunchDescription from launch.conditions import IfCondition from launch.event_handlers import OnProc...
jhu-dvrk/dvrk_model
ros2/launch/dvrk_bringup.launch.py
.py
b74193fc20019e5e
7.54
11
import os import sys import textwrap import mypy.api def _add_line_numbers(s: str) -> str: lines = s.splitlines() width = len(str(len(lines))) return "\n".join( f"{i + 1:>{width}}| {line}" for i, line in enumerate(lines) ) def _format_mypy_output(source: str, stdout: str, stderr: str) -> st...
harrymander/dataclasses-struct
test/test_mypy_plugin.py
.py
5621fe093f79a461
7.16
20
from xme.xmetools import jsontools from xme.xmetools.texttools import replace_formatted from xme.xmetools.randtools import str_choice from xme.xmetools import dicttools from nonebot.message import Message from functools import lru_cache import config import os # from xme.xmetools.debugtools import debug_msg fr...
xzadudu179/XME-bot-qq
character.py
.py
3ed5631efe0cd1eb
7.63
17
__version__ = (1, 9, 1) import asyncio import logging from typing import Any, Optional, Callable, Awaitable import aiocqhttp from aiocqhttp import CQHttp from .log import logger from .sched import Scheduler if Scheduler: scheduler = Scheduler() else: scheduler = None class NoneBot(CQHttp): def __init...
xzadudu179/XME-bot-qq
nonebot/__init__.py
.py
3dc5320234e4b795
7.63
17
from argparse import ArgumentParser from .command import CommandSession class ParserExit(RuntimeError): """INTERNAL API""" def __init__(self, status=0, message=None): self.status = status self.message = message class ArgumentParser(ArgumentParser): """ An ArgumentParser wrapper tha...
xzadudu179/XME-bot-qq
nonebot/argparse.py
.py
fdae70c9363eb269
7.63
17
import re from nonebot import CommandSession from nonebot.helpers import render_expression def handle_cancellation(session: CommandSession): """ If the input is a string of cancellation word, finish the command session. """ def control(value): if _is_cancellation(value) is True: ...
xzadudu179/XME-bot-qq
nonebot/command/argfilter/controllers.py
.py
492b94ba77763aef
7.63
17
import re from typing import List from aiocqhttp.message import Message from nonebot.typing import Message_T def extract_text(arg: Message_T) -> str: """Extract all plain text segments from a message-like object.""" arg_as_msg = Message(arg) return arg_as_msg.extract_plain_text() def extract_image_url...
xzadudu179/XME-bot-qq
nonebot/command/argfilter/extractors.py
.py
2503f28d33e411b9
7.63
17
from typing import Union, Callable from nonebot.plugin import on_command from nonebot.typing import CommandHandler_T, CommandName_T class CommandGroup: """ Group a set of commands with same name prefix. """ __slots__ = ('basename', 'base_kwargs') def __init__(self, name: Union[str, CommandName_...
xzadudu179/XME-bot-qq
nonebot/command/group.py
.py
a1eff908c8cf3210
7.63
17
from datetime import datetime, time from typing import Any, Container from nonebot.permission import SenderRoles from nonebot.typing import PermissionPolicy_T def simple_allow_list(*, user_ids: Container[int] = ..., group_ids: Container[int] = ..., reverse: bool = False) -...
xzadudu179/XME-bot-qq
nonebot/experimental/permission.py
.py
e0fa68f94ed1aaf5
7.63
17
import asyncio import hashlib import random from typing import Callable, Iterable, List, Sequence, Any, Tuple from aiocqhttp.message import escape from aiocqhttp import Event as CQEvent from . import NoneBot from .exceptions import CQHttpError from .typing import Message_T, Expression_T def context_id(event: CQEven...
xzadudu179/XME-bot-qq
nonebot/helpers.py
.py
1b7ac1fefa3dbc24
7.63
17
import asyncio from typing import Any, Awaitable, Callable, Container, Dict, Iterable, NamedTuple, Optional, Union, List from aiocache.decorators import cached from aiocqhttp.event import Event as CQEvent from nonebot import NoneBot from nonebot.exceptions import CQHttpError from nonebot.helpers import separate_async...
xzadudu179/XME-bot-qq
nonebot/permission.py
.py
301d8d6c743ba70b
7.63
17
from PIL import Image, ImageDraw, ImageFont, ImageFilter import random random.seed() import math def gen_node_lines(node_xys: list[tuple], draw: ImageDraw, color, radius=1, width=1): # print(node_xys) for line in node_xys: # print(line) draw.line([line[0], line[1]], fill=color, width=w...
xzadudu179/XME-bot-qq
xme/plugins/archive/map_tools_archive.py
.py
27fc4c1b36130324
7.63
17
""" core/agent_mode.py — Agent mode dataclass for Supernova. Agent modes define what Supernova is focused on — a complete personality and toolset for a specific working context. Loaded from config/modes.yaml by ModeRegistry and stored on the session. Unlike InterfaceMode (which is fixed at session creation), agent mo...
JesseCake/supernova
core/agent_mode.py
.py
68a45da34084b692
7.45
7
""" core/interface_mode.py — Interface mode enum for Supernova. Defines the three interfaces a user can interact through. Set once at session creation by the interface, never changes during a session. Usage: from core.interface_mode import InterfaceMode # Set at session creation session['interface_mode']...
JesseCake/supernova
core/interface_mode.py
.py
83c6c5abb3f5f8fc
7.45
7
""" core/precontext.py — Personality file loader for Supernova. Loads agent mode personality files from the personality/ directory. Hot-reloads on file change so edits take effect without restart. Each agent mode has its own .md file defined in config/modes.yaml: general → personality/agent_general.md d...
JesseCake/supernova
core/precontext.py
.py
b36b656d7e706e90
7.45
7
import requests import os import json from datetime import datetime def get_current_weather(latitude, longitude): """Get the current weather in a given latitude and longitude""" base = "https://api.openweathermap.org/data/2.5/weather" key = os.environ['WEATHERMAP_API_KEY'] request_url = f"{base}?lat={latitude...
JesseCake/supernova
functions.py
.py
732401151e790e94
7.45
7
""" vad.py — Lean Silero VAD wrapper, numpy + ONNX only. Drops the torch dependency entirely. The ONNX runtime takes numpy arrays directly; the original whisper-live wrapper converted numpy → torch → numpy purely as an artefact of the upstream utility code it was based on. Public API is backwards-compatible with the ...
JesseCake/supernova
interfaces/vad.py
.py
89d109e883590266
7.45
7
#!/usr/bin/env python3 """ Speaker enrollment script for Supernova. Records or loads audio samples and saves speaker embeddings to config/speaker_profiles.json for use by the real-time speaker identifier. Usage: # Enroll from an existing audio file (WAV, recommended 5-10s of clean speech): python3 scripts/enr...
JesseCake/supernova
scripts/enroll_speaker.py
.py
2475ded9e3de286b
7.45
7
#!/usr/bin/env python3 """ Simple voice recording utility for speaker enrollment (if using this machine). Records audio from the default microphone and saves it as a WAV file. Usage: python3 scripts/record_sample.py --out samples/jesse.wav python3 scripts/record_sample.py --out samples/jesse.wav --duration 8 ...
JesseCake/supernova
scripts/record_sample.py
.py
97c9a38ba65b5c03
7.45
7
class Config: """Module-level configuration for ``device-smi``.""" def __init__(self): # A TTL of 0 disables the nvidia-smi cache entirely so every call # runs the subprocess. Set it >0 to enable caching. self._nvidia_smi_cache_ttl = 0.0 self._nvidia_smi_cache_maxsize = 16 ...
ModelCloud/Device-SMI
device_smi/config.py
.py
2280c66c96f93c44
7.62
16
import time import pytest from device_smi.device import Device class DummyDevice: """A minimal fake device that pretends to provide metrics.""" fast_metrics_same_as_slow = False def __init__(self, parent): self.parent = parent self._counter = 0 def metrics(self): self._coun...
ModelCloud/Device-SMI
tests/test_close.py
.py
76894d8fb8c84865
8.12
16
#!/usr/bin/env python3 """Weekly profile README updater — auto-runs every Sunday via GitHub Actions.""" import re from datetime import date START_DATE = date(2026, 6, 15) # ── 12 deep-research missions (cycles through the year) ───────────────────── # (title, quest, stack, topics, quote, difficulty_bar, gif_url) MISS...
mdnuruzzamanKALLOL/mdnuruzzamanKALLOL
update_weekly.py
.py
9f1ab7b1ba57c734
7.52
10
"""TUI 内嵌 MCP 服务:向 agent 暴露设备控制工具(截图/点击/滑动/拖动)。 服务随 TUI 启动在后台 daemon 线程运行,streamable-http 传输, agent 经 http://127.0.0.1:{port}/mcp 连接。 """ import json import logging import os import cv2 import numpy as np from mcp.server import MCPServer from mcp.server.mcpserver.utilities.types import Image from jczx.configEntity i...
Amber-siley/JCZXAutoScript
jczx/mcpServer.py
.py
3d6b7bc683a23a9f
7.63
17
"""方案 2 harness:FakeDevice 桩替身,object.__new__ 绕过 ADB(避免 ready_env 联网下载)。""" import logging from copy import deepcopy from types import SimpleNamespace import numpy as np from jczx.CommonBuilder.CommonBuilder.Android.Adb import MatchTemplete from jczx.jczxCli import JCZXGaming, PlaceholderResolver, ScreenshotCache fro...
Amber-siley/JCZXAutoScript
tests/engine/fake_device.py
.py
f203818f1c9a5b96
8.13
17
"""方案 2:exec_match — action 变换、级联搜索外扩区域、标注时机(on_match 收到变换后点)。 使用真实配置 receive.txt 中的通用 method+call 实体: if-around-click method:params base,neighbor;neighbor 默认 locations\hasNew.png match-around-10 匹配 %{base} 后边向外扩 10px(up-M|10,down-M|10,left-M|10,right-M|10) matched-around 级联:在 match-around-10 区域搜...
Amber-siley/JCZXAutoScript
tests/engine/test_exec_match.py
.py
d2f19c369042f42c
8.13
17
"""ScreenAnnotator 标注坐标扩展:点击/滑动标注应产生像素变化(标注生效)。""" import numpy as np from jczx.debug.annotator import ScreenAnnotator class TestAnnotatorCoordinates: def test_draw_click_marks_image(self): img = np.zeros((100, 100, 3), np.uint8) out = img.copy() ScreenAnnotator.draw_click(out, 30, 40) ...
Amber-siley/JCZXAutoScript
tests/pure/test_annotator.py
.py
4c79eec9713fc8fc
8.13
17
"""方案 1(纯逻辑):configEntity 类型强转 / list 拆分 / 占位符保留 / SectionType。""" from jczx.configEntity import JczxSectionEntity, SectionType class TestSetAttrCoercion: """BaseEntity.__setattr__ 的类型强转逻辑。""" def test_str_to_int(self): e = JczxSectionEntity() e.times = "3" assert e.times == 3 ...
Amber-siley/JCZXAutoScript
tests/pure/test_config_entity.py
.py
eed593fef6c75ec2
8.13
17
from talon import Module, actions from ..src.core.entity_manager import entity_manager from .hello_world.hello_world_ui import hello_world_ui from .todo_list.todo_list_ui import todo_list_ui from .alignment.alignment_ui import alignment_ui from .state_tests.state_tests_ui import state_tests_ui from .cheatsheet.ch...
rokubop/talon-ui-elements
examples/_tests.py
.py
35dde3389f4b4c51
7.09
14
from talon import actions def actions_ui(): """ Display buttons to perform actions on the UI elements for testing. Expects state to be set such as: ``` actions.user.ui_elements_set_state("actions", [{ "text": 'Set background Color: 456456', "action": lambda: actions.user....
rokubop/talon-ui-elements
examples/actions/actions_ui.py
.py
8f0c014a9331eb98
7.59
14
from talon import Module, Context mod = Module() ctx = Context() ctx_hints_active_browser = Context() # Import after creating ctx so src/hints can access it from .src.hints import ( trigger_hint_click, trigger_hint_focus, focus_next, focus_previous, set_hint_context, show_scale_no...
rokubop/talon-ui-elements
hints_and_keys.py
.py
2b4d322fc5ac24ac
7.59
14
from weakref import WeakMethod from talon.canvas import Canvas class CanvasWeakRef: """ A lightweight wrapper for Talon's Canvas that uses weak references for event callbacks e.g. 'draw', 'mouse', and 'scroll', ensuring proper garbage collection for bound method like self.on_draw (Otherwise ...
rokubop/talon-ui-elements
src/canvas_wrapper.py
.py
1979fa6d2fa65673
7.59
14
import os import platform from talon.skia.typeface import Typeface weight_keywords = { "regular": ["regular", ""], "light": ["light", "thin", "extralight"], "medium": ["medium"], "semibold": ["semibold", "demibold"], "bold": ["bold", "extrabold", "heavy"], "black": ["black"], } pr...
rokubop/talon-ui-elements
src/fonts.py
.py
7f3f3484392f06b8
7.59
14
from talon import cron, settings, registry, actions from talon.skia.canvas import Canvas as SkiaCanvas from talon.skia import RoundRect from talon.types import Rect from .utils import scale_value from .core.state_manager import state_manager from .core.store import store from .interfaces import NodeType, ClickEv...
rokubop/talon-ui-elements
src/hints.py
.py
e44a5c6b4c2c50e4
7.59
14
from talon import actions, clip, cron from ..constants import ELEMENT_ENUM_TYPE from ..properties import NodeCodeProperties, validate_combined_props from .node_code import NodeCode from .component import Component CODE_ONLY_PROPS = { "language", "theme", "diff", "selectable", "selection_color", "font_family", ...
rokubop/talon-ui-elements
src/nodes/code.py
.py
901a63069d3bcd10
7.59
14
import inspect import weakref from typing import List from ..core.state_manager import state_manager from ..style import Style from ..interfaces import NodeType, TreeType, ComponentType class Component(ComponentType): """ Has it's own renderer for containing rerenders, state, and styles. """ ...
rokubop/talon-ui-elements
src/nodes/component.py
.py
c4bd33ecf299f6af
7.59
14
import traceback import weakref from ..core.state_manager import state_manager from .component import Component class ErrorBoundary(Component): """Component that renders a fallback error card instead of propagating exceptions raised by its renderer. The rest of the tree continues to render normally.""" ...
rokubop/talon-ui-elements
src/nodes/error_boundary.py
.py
aec43f486ae79525
7.59
14
from talon.skia.paint import Paint from talon.types import Rect from .node_text import NodeText from ..properties import NodeCodeProperties from ..syntax import ( tokenize, tokenize_line, resolve_theme, TOKEN_TEXT, TOKEN_DIFF_ADD, TOKEN_DIFF_ADD_BG, TOKEN_DIFF_REMOVE, TOKEN_DIFF_REMOVE_BG, TOKEN_DIFF_HU...
rokubop/talon-ui-elements
src/nodes/node_code.py
.py
2ea5044c04adcc4b
7.59
14
"""PocketSmith Integration.""" import logging from datetime import timedelta from homeassistant.core import HomeAssistant from homeassistant.config_entries import ConfigEntry from homeassistant.helpers import config_validation as cv from .actions import async_register_actions, async_unregister_actions from .backfill ...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/__init__.py
.py
af7d51bdfb4604c4
7.45
7
"""HA actions (services) for the PocketSmith integration.""" import logging from homeassistant.core import HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse from homeassistant.helpers.storage import Store from .backfill import async_trigger_backfill from .const import DOMAIN from .repairs import clear_bac...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/actions.py
.py
3248996a564001b2
7.45
7
"""PocketSmith binary sensor platform.""" import logging from homeassistant.components.binary_sensor import BinarySensorDeviceClass, BinarySensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import EntityCategory from homeassi...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/binary_sensor.py
.py
d7c36260615c70fb
7.45
7
"""PocketSmith button platform.""" import logging from homeassistant.components.button import ButtonEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntit...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/button.py
.py
1580a10d7adbfc58
7.45
7
"""Config flow for PocketSmith.""" import asyncio import logging import aiohttp import voluptuous as vol from homeassistant import config_entries from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import ( CONF_ENABLE_BACKFILL, CONF_UPDATE_INTERVAL_HOURS, DEFAULT_ENABLE_B...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/config_flow.py
.py
de1391185eabb2a0
7.45
7
"""Constants for the PocketSmith integration.""" from dataclasses import dataclass, field DOMAIN = "ha_pocketsmith" CONF_UPDATE_INTERVAL_HOURS = "update_interval_hours" CONF_ENABLE_BACKFILL = "enable_backfill" CONF_ACTIVE_CURRENCY = "active_currency" DEFAULT_UPDATE_INTERVAL_HOURS = 1 DEFAULT_ENABLE_BACKFILL = True D...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/const.py
.py
c5c9eb18c69215d7
7.45
7
"""PocketSmith number platform — polling interval control.""" import logging from homeassistant.components.number import NumberDeviceClass, NumberEntity, NumberEntityDescription, NumberMode from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.devi...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/number.py
.py
722ed28962b0202c
7.45
7
"""Repair issue helpers for the PocketSmith integration.""" import logging from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue, async_delete_issue from homeassistant.core import HomeAssistant from .const import DOMAIN _LOGGER = logging.getLogger(__name__) ISSUE_UNCATEGORISED = "uncate...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/repairs.py
.py
6782ab43e4b1426f
7.45
7
"""PocketSmith select platform — active currency for Net Worth sensor.""" import logging from homeassistant.components.select import SelectEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntryType, DeviceIn...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/select.py
.py
06f91804706587c5
7.45
7
"""System health for the PocketSmith integration.""" from typing import Any from homeassistant.components import system_health from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from .const import DOMAIN @callback def async_register(hass: HomeAssistant, regis...
cloudbr34k84/home-assistant-pocketsmith
custom_components/ha_pocketsmith/system_health.py
.py
daa85ab5ce536d06
7.45
7
"""Error classes.""" from __future__ import annotations __all__ = [ "JsonSchemaExtensionError", "LoaderNotFoundError", "SchemaFileNotFoundError", ] class JsonSchemaExtensionError(Exception): """Base class for all JSON Schema extension errors.""" class LoaderNotFoundError(JsonSchemaExtensionError):...
copier-org/jinja2-jsonschema
src/jinja2_jsonschema/errors.py
.py
b85624f393465889
7.56
12
"""Test configuration.""" from __future__ import annotations from collections.abc import Callable from contextlib import closing from functools import partial from http.server import SimpleHTTPRequestHandler from pathlib import Path from socket import SOCK_STREAM from socket import socket from socketserver import TCP...
copier-org/jinja2-jsonschema
tests/conftest.py
.py
ad5bc4a8c28e4c8a
8.06
12
"""Tests for using inline schemas.""" from __future__ import annotations from typing import Any import pytest from tests.utils import SCHEMA from tests.utils import create_env from .utils import TEST_CASES @pytest.mark.parametrize(("data", "message"), TEST_CASES) def test_basic(data: Any, message: str) -> None: ...
copier-org/jinja2-jsonschema
tests/filter/test_inline.py
.py
93feebcd943f39cf
7.06
12
"""Tests for using inline schemas.""" from __future__ import annotations from typing import Any import pytest from tests.utils import SCHEMA from tests.utils import create_env from .utils import TEST_CASES @pytest.mark.parametrize(("data", "message"), TEST_CASES) def test_basic(data: Any, message: str) -> None: ...
copier-org/jinja2-jsonschema
tests/test/test_inline.py
.py
6337440cbe007206
7.06
12
"""Tests for adding the extension to the Jinja2 environment.""" from __future__ import annotations from re import escape from typing import Any import pytest from jinja2 import Environment from jinja2.ext import Extension from jinja2_jsonschema import JsonSchemaExtension def test_filter_name_conflict() -> None: ...
copier-org/jinja2-jsonschema
tests/test_extension.py
.py
9121b126899c3262
7.06
12
"""Testing utilities.""" from __future__ import annotations import json from textwrap import dedent from typing import TYPE_CHECKING from typing import Any from typing import Literal import yaml from jinja2 import Environment from jinja2 import FileSystemLoader from jinja2_jsonschema import JsonSchemaExtension if ...
copier-org/jinja2-jsonschema
tests/utils.py
.py
74222c9ce1ab2360
8.06
12
""" Module for validate and formatted parameters """ import logging import os from urllib.parse import urlparse import urllib3 import validators from backend._http import requests logger = logging.getLogger(__name__) def verify_tls() -> bool: """ Whether outbound HTTPS calls should verify the TLS certificate "...
denimoll/dt-report-generator
backend/param_validators.py
.py
a5db87121338117d
7.52
10
""" Forms """ import os from flask_wtf import FlaskForm from wtforms import ( BooleanField, PasswordField, SelectField, StringField, SubmitField, validators, ) # Sentinel render_kw applied to URL/Token when the corresponding DTRG_* # env var is set, so the form makes it visible that an admin...
denimoll/dt-report-generator
form.py
.py
1fe0f80afbd5ebec
7.52
10
""" Tests for form.GetReportForm """ import app as app_module from form import GetReportForm def _form_in_context(): """ FlaskForm needs an app context to render """ with app_module.app.test_request_context("/"): return GetReportForm() def test_url_field_writable_when_env_unset(monkeypatch): mo...
denimoll/dt-report-generator
tests/test_form.py
.py
7b0302539be21797
8.02
10
""" Tests for backend.param_validators """ from unittest.mock import MagicMock, patch import pytest import requests from backend import param_validators as pv # verify_tls / http_timeout def test_verify_tls_default_true(monkeypatch): monkeypatch.delenv("DTRG_VERIFY_TLS", raising=False) assert pv.verify_tl...
denimoll/dt-report-generator
tests/test_param_validators.py
.py
1c743ec9c2fa0cb9
8.02
10
class DownloaderError(Exception): """Base exception for user-facing downloader failures.""" class ValidationError(DownloaderError): """The supplied URL is not a supported public episode URL.""" class ParseError(DownloaderError): """Episode metadata could not be extracted from the public page.""" class...
david-bowiegxw/xiaoyuzhoufmdownload
xiaoyuzhou_downloader/errors.py
.py
ef984d92b4b575b3
7
9
""" Configuration for the FOLIO (Federated Open Legal Information Ontology) Python library. """ # annotations from __future__ import annotations # imports import json from pathlib import Path from typing import Literal, Optional # packages from pydantic import BaseModel, ConfigDict, Field # project imports from fol...
alea-institute/folio-python
folio/config.py
.py
63ce087ac620f28f
7.56
12
""" This module contains the OWLClass model and related pydantic models for the FOLIO package. """ # pylint: disable=fixme,no-member,unsupported-assignment-operation,too-many-lines,too-many-public-methods # imports from typing import Dict, List, Optional, Any # packages import lxml.etree from pydantic import BaseMod...
alea-institute/folio-python
folio/models.py
.py
23b9a52f9023f712
7.56
12
"""Tests for folio.iri, the concept IRI generator. folio.iri imports only the standard library, so these run without network access, without a FOLIO graph, and without the optional search extras. """ # SPDX-License-Identifier: MIT # (c) 2024 ALEA Institute. import re import pytest from folio.iri import ( BASE6...
alea-institute/folio-python
tests/test_iri.py
.py
bcd3fc76987fc2e9
8.06
12
"""Launch one isolated process group per (preset, strategy), then aggregate + plot. Every combination gets its own process. Two reasons, both learned by failure: * Mixing DDP's collective communicators with the pipeline's lazily-created P2P communicators inside one process throws an internal NCCL error, even though...
KohakuBlueleaf/KohakUwULLM
scripts/bench/_archive/e2e_driver.py
.py
cdfe696964886b79
7.52
10
"""Data pipeline throughput: is the loader ever going to be the bottleneck? Three questions, because they have different answers and different fixes: 1. **Raw record reads.** KohakuVault random-access rate against DataLoader worker count, local NVMe vs NFS. Random reads over NFS are latency-bound, not bandwidth...
KohakuBlueleaf/KohakUwULLM
scripts/bench/data/data.py
.py
4658cec29d092cab
7.52
10
"""Scaling curves for the Kohaku 4-card sweep, judged by correlation not by slope. Bars across rungs answer nothing -- of course 1.5B is slower than 200M. The question is whether **one** power law describes the whole ladder, so every panel is log-log with a fitted exponent *and* an r2, and the r2 is the verdict. Why ...
KohakuBlueleaf/KohakUwULLM
scripts/bench/e2e/kohaku_e2e_plot.py
.py
2b6dc7c185018d94
7.52
10
"""Report the Kohaku 4-card sweep in planning units: B tokens/day and steps/day. tok/s answers "is this kernel fast"; a run is planned in days and checkpointed in steps, and the conversion is where an hour of arithmetic gets done by hand and gets done wrong. Row loading and the clean/contended/oom verdict come from :...
KohakuBlueleaf/KohakUwULLM
scripts/bench/e2e/kohaku_e2e_table.py
.py
ad42fd4cfc5b77c0
7.52
10
"""Microbatch-count sweep: bubble rate against fixed per-boundary latency. .venv/bin/python scripts/bench/e2e/pp_micro_sweep.py """ import os import time import torch import torch.distributed as dist from torch.distributed.launcher.api import LaunchConfig, elastic_launch from kohakuwullm.models import get_preset fr...
KohakuBlueleaf/KohakUwULLM
scripts/bench/e2e/pp_micro_sweep.py
.py
9fb5fbe34ad66eab
7.52
10
"""Time one pipeline stage's compute in isolation, with no communication. Separates stage compute from pipeline overhead: if the sum of per-stage times is already close to the observed step time, the schedule is not the problem. .venv/bin/python scripts/bench/e2e/pp_phase.py """ import os import time import tor...
KohakuBlueleaf/KohakUwULLM
scripts/bench/e2e/pp_phase.py
.py
3c0bbf8d7b2ff20a
7.52
10
"""The Kohaku preset ladder, measured: does it hit its design targets? Nine rungs, dense and sparse interleaved, whose effective capacities ``sqrt(active * total)`` were solved to sit on one smooth sequence. This script does not trust that solve. Every count comes from a real ``LMBackbone`` built on ``torch.device("me...
KohakuBlueleaf/KohakUwULLM
scripts/bench/e2e/presets.py
.py
05e064f396494d51
7.52
10
"""Draw the four Kohaku-ladder figures from ``presets.json``. Split from the census half for the same reason as ``kernels.py`` / ``kernels_plot.py``: a rejected layout should not force a re-count, and the JSON is then the one table every figure is reachable from. Each figure answers one question about the ladder: 1....
KohakuBlueleaf/KohakUwULLM
scripts/bench/e2e/presets_plot.py
.py
675576936aaa48e8
7.52
10
"""Draw the MXFP8 size- and token-scaling result. Split from the measurement for the reason the repo splits every bench: the runs cost GPU time and a rejected figure should not cost them again. The layout argues one claim in the order the evidence supports it. **What gates MXFP8 is device work per launch**, and model...
KohakuBlueleaf/KohakUwULLM
scripts/bench/fp8/fp8_sizes_plot.py
.py
c730387c52c25756
7.52
10
"""Does MXFP8 cost stability margin? bf16 vs round-up across multiples of the base lr. The main A/B answers "does fp8 track bf16 on the shipped recipe" and it can only answer it at 651.8M tokens. The published MX divergence appeared at 300B, which this hardware cannot reach, so the limitation is real and a longer run ...
KohakuBlueleaf/KohakUwULLM
scripts/bench/fp8/fp8_stability_plot.py
.py
f23422edb25ad509
7.52
10
""" Simple implementation of the Ayla networks API Some devices use the Ayla networks IoT API integration to provide IoT functionality to the device. Documentation can be found at: - https://developer.aylanetworks.com/apibrowser/ - https://docs.aylanetworks.com/cloud-services/api-browser/ """ from aiohttp import...
rewardone/ayla-iot-unofficial
src/ayla_iot_unofficial/ayla_iot_unofficial.py
.py
249e812677c6a277
7.52
10
"""Exceptions""" # Default messages AUTH_EXPIRED_MESSAGE = 'Ayla Networks API authentication expired. Re-authenticate and retry.' AUTH_FAILURE_MESSAGE = 'Error authenticating to Ayla Networks.' NOT_AUTHED_MESSAGE = 'Ayla Networks API not authenticated. Authenticate first and retry.' class AylaError(RuntimeError)...
rewardone/ayla-iot-unofficial
src/ayla_iot_unofficial/exc.py
.py
f29acdb4edc01347
7.52
10
import pytest import os from src.ayla_iot_unofficial.ayla_iot_unofficial import new_ayla_api from datetime import datetime, timedelta @pytest.fixture def dummy_api(): """AylaApi object with invalid auth creds and attributes populated.""" username = "myusername@mysite.com" password = "mypassword" dummy...
rewardone/ayla-iot-unofficial
tests/conftest.py
.py
c9df1cd4069e0617
8.02
10
import logging import sys import orjson import structlog from structlog.stdlib import BoundLogger def setup_logging(): log_level = logging.INFO structlog.configure( cache_logger_on_first_use=True, wrapper_class=structlog.make_filtering_bound_logger(log_level), processors=[ ...
bralbral/fastapi_aiogram_template
src/logger.py
.py
f8817eb3efcd9712
7.5
9
# pylint: disable=abstract-method import typing import edq.net.request import lms.backend.blackboard.model import lms.model.backend import lms.model.constants import lms.model.courses import lms.model.users import lms.util.net import lms.util.parse class BlackboardBackend(lms.model.backend.APIBackend): """ An A...
edulinq/lms-toolkit
lms/backend/blackboard/backend.py
.py
f7b9632064c69806
7.6
15
import re import typing import lms.model.courses import lms.model.users COURSE_ROLE_MAPPING: typing.Dict[str, lms.model.users.CourseRole] = { 'Guest': lms.model.users.CourseRole.OTHER, 'Student': lms.model.users.CourseRole.STUDENT, 'Grader': lms.model.users.CourseRole.GRADER, 'TeachingAssistant': lms....
edulinq/lms-toolkit
lms/backend/blackboard/model.py
.py
f8587d2a9df642e7
7.6
15
import os import typing import edq.testing.cli import lms.backend.canvas.backend import lms.backend.testing import lms.model.constants THIS_DIR: str = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) ROOT_DIR: str = os.path.join(THIS_DIR, '..', '..', '..') CANVAS_TEST_EXCHANGES_DIR: str = os.path.join(R...
edulinq/lms-toolkit
lms/backend/canvas/backend_test.py
.py
490cb3c990f4ba99
8.1
15
import datetime import http import re import typing import html2text import edq.net.request import edq.util.json import edq.util.time import requests DEFAULT_PAGE_SIZE: int = 95 HEADER_LINK: str = 'Link' def fetch_next_canvas_link(response: requests.Response) -> typing.Union[str, None]: """ Fetch the Canvas...
edulinq/lms-toolkit
lms/backend/canvas/common.py
.py
9567fb3648afb98b
7.6
15
import typing import edq.net.request import requests import lms.backend.blackboard.backend import lms.backend.canvas.backend import lms.backend.moodle.backend import lms.model.config import lms.model.constants import lms.model.backend def get_backend( config: lms.model.config.Config, **kwargs: typing...
edulinq/lms-toolkit
lms/backend/instance.py
.py
2aaf9734bd36fa69
7.6
15
# pylint: disable=abstract-method import logging import typing import urllib.parse import bs4 import edq.net.request import requests import lms.model.backend import lms.model.constants import lms.util.net _logger = logging.getLogger(__name__) ROLE_MAPPING: typing.Dict[str, lms.model.users.CourseRole] = { "gues...
edulinq/lms-toolkit
lms/backend/moodle/backend.py
.py
0e4ae769434e474b
7.6
15
""" Resource and environment management utilities for Lanscape. """ from pathlib import Path import json class ResourceManager: """ A class to manage assets in the resources folder. Works locally and if installed based on relative path from this file. """ def __init__(self, asset_folder: str): ...
mdennis281/LANscape
lanscape/core/app_scope.py
.py
971c5a4c1dae87e4
7.52
10
"""Decorators and job tracking utilities for Lanscape.""" from time import time from collections import defaultdict import functools import concurrent.futures import logging import threading from tabulate import tabulate log = logging.getLogger(__name__) def run_once(func): """Ensure a function executes only ...
mdennis281/LANscape
lanscape/core/decorators.py
.py
7834c962e8a53192
7.52
10
"""Handles device alive checks using various methods. These probe primitives are consumed by the discovery stages in :mod:`lanscape.core.stages.discovery`: * ``*Lookup`` classes (``IcmpLookup``, ``ArpLookup``, ``ArpCacheLookup``) share the contract ``execute(device, cfg) -> bool``: mutate ``device.alive`` (and ``...
mdennis281/LANscape
lanscape/core/device_alive.py
.py
3ea21cd12e95fbe1
7.52
10
"""Custom exceptions for LANscape.""" class SubnetScanTerminationFailure(Exception): """Exception raised when subnet scanning threads cannot be terminated properly.""" def __init__(self, running_threads): super().__init__( f'Unable to terminate active threads: {running_threads}') class ...
mdennis281/LANscape
lanscape/core/errors.py
.py
0bd1b938b279603a
7.52
10
"""IP address parsing utilities (single, CIDR, ranges) — IPv4 & IPv6.""" import ipaddress from typing import List, Union IPAddress = Union[ipaddress.IPv4Address, ipaddress.IPv6Address] IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network] def _is_ipv6(text: str) -> bool: """Return True when *text* look...
mdennis281/LANscape
lanscape/core/ip_parser.py
.py
14a4813a55c32b3a
7.52
10
"""MAC address lookup and resolution service.""" import logging from typing import List, Optional from lanscape.core.app_scope import ResourceManager from lanscape.core.decorators import job_tracker, JobStatsMixin from lanscape.core.errors import DeviceError from lanscape.core.system_compat import ( send_arp_requ...
mdennis281/LANscape
lanscape/core/mac_lookup.py
.py
3e35f25a4b26bd54
7.52
10
""" Device-related Pydantic models for scanner results. """ import traceback as tb_module from typing import List, Dict, Optional from pydantic import BaseModel, Field, computed_field from lanscape.core.models.enums import DeviceStage class DeviceErrorInfo(BaseModel): """Serializable representation of a device...
mdennis281/LANscape
lanscape/core/models/device.py
.py
89bab19be540cc44
7.52
10
""" Enumeration types for scanner models. """ from enum import Enum class DeviceStage(str, Enum): """Stage of device discovery/scanning.""" RESOLVING = "resolving" FOUND = "found" SCANNING = "scanning" COMPLETE = "complete" class ScanStage(str, Enum): """Overall scan stage.""" INSTANTIA...
mdennis281/LANscape
lanscape/core/models/enums.py
.py
ebf5b8c2266dd03c
7.52
10
""" Scan-related Pydantic models for scanner results. """ from typing import List, Optional, Any, Dict from pydantic import BaseModel, Field from lanscape.core.models.enums import ScanStage, StageType, WarningCategory from lanscape.core.models.device import DeviceResult class StageEvalContext(BaseModel): """Co...
mdennis281/LANscape
lanscape/core/models/scan.py
.py
0cad8be1e4fdfa52
7.52
10
"""Runtime argument handler for LANscape as module""" import argparse import sys from typing import Any, Dict, Optional from pydantic import BaseModel from lanscape.core.version_manager import get_installed_version class RuntimeArgs(BaseModel): """Runtime arguments for the application.""" ui_port: int = 50...
mdennis281/LANscape
lanscape/core/runtime_args.py
.py
40f970d6f765e653
7.52
10
"""Service identification via binary signatures and text pattern matching.""" from typing import Optional, Tuple from lanscape.core.service_scan.resources import ( BINARY_SIGNATURES, SERVICE_MATCHERS, SERVICES, ) # Maximum length for stored responses to avoid bloating results MAX_RESPONSE_LENGTH = 512 ...
mdennis281/LANscape
lanscape/core/service_scan/identification.py
.py
3cf9a55d2ba947ca
7.52
10