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
# MIT License # # Copyright (C) 2026 vanous # # This file is part of pygdtf. # # 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 # t...
open-stage/python-gdtf
tests/test_mode_master_ranges.py
.py
34f7422d41e7dfed
7.1
15
# MIT License # # Copyright (C) 2025 vanous # # This file is part of pygdtf. # # 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 # t...
open-stage/python-gdtf
tests/test_physical.py
.py
b164ad045ba8bfa5
8.1
15
# MIT License # # Copyright (C) 2024 vanous # # This file is part of pygdtf. # # 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 # t...
open-stage/python-gdtf
tests/test_utils.py
.py
2e7daf3e1ced503c
8.1
15
# MIT License # # Copyright (C) 2025 vanous # # This file is part of pygdtf. # # 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 # t...
open-stage/python-gdtf
tests/test_writer.py
.py
720829ccdd293316
8.1
15
"""State update handler for blockchain data collection with provider filtering.""" import asyncio import hmac import json import logging import os from collections.abc import Coroutine from http.server import BaseHTTPRequestHandler from typing import Any from common.state.blob_storage import BlobConfig, BlobStorageHa...
chainstacklabs/compare-dashboard-functions
api/support/update_state.py
.py
7c9cc6ced4dd1324
7.66
20
"""Verifier function: emits balance_verified + verifier_status for EVM chains. Per cron round (fra1-only, every 15 min). For each chain in [Ethereum, Arbitrum, BNB, Robinhood]: - Compute VERIFY_BLOCK = latest_head - random(VERIFY_BLOCK_OFFSET_RANGES[chain]). Self-contained: no blob coordination with update_state...
chainstacklabs/compare-dashboard-functions
api/support/verify_state.py
.py
0e79a1fa5817d7cc
7.66
20
"""Hash uint256 balances to 52-bit floats for Influx/Mimir storage. Grafana Cloud's Prometheus-compatible store accepts only float64 samples. Ethereum balances are uint256 and routinely exceed 2^53, so direct float storage silently rounds and breaks equality. We SHA-256 the decimal-string form and keep the low 52 bits...
chainstacklabs/compare-dashboard-functions
common/balance_hash.py
.py
ec63c90d67281315
7.66
20
"""Metrics collection and processing base class.""" import logging import uuid from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, ClassVar, Optional, Union import aiohttp import websockets import websockets.exceptions from common.metric_config import MetricConfig, MetricLab...
chainstacklabs/compare-dashboard-functions
common/base_metric.py
.py
f48af66647ad4fe4
7.66
20
"""Factory for creating blockchain-specific metric instances.""" import copy from dataclasses import dataclass from typing import ClassVar from common.base_metric import BaseMetric from common.metric_config import EndpointConfig, MetricConfig, MetricLabels @dataclass class MetricRegistration: """Stores metadata...
chainstacklabs/compare-dashboard-functions
common/factory.py
.py
2e66b798bede88a2
7.66
20
"""Base class for Hyperliquid /info endpoint metrics.""" from abc import abstractmethod from typing import Any import aiohttp from common.metric_config import MetricConfig, MetricLabels from common.metric_types import HttpCallLatencyMetricBase from common.metrics_handler import MetricsHandler class HyperliquidInfo...
chainstacklabs/compare-dashboard-functions
common/hyperliquid_info_base.py
.py
4769c059cfc50828
7.66
20
"""Configuration classes for metrics.""" import logging from enum import Enum from typing import Any, Optional class MetricLabelKey(Enum): """Standard label keys for metric identification.""" SOURCE_REGION = "source_region" TARGET_REGION = "target_region" BLOCKCHAIN = "blockchain" PROVIDER = "pr...
chainstacklabs/compare-dashboard-functions
common/metric_config.py
.py
0e3db93f2e82331a
7.66
20
"""Base classes for WebSocket and HTTP metric collection.""" import asyncio import contextlib import logging import time from abc import abstractmethod from typing import Any, ClassVar, Optional, Union import aiohttp import websockets from common.base_metric import BaseMetric from common.metric_config import MetricC...
chainstacklabs/compare-dashboard-functions
common/metric_types.py
.py
5347ff94cf4ef706
7.66
20
"""Handlers for serverless metric collection and pushing.""" import asyncio import json import logging import os import time from http.server import BaseHTTPRequestHandler from typing import Any import aiohttp from common.balance_hash import hash_balance_to_float from common.base_metric import BaseMetric from common...
chainstacklabs/compare-dashboard-functions
common/metrics_handler.py
.py
3c26867864b46054
7.66
20
"""Blob storage handler for managing blobs in Vercel Blob Storage.""" import json import time from dataclasses import dataclass from typing import Optional import aiohttp from config.defaults import BlobStorageConfig @dataclass class BlobConfig: """Configuration for Vercel Blob Storage access.""" store_id...
chainstacklabs/compare-dashboard-functions
common/state/blob_storage.py
.py
f9769d5ae92944f8
7.66
20
"""Manages blockchain state data by fetching and processing data from blob storage.""" import asyncio import logging import os import aiohttp from config.defaults import BlobStorageConfig class BlockchainState: """Manages blockchain state data retrieval from blob storage.""" _TIMEOUT = aiohttp.ClientTimeo...
chainstacklabs/compare-dashboard-functions
common/state/blockchain_state.py
.py
a1955ed0628b576c
7.66
20
"""Multi-provider stateRoot quorum + Chainstack proof fetch. The quorum policy is "all or none" per spec: if any provider in fra1 fails to return a valid stateRoot, raise ``AnchorPartialResponse``. If all respond but not all agree, raise ``AnchorDisagreement``. The orchestration code in ``api/support/verify_state.py``...
chainstacklabs/compare-dashboard-functions
common/verify/anchor.py
.py
a4dfa1fe0560bd4c
7.66
20
"""Local verification of an EVM account's MPT proof. Walks ``accountProof`` returned by ``eth_getProof`` and confirms the leaf is consistent with a given ``state_root``. Returns the canonical balance on success; returns ``None`` for canonical exclusion proofs (path divergence, empty branch slot, etc.); raises ``ProofE...
chainstacklabs/compare-dashboard-functions
common/verify/proof.py
.py
5f99aa7547d7de18
7.66
20
"""Endpoint enumeration for the verifier. Reads from the same ``ENDPOINTS`` env var that ``api/support/update_state.py`` and ``common/metrics_handler.py`` already use, but exposes two queries that ``update_state`` doesn't need: - ``all_providers_for(chain)`` — every HTTP endpoint configured for the chain (regardles...
chainstacklabs/compare-dashboard-functions
common/verify/providers.py
.py
3eda226fa45955bb
7.66
20
# /// script # requires-python = ">=3.11" # dependencies = [ # "requests", # "python-dotenv", # ] # /// """CLI tool to pull, push, and diff Grafana dashboards via the Grafana HTTP API.""" import hashlib import json import os import re import sys from pathlib import Path import requests from dotenv import load_dot...
chainstacklabs/compare-dashboard-functions
dashboards/grafana_sync.py
.py
9a42b3725de02f8f
7.66
20
"""Solana landing rate metrics with priority fees.""" import asyncio import logging import os import random import time from enum import Enum from typing import Optional import base58 from solana.rpc.async_api import AsyncClient from solana.rpc.commitment import Confirmed from solana.rpc.types import TxOpts from sold...
chainstacklabs/compare-dashboard-functions
metrics/solana_landing_rate.py
.py
925b6d43c8bfe11e
7.66
20
"""Run local development server for blockchain metrics collection.""" import json import os import sys from http.server import HTTPServer from pathlib import Path import dotenv project_root = str(Path(__file__).parent.parent) sys.path.append(project_root) def setup_environment() -> None: """Load environment an...
chainstacklabs/compare-dashboard-functions
tests/test_api_read.py
.py
39678e5a8a337d74
8.16
20
"""Run local development server for blockchain metrics collection.""" import json import os import sys from http.server import HTTPServer from pathlib import Path import dotenv project_root = str(Path(__file__).parent.parent) sys.path.append(project_root) def setup_environment() -> None: """Load environment an...
chainstacklabs/compare-dashboard-functions
tests/test_api_write.py
.py
4082acf7fd74f260
8.16
20
"""Self-check for the measurement gate: python tests/test_measurement_gate.py Fails if serialised metrics ever overlap, if exempt metrics get serialised, if a hung metric can consume the whole round, or if a metric the budget starved before it started gets wrongly reported as a provider failure. """ import asyncio im...
chainstacklabs/compare-dashboard-functions
tests/test_measurement_gate.py
.py
6f7667d75596e8e5
8.16
20
"""Local development server for blockchain state updates.""" import json import os import sys from http.server import HTTPServer from pathlib import Path import dotenv project_root = str(Path(__file__).parent.parent) sys.path.append(project_root) def setup_environment() -> None: """Load environment and endpoin...
chainstacklabs/compare-dashboard-functions
tests/test_update_state.py
.py
e68e6d09c74ee78b
8.16
20
""" Cell position I/O Based on https://github.com/SainsburyWellcomeCentre/niftynet_cell_count by Christian Niedworok (https://github.com/cniedwor). """ import json import logging import os import re from pathlib import Path from typing import List, NoReturn, Optional, Union from xml.dom import minidom from xml.etree ...
brainglobe/brainglobe-utils
brainglobe_utils/IO/cells.py
.py
edb711636b5df93f
7.56
12
import warnings from pathlib import Path import numpy as np import tifffile with warnings.catch_warnings(): warnings.simplefilter("ignore") import nibabel as nib def to_nii(img, dest_path, scale=None, affine_transform=None): # TODO: see if we want also real units scale """ Write the brain volum...
brainglobe/brainglobe-utils
brainglobe_utils/IO/image/save.py
.py
c943bddc2a09d150
7.56
12
import psutil from scipy.ndimage import zoom class ImageIOLoadException(Exception): """ Custom exception class for errors found loading images with brainglobe_utils.IO.image.load Alerts the user of: loading a directory containing only a single .tiff, loading a single 2D .tiff, loading an image se...
brainglobe/brainglobe-utils
brainglobe_utils/IO/image/utils.py
.py
7d3e0ff116feaa22
7.56
12
from pathlib import Path from typing import Any, Dict, Optional, Union import yaml def read_yaml_section(yaml_file: Union[str, Path], section: str) -> Any: """ Read section from yaml file. Parameters ---------- yaml_file : str or pathlib.Path Path of .yml file to read. section : str ...
brainglobe/brainglobe-utils
brainglobe_utils/IO/yaml.py
.py
7d00fc79be095d3e
7.56
12
import inspect import sys from string import ascii_letters, digits from typing import Any, ClassVar, Dict from brainglobe_utils.citation.format import Format class BibTexEntry(Format): """ An abstract base class for generating BibTex entries from CITATION.cff yaml-content. Constructed by passing a d...
brainglobe/brainglobe-utils
brainglobe_utils/citation/bibtex_fmt.py
.py
35caa0c240b71a2a
7.56
12
import sys from argparse import ArgumentParser from pathlib import Path from typing import Literal from warnings import warn from brainglobe_utils.citation.bibtex_fmt import ( BibTexEntry, supported_bibtex_entry_types, ) from brainglobe_utils.citation.repositories import ( all_citable_repositories, uni...
brainglobe/brainglobe-utils
brainglobe_utils/citation/cite.py
.py
0e6de88fe153f128
7.56
12
from typing import Dict import requests from yaml import safe_load BASE_URL = "https://raw.githubusercontent.com" def fetch_from_github( user: str, repo: str, file: str = "CITATION.cff", branch: str = "main", ) -> requests.Response: """ Fetches the content of a file hosted on GitHub, ret...
brainglobe/brainglobe-utils
brainglobe_utils/citation/fetch.py
.py
2b9e06cfd6352991
7.56
12
import warnings from typing import Any, ClassVar, Dict, List, Union class Format: """ An abstract base class for generating reference formats from CITATION.cff yaml-content. Constructed by passing a dict containing the yaml-processed content of the CITATION.cff file to the constructor. Requir...
brainglobe/brainglobe-utils
brainglobe_utils/citation/format.py
.py
80e5d2116a8b578a
7.56
12
import inspect import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Set import requests from brainglobe_utils.citation.fetch import fetch_from_github, yaml_str_to_dict @dataclass class Repository: """ Static class for representing GitHub repositories, in particular whe...
brainglobe/brainglobe-utils
brainglobe_utils/citation/repositories.py
.py
7114aeb57a018b44
7.56
12
from brainglobe_utils.citation.format import Format class TextCitation(Format): """ Generates a reference string that can be copy-pasted into a text document's bibliography for use as a reference. Style of text-based references will be <citation-sentence>; <authors> (<year>). <title>. <j...
brainglobe/brainglobe-utils
brainglobe_utils/citation/text_fmt.py
.py
8cc36887aab9acf4
7.56
12
class CommandLineInputError(Exception): """Exception raised for incorrect or illogical command line inputs that are not caught elsewhere. Attributes ---------- message : str explanation of the error """ def __init__(self, message): self.message = message def __...
brainglobe/brainglobe-utils
brainglobe_utils/general/exceptions.py
.py
5b60e7216bc845a3
7.06
12
import glob import logging import os import platform import shutil import subprocess from pathlib import Path from tempfile import gettempdir from typing import Union import psutil from natsort import natsorted from slurmio import slurmio from tqdm import tqdm from brainglobe_utils.general.exceptions import CommandLi...
brainglobe/brainglobe-utils
brainglobe_utils/general/system.py
.py
a5b47430c475a5ec
7.56
12
from pathlib import Path from typing import Tuple, Union import numpy as np from scipy.ndimage import zoom from skimage.filters import gaussian from brainglobe_utils.general.system import ensure_directory_exists from brainglobe_utils.image.binning import get_bins from brainglobe_utils.image.masking import mask_image_...
brainglobe/brainglobe-utils
brainglobe_utils/image/heatmap.py
.py
7b7a6dd5e6c7bdc3
7.56
12
import numpy as np def mask_image_threshold(image, masking_image, threshold=0): """ Mask one image, based on the values in another image that are above a threshold. Parameters ---------- image : np.ndarray Input image masking_image : np.ndarray Image to base the mask on (s...
brainglobe/brainglobe-utils
brainglobe_utils/image/masking.py
.py
9b4671f43b3e02eb
7.56
12
import numpy as np import pandas as pd def initialise_df(*column_names): """ Initialise a pandas dataframe with n column names. Parameters ---------- *column_names : str N column names Returns ------- pd.DataFrame Empty pandas dataframe with specified column names ...
brainglobe/brainglobe-utils
brainglobe_utils/pandas/misc.py
.py
4883c34990042fe3
7.56
12
from pathlib import Path import pooch import pytest @pytest.fixture def data_path(): """Directory storing all test data""" return Path(__file__).parent.parent / "data" @pytest.fixture def test_data_registry(): """ Create a test data registry for BrainGlobe. Returns: pooch.Pooch: The te...
brainglobe/brainglobe-utils
tests/tests/conftest.py
.py
ba7d09162e99d9ba
8.06
12
import os from pathlib import Path from xml.etree import ElementTree import pandas as pd import pytest import yaml from natsort import natsorted from brainglobe_utils.cells.cells import ( Cell, UntypedCell, file_name_from_cell, pos_from_file_name, ) from brainglobe_utils.IO import cells as cell_io @...
brainglobe/brainglobe-utils
tests/tests/test_IO/test_cell_io.py
.py
dc6719ebd331fcd4
7.06
12
import random from collections import namedtuple from unittest import mock import numpy as np import psutil import pytest import tifffile from brainglobe_utils.IO.image import load, save, to_tiffs, utils @pytest.fixture() def array_2d(): """Create a 4x4 array of 32-bit integers""" return np.tile(np.array([1...
brainglobe/brainglobe-utils
tests/tests/test_IO/test_image_io.py
.py
cbf5245c71405f07
7.06
12
"""Generate Typst resume files from YAML data.""" import os import shutil import subprocess from functools import lru_cache from pathlib import Path from typing import Any, Dict import requests import yaml @lru_cache(None) def get_github_stars(repository: str) -> str: """Fetch GitHub stars with graceful fallback...
yihong0618/resume
renderer/typst_generator.py
.py
4d893b9ddb7f0509
7.48
8
from typing import Any, Dict, Optional from pathlib import Path def load_settings(default_settings: Dict[str, Any]) -> Dict[str, Any]: """ Load settings by merging default settings with environment variables. Args: default_settings (Dict[str, Any]): The default settings to use. Returns: ...
OneBusAway/python-sdk
examples/helpers/load_env.py
.py
f1b82b196ef627d0
7.54
11
# Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py from __future__ import annotations import json import inspect from types import TracebackType from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, Optional, AsyncIterator, cast from typing_ext...
OneBusAway/python-sdk
src/onebusaway/_streaming.py
.py
37279624c9c49ba0
7.54
11
from __future__ import annotations from os import PathLike from typing import ( IO, TYPE_CHECKING, Any, Dict, List, Type, Tuple, Union, Mapping, TypeVar, Callable, Iterable, Iterator, Optional, Sequence, AsyncIterable, ) from typing_extensions import ( ...
OneBusAway/python-sdk
src/onebusaway/_types.py
.py
d153b838bdada5b7
7.54
11
from __future__ import annotations from typing import Any from typing_extensions import override from ._proxy import LazyProxy class ResourcesProxy(LazyProxy[Any]): """A proxy for the `onebusaway.resources` module. This is used so that we can lazily import `onebusaway.resources` only when needed *and* ...
OneBusAway/python-sdk
src/onebusaway/_utils/_resources_proxy.py
.py
b07c52819e72ca85
7.54
11
# MIT License # # Copyright (C) 2023 vanous # # This file is part of pymvr. # # 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...
open-stage/python-mvr
conftest.py
.py
af7557bd371801c2
8.15
19
# MIT License # # Copyright (C) 2026 vanous # # This file is part of pymvr. # # 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...
open-stage/python-mvr
tests/test_empty_self_closed_tags.py
.py
7181bb4239ed5fb2
7.15
19
# MIT License # # Copyright (C) 2023 vanous # # This file is part of pymvr. # # 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...
open-stage/python-mvr
tests/test_fixture_1_5.py
.py
48272d1829a0d9f5
8.15
19
# MIT License # # Copyright (C) 2023 vanous # # This file is part of pymvr. # # 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...
open-stage/python-mvr
tests/test_fixture_scene_object_1_5.py
.py
abdcfd0647c9ab22
8.15
19
# MIT License # # Copyright (C) 2025 vanous # # This file is part of pymvr. # # 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...
open-stage/python-mvr
tests/test_mvr_04_read_ours_json.py
.py
bbf08b79a6865918
8.15
19
"""Show how fast one ordinary Black-Scholes-Merton call chain is priced.""" import platform import sys from importlib.metadata import version from statistics import median from time import perf_counter from timeit import repeat as timeit_repeat import numba import numpy as np import vanilla_option_pricers as vop #...
ArturSepp/VanillaOptionPricers
examples/performance/bsm_speed.py
.py
933f3daa1b0b64a8
7.59
14
import json from geoalchemy2 import WKBElement from shapely.wkb import loads from shapely import Point from sqlalchemy import create_engine, MetaData, Table, select, and_ from sqlalchemy.dialects.postgresql import insert from landlensdb.geoclasses.geoimageframe import GeoImageFrame class Postgres: """ A cla...
landlensdb/landlensdb
landlensdb/handlers/db.py
.py
bdfc9ea27b65a546
7.42
6
""" Image anonymization module for blurring faces and license plates. This module provides functionality to detect and blur privacy-sensitive information (faces and license plates) in street-level imagery using YOLOv8 model fine-tuned on dashcam data. Based on: https://github.com/varungupta31/dashcam_anonymizer """ ...
landlensdb/landlensdb
landlensdb/process/anonymize.py
.py
19793edb7fde610c
7.42
6
import os import time import warnings from datetime import datetime import geopandas as gpd import networkx as nx import osmnx as ox from shapely.geometry import box def get_osm_lines(bbox, network_type="drive", cache_dir=None, retries=3): """Get road network from OpenStreetMap for a given bounding box. Arg...
landlensdb/landlensdb
landlensdb/process/road_network.py
.py
9e111efff21f426b
7.42
6
import math import warnings import geopandas as gpd import numpy as np import osmnx as ox import pandas as pd from shapely import Point from shapely.geometry import LineString from rtree import index from .road_network import ( get_osm_lines, optimize_network_for_snapping, validate_network_topology, c...
landlensdb/landlensdb
landlensdb/process/snap.py
.py
8de4ef53e0abb0c7
7.42
6
""" Tests for the anonymize module. Note: These tests require optional dependencies (ultralytics, opencv-python). Run with: pip install landlensdb[anonymize] """ import os import pytest import warnings # Check if anonymize dependencies are available try: from ultralytics import YOLO import cv2 ANONYMIZE...
landlensdb/landlensdb
tests/test_process/test_anonymize.py
.py
2737c42a5f70aec9
7.92
6
"""Support for Here comes the bus binary sensors.""" from collections.abc import Callable from dataclasses import dataclass from homeassistant.components.binary_sensor import ( BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helper...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
custom_components/here_comes_the_bus/binary_sensor.py
.py
099cbf3a54b42774
7.42
6
"""Adds config flow for Here comes the bus.""" import homeassistant.helpers.config_validation as cv import voluptuous as vol from hcb_soap_client.hcb_soap_client import HcbSoapClient from homeassistant import config_entries from homeassistant.auth.providers.homeassistant import InvalidAuth from homeassistant.const imp...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
custom_components/here_comes_the_bus/config_flow.py
.py
6e8e371772d20538
7.42
6
"""Coordinator file for Here comes the bus Home assistant integration.""" from calendar import SATURDAY from datetime import datetime, time, timedelta from enum import StrEnum from hcb_soap_client.stop_response import StudentStop, VehicleLocation from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homea...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
custom_components/here_comes_the_bus/coordinator.py
.py
01755e567a8eca49
7.42
6
"""Custom types for here comes the bus.""" from __future__ import annotations from dataclasses import dataclass, field from datetime import time from typing import TYPE_CHECKING from homeassistant.config_entries import ConfigEntry if TYPE_CHECKING: from datetime import datetime from hcb_soap_client.hcb_soa...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
custom_components/here_comes_the_bus/data.py
.py
0d3066c61a66d0f1
7.42
6
"""Define a device tracker.""" from collections.abc import Callable from attr import dataclass from homeassistant.components.device_tracker import ( TrackerEntity, # type: ignore i am pretty sure it is but ? TrackerEntityDescription, # type: ignore i am pretty sure it is but ? ) from homeassistant.core impo...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
custom_components/here_comes_the_bus/device_tracker.py
.py
58b7af51b04b74f8
7.42
6
"""HCB class.""" from __future__ import annotations from typing import TYPE_CHECKING from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import BUS, DOMAIN, HERE_COMES_THE_BUS from .coordinator import HCBDat...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
custom_components/here_comes_the_bus/entity.py
.py
8899eef3ddf0e861
7.42
6
"""Define sensors.""" from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, time from typing import Any from homeassistant.components.sensor import SensorEntity, SensorEntityDescription from homeassistant.components.sensor.const import SensorDeviceClass from homeassista...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
custom_components/here_comes_the_bus/sensor.py
.py
60369672b3832b19
7.42
6
"""Tests for the Here Comes The Bus binary sensor.""" from collections.abc import Generator from unittest.mock import AsyncMock, MagicMock, patch import pytest from homeassistant.core import HomeAssistant from custom_components.here_comes_the_bus.binary_sensor import ( ENTITY_DESCRIPTIONS, HCBBinarySensor, ...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
tests/test_binary_sensor.py
.py
5cff4daaf2429029
7.92
6
"""Tests for config flow.""" from unittest.mock import AsyncMock, MagicMock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.auth.providers.homeassistant import InvalidAuth from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import Home...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
tests/test_config_flow.py
.py
c402e3d11bb09132
7.92
6
"""Test the init module.""" from collections.abc import Generator from unittest.mock import AsyncMock, MagicMock, patch import pytest from homeassistant.const import Platform from homeassistant.core import HomeAssistant from custom_components.here_comes_the_bus import ( async_reload_entry, async_setup_entry,...
pcartwright81/Home-Assistant-Here-Comes-The-Bus
tests/test_init.py
.py
ecd29003ee8c8a29
7.92
6
""" Quantum Channel simulation modeling optical fiber loss, depolarization, and detector noise. """ from dataclasses import dataclass import numpy as np from qkd.core.states import Basis, PolarizationState @dataclass class ChannelParameters: """Physical parameters for the optical quantum channel and detectors.""...
Sheng254/QKDSimulator
qkd/core/channel.py
.py
25a0b1a27d395740
7.42
6
""" Eavesdropping attack models in Quantum Key Distribution. """ from dataclasses import dataclass import numpy as np from qkd.core.states import Basis, PolarizationState @dataclass class EveAction: """Record of Eve's interaction with a single quantum state.""" intercepted: bool basis: Basis | None = Non...
Sheng254/QKDSimulator
qkd/core/eve.py
.py
a214e22d40e6f674
7.42
6
""" Quantum States and Measurement Operators for Quantum Cryptography. """ from enum import Enum import numpy as np class Basis(str, Enum): """Measurement and preparation bases.""" RECTILINEAR = "Z" # Computational / Rectilinear basis: {|0⟩, |1⟩} or {↔, ↕} DIAGONAL = "X" # Hadamard / Diagonal basis:...
Sheng254/QKDSimulator
qkd/core/states.py
.py
b7243633872f2a01
7.42
6
""" Information-Theoretically Secure One-Time Pad (OTP) Cipher using Quantum Keys. """ from dataclasses import dataclass @dataclass class OTPEncryptionResult: """Result of One-Time Pad encryption.""" plaintext: str plaintext_bits: list[int] key_bits_used: list[int] ciphertext_bits: list[int] ...
Sheng254/QKDSimulator
qkd/crypto/otp.py
.py
c60b6c4117119957
7.42
6
""" B92 (Bennett 1992) Quantum Key Distribution Protocol with 2 Non-Orthogonal States. """ from dataclasses import dataclass, field import numpy as np from qkd.core.states import Basis, PolarizationState from qkd.core.channel import QuantumChannel, ChannelParameters from qkd.core.eve import EveAttacker @dataclass cl...
Sheng254/QKDSimulator
qkd/protocols/b92.py
.py
c7e7840b2ffc02a4
7.42
6
""" BB84 (Bennett & Brassard 1984) Quantum Key Distribution Protocol. """ from dataclasses import dataclass, field import numpy as np from qkd.core.states import Basis, PolarizationState from qkd.core.channel import QuantumChannel, ChannelParameters from qkd.core.eve import EveAttacker, EveAction from qkd.core.reconci...
Sheng254/QKDSimulator
qkd/protocols/bb84.py
.py
104014e00583464c
7.42
6
""" E91 (Ekert 1991) Entanglement-Based Quantum Key Distribution with CHSH Bell Test. """ from dataclasses import dataclass, field import numpy as np from qkd.core.reconciliation import CascadeReconciliation, PrivacyAmplification, binary_entropy @dataclass class E91StepData: """Step trace for an entangled EPR p...
Sheng254/QKDSimulator
qkd/protocols/e91.py
.py
4d5e986cd3e1e395
7.42
6
""" Unit tests for B92 (Bennett 1992) 2-state protocol. """ import unittest from qkd.protocols.b92 import B92Simulator class TestB92Physics(unittest.TestCase): def test_b92_ideal_channel_efficiency(self): """Verify that B92 without noise has 0% QBER and ~25% sifting efficiency.""" sim = B92Simula...
Sheng254/QKDSimulator
tests/test_b92.py
.py
9b43a2d67a87c7a6
7.92
6
""" Unit tests for BB84 Quantum Physics and Channel Statistics. """ import unittest import numpy as np from qkd.protocols.bb84 import BB84Simulator from qkd.core.channel import ChannelParameters class TestBB84Physics(unittest.TestCase): def test_bb84_ideal_channel_zero_error(self): """Verify that with ze...
Sheng254/QKDSimulator
tests/test_bb84_physics.py
.py
ea9dc50d5bc4b079
7.92
6
""" Unit tests for E91 Entanglement and CHSH Bell Inequality Violations. """ import unittest from qkd.protocols.e91 import E91Simulator class TestE91Bell(unittest.TestCase): def test_e91_bell_inequality_violation_when_secure(self): """ Quantum mechanics predicts S > 2.0 (up to Tsirelson limit S =...
Sheng254/QKDSimulator
tests/test_e91_bell.py
.py
ddc2c37f5ea414b4
7.92
6
""" Unit tests for One-Time Pad quantum cipher. """ import unittest from qkd.crypto.otp import OneTimePad class TestOneTimePad(unittest.TestCase): def test_otp_roundtrip_encryption_decryption(self): """Verify that plaintext encrypts to ciphertext and decrypts back perfectly.""" key = [1, 0, 1, 1,...
Sheng254/QKDSimulator
tests/test_otp.py
.py
a92134ffe070bf12
7.92
6
""" Unit tests for Cascade Error Reconciliation and Privacy Amplification. """ import unittest import numpy as np from qkd.core.reconciliation import CascadeReconciliation, PrivacyAmplification, binary_entropy class TestReconciliation(unittest.TestCase): def test_cascade_reconciles_bit_errors(self): """V...
Sheng254/QKDSimulator
tests/test_reconciliation.py
.py
c2eab8ab67b936fc
7.92
6
"""write-protection guard used by LinearBase and TreeBase. blocks assignment to any name listed in a subclass's _protected_fields from anywhere except the base class's own object.__setattr__ calls [see LinearBase/TreeBase's _set_* helpers]. """ from __future__ import annotations from typing import Any, ClassVar, Froz...
waltermichelraja/mercurytools
src/mercurytools/core/base.py
.py
4189645535ab9e65
7.45
7
"""shared base class for doubly-linked sequential structures [LinkedList, Stack, Deque].""" from __future__ import annotations from typing import Generic, Iterable, Iterator, List, Optional, TypeVar, Union from .base import InternalStateGuard from .nodes import LinearNode as Node from .exceptions import EmptyStructu...
waltermichelraja/mercurytools
src/mercurytools/core/base_linear.py
.py
f52e8b52db1ab288
7.45
7
"""shared base class for binary tree structures [BinaryTree, BinarySearchTree, AVLTree].""" from __future__ import annotations from collections import deque from typing import Generic, Iterator, Optional, TypeVar from .base import InternalStateGuard from .nodes import BinaryTreeNode as Node T=TypeVar("T") class T...
waltermichelraja/mercurytools
src/mercurytools/core/base_tree.py
.py
9532fc66f6663621
7.45
7
"""structural typing helper for TypeVar bounds that require ordering [<, >]. used by BinarySearchTree and AVLTree, whose stored values must support comparison for the tree to remain ordered. BinaryTree does not use this -- it has no ordering requirement. """ from __future__ import annotations from typing import Any, ...
waltermichelraja/mercurytools
src/mercurytools/core/comparable.py
.py
8817508603d5f9e5
7.45
7
"""custom exception hierarchy for mercurytools. all exceptions raised by this library inherit from MercuryError. """ from __future__ import annotations class MercuryError(Exception): """base class for all exceptions raised by mercurytools.""" pass class EmptyStructureError(MercuryError,IndexError): ""...
waltermichelraja/mercurytools
src/mercurytools/core/exceptions.py
.py
b1ef1fc836220a31
7.45
7
"""internal node types backing the linear and tree structures.""" from __future__ import annotations from typing import Generic, Optional, TypeVar T=TypeVar("T") K=TypeVar("K") V=TypeVar("V") class LinearNode(Generic[T]): """a doubly-linked node used by LinearBase-derived structures [LinkedList, Stack, Deque]....
waltermichelraja/mercurytools
src/mercurytools/core/nodes.py
.py
0be87693cc64390e
7.45
7
"""double-ended queue backed by a doubly-linked list.""" from __future__ import annotations from typing import TypeVar from ..core.base_linear import LinearBase from ..core.nodes import LinearNode as Node from ..core.exceptions import EmptyStructureError T=TypeVar("T") class Deque(LinearBase[T]): """a double-...
waltermichelraja/mercurytools
src/mercurytools/linear/deque.py
.py
c947fd203677c51e
7.45
7
"""doubly-linked list.""" from __future__ import annotations from typing import TypeVar from ..core.base_linear import LinearBase from ..core.nodes import LinearNode as Node from ..core.exceptions import IndexOutOfBoundsError,ValueNotFoundError T=TypeVar("T") class LinkedList(LinearBase[T]): """a doubly-linke...
waltermichelraja/mercurytools
src/mercurytools/linear/linked_list.py
.py
d89594b9bc39f0c5
7.45
7
"""binary min-heap priority queue, with an optional FIFO fallback mode.""" from __future__ import annotations from typing import Any, Generic, Iterator, List, Optional, Tuple, TypeVar from ..core.exceptions import EmptyStructureError T=TypeVar("T") class PriorityQueue(Generic[T]): """a binary min-heap that po...
waltermichelraja/mercurytools
src/mercurytools/linear/priority_queue.py
.py
94409833da49b8ba
7.45
7
"""LIFO stack backed by a doubly-linked list.""" from __future__ import annotations from typing import Optional, TypeVar from ..core.base_linear import LinearBase from ..core.nodes import LinearNode as Node from ..core.exceptions import EmptyStructureError T=TypeVar("T") class Stack(LinearBase[T]): """a last-...
waltermichelraja/mercurytools
src/mercurytools/linear/stack.py
.py
4f9297cf4627048c
7.45
7
"""self-balancing [AVL] binary search tree.""" from __future__ import annotations from typing import Optional, Tuple, TypeVar from ..core.base_tree import TreeBase from ..core.nodes import BinaryTreeNode as Node from ..core.exceptions import ValueNotFoundError from ..core.comparable import Comparable T=TypeVar("T",...
waltermichelraja/mercurytools
src/mercurytools/tree/avl_tree.py
.py
a9c6fe6a025b21ac
7.45
7
"""unbalanced binary search tree.""" from __future__ import annotations from typing import Optional, Tuple, TypeVar from ..core.base_tree import TreeBase from ..core.nodes import BinaryTreeNode as Node from ..core.exceptions import ValueNotFoundError from ..core.comparable import Comparable T=TypeVar("T",bound=Comp...
waltermichelraja/mercurytools
src/mercurytools/tree/binary_search_tree.py
.py
2ade0df15b020665
7.45
7
"""unordered binary tree with level-order [complete-tree] insertion.""" from __future__ import annotations from collections import deque from typing import TypeVar from ..core.nodes import BinaryTreeNode as Node from ..core.base_tree import TreeBase T=TypeVar("T") class BinaryTree(TreeBase[T]): """a generic b...
waltermichelraja/mercurytools
src/mercurytools/tree/binary_tree.py
.py
b1732ab0735db281
7.45
7
"""fixed-capacity LRU [least-recently-used] cache.""" from __future__ import annotations from typing import Generic, Iterator, Optional, TypeVar from ..core.nodes import LRUNode as Node K=TypeVar("K") V=TypeVar("V") class LRUCache(Generic[K,V]): """a fixed-capacity key/value cache that evicts the least recent...
waltermichelraja/mercurytools
src/mercurytools/utils/lru_cache.py
.py
fc52089bf40d3c71
7.45
7
"""Physical constants and configuration for the MagRobotNav environment.""" import numpy as np from dataclasses import dataclass, field from enum import Enum, auto @dataclass(frozen=True) class EnvConfig: """Centralized physical constants for robot navigation simulation. All length units are in millimeters, ...
fanghaow/STTRL-DVO
mag_robot_nav/envs/config.py
.py
fc60562a930452d9
7.45
7
"""Pure helpers for Dynamic Velocity Obstacle heading selection.""" import numpy as np from .geometry import pi_2_pi def merge_angle_intervals(intervals): """Merge overlapping linear intervals without mutating the caller's list.""" merged = [] for current in sorted((list(interval) for interval in interv...
fanghaow/STTRL-DVO
mag_robot_nav/envs/dvo.py
.py
daf7ec968bdcd32d
7.45
7
"""Low-level geometry/math utilities with no project-internal dependencies.""" import numpy as np def pi_2_pi(angle: float) -> float: """Wrap angle to [-pi, pi].""" return (angle + np.pi) % (2 * np.pi) - np.pi def euclidean_distance(x1: float, y1: float, x2: float, y2: float) -> floa...
fanghaow/STTRL-DVO
mag_robot_nav/envs/geometry.py
.py
0b0ab13b4f229f4e
7.45
7
"""Data model classes for the MagRobot navigation environment.""" import numpy as np from collections import deque from dataclasses import dataclass from typing import List, Optional, Tuple from .config import ( MAX_ACCELERATION, MAX_ANGULAR_ACCELERATION, MIN_VELOCITY, MAX_VELOCITY, MIN_ANGULAR_VELOCITY, ...
fanghaow/STTRL-DVO
mag_robot_nav/envs/models.py
.py
ce6db48888150f5a
7.45
7
"""Path-planning algorithms with lazy public imports. Importing :mod:`mag_robot_nav.planners` no longer imports matplotlib, cvxpy, and every planner eagerly. Public symbols remain available from this package. """ from importlib import import_module _EXPORTS = { "AStarPlanner": ("a_star", "AStarPlanner"), "D...
fanghaow/STTRL-DVO
mag_robot_nav/planners/__init__.py
.py
c192801c2d9274c5
7.45
7
"""Adapted from PythonRobotics under the MIT License. Upstream: https://github.com/AtsushiSakai/PythonRobotics See THIRD_PARTY_LICENSES.md for the complete notice. Mobile robot motion planning sample with Dynamic Window Approach author: Atsushi Sakai (@Atsushi_twi), Göktuğ Karakaşlı """ import math from enum impor...
fanghaow/STTRL-DVO
mag_robot_nav/planners/dynamic_window_approach.py
.py
b73f76d00b3272bb
7.45
7