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
"""Factory for building stage instances from pipeline configuration.""" from typing import List from lanscape.core.scan_config import PipelineConfig from lanscape.core.scan_stage import ScanStageMixin from lanscape.core.models.enums import StageType from lanscape.core.ip_parser import parse_ip_input, get_address_coun...
mdennis281/LANscape
lanscape/core/stage_builder.py
.py
fa24a63d4e3a4772
7.52
10
"""Per-stage time estimation for a single unit of work. Each discovery stage returns the worst-case seconds to probe **one IP** (without hostname resolution, since ~90 % of IPs won't be alive). The port-scan stage returns the worst-case seconds to scan **one device** given the configured port list, thread count, and ...
mdennis281/LANscape
lanscape/core/stage_estimates.py
.py
261c90f4258b0150
7.52
10
"""Port scanning stage.""" import logging from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List from lanscape.core.scan_stage import ScanStageMixin from lanscape.core.scan_context import ScanContext from lanscape.core.models.enums import StageType from lanscape.core.models.scan impor...
mdennis281/LANscape
lanscape/core/stages/port_scan.py
.py
dd310988855a20fb
7.52
10
"""ThreadPool retry manager for resilient concurrent operations.""" import logging import traceback from time import time from dataclasses import dataclass, field from typing import Callable, Any, Dict, List, TypeVar, Generic, Optional from concurrent.futures import ThreadPoolExecutor, Future, as_completed from thread...
mdennis281/LANscape
lanscape/core/threadpool_retry.py
.py
78b0936dd9ec15b1
7.52
10
""" Version management module for LANscape. Handles version checking, update detection, and retrieving package information from both local installation and PyPI repository. Uses PEP 440 version ordering via the ``packaging`` library so that pre-release channels are compared correctly:: alpha < beta < rc < stable...
mdennis281/LANscape
lanscape/core/version_manager.py
.py
83a4b89d660f0ec4
7.52
10
""" LANscape local dev orchestrator. Triggered by `python -m lanscape` in a source checkout that has configured `lanscape/local/.env`. Replaces the bundled-UI flow with three things in concert: - Python WebSocket backend (subprocess; optionally wrapped with watchdog for auto-restart on .py changes) - UI dev se...
mdennis281/LANscape
lanscape/local/dev_runner.py
.py
bd3f8d1c43947ea1
7.52
10
#!/usr/bin/env python3 """ Created by GitHub Copilot CLI on 2026-07-05 Filter CodeQL findings to suppress known false positives. This script removes honeypot credential logging findings from CodeQL results. Usage: python3 codeql-filter.py <input.sarif> <output.sarif> """ import json import sys from pathlib import ...
linickx/HomeDetector
.github/codeql/codeql-filter.py
.py
6206645a2b9697dd
7.45
7
#!/usr/bin/env python3 # Created by Antigravity using model Gemini 3.6 Flash on 2026-08-09 """ Patch dependencies in OpenCanary's pyproject.toml file based on a JSON config. """ import argparse import json import os import re import sys def apply_patch(patch: dict, content: str, target_path: str) -> tuple[str, bool...
linickx/HomeDetector
opencanary/patch_dependencies.py
.py
db9fc25c0da44ec9
7.45
7
#!/usr/bin/env python3 # Created by Antigravity using model Gemini 3.6 Flash on 2026-08-09 # Modified by Antigravity using model Claude Opus 4.6 on 2026-08-10 """ Synchronize the OpenCanary release version across project files. """ import argparse import os import re import shutil import subprocess import sys # Defa...
linickx/HomeDetector
opencanary/sync_version.py
.py
de924cbab356fc0a
7.45
7
"""Glentronics API Client.""" from __future__ import annotations import asyncio import socket from typing import Any import aiohttp import async_timeout from .const import LOGGER, GLENTRONICS_API_USERNAME, GLENTRONICS_API_PASSWORD API_URL = "https://api.glentronicsconnect.com" class GlentronicsApiClientError(Exce...
theOrakle/glentronics
custom_components/glentronics/api.py
.py
daf558eca1c3ffef
7.57
13
"""Adds config flow for Glentronics.""" from __future__ import annotations import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers import selector from homeassistant.helpers.aiohttp_client import async_create_clientsessio...
theOrakle/glentronics
custom_components/glentronics/config_flow.py
.py
37d13bb3ce3338b5
7.57
13
"""DataUpdateCoordinator for glentronics.""" from __future__ import annotations from datetime import timedelta from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( DataUpdateCoordinator, UpdateFailed, ) from ho...
theOrakle/glentronics
custom_components/glentronics/coordinator.py
.py
f550e43324fc4277
7.57
13
"""GlentronicsEntity class.""" from __future__ import annotations from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import GlentronicsDataUpdateCoordinator class GlentronicsEntity(CoordinatorEntity): ...
theOrakle/glentronics
custom_components/glentronics/entity.py
.py
f4d0402fb7a8bac5
7.57
13
"""Sensor platform for glentronics.""" from __future__ import annotations from datetime import datetime from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.util import dt as dt_util from .const import DOMAIN, L...
theOrakle/glentronics
custom_components/glentronics/sensor.py
.py
7305086dac5f6511
7.57
13
"""Climate platform for MyHeat.""" from homeassistant.components.climate import ( PRESET_AWAY, PRESET_ECO, PRESET_HOME, PRESET_NONE, PRESET_SLEEP, ClimateEntity, ClimateEntityFeature, HVACAction, HVACMode, ) from homeassistant.components.climate import PRESET_ACTIVITY # noqa: F401 ...
vooon/hass-myheat
custom_components/myheat/climate.py
.py
95922450f16ef11e
7.63
17
from datetime import timedelta import logging from typing import Any from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_CLOUD_POLL_INTERVAL, DOMAIN # noqa...
vooon/hass-myheat
custom_components/myheat/coordinator.py
.py
2ea5e41a91505ade
7.63
17
"""Switch platform for MyHeat.""" from itertools import chain from homeassistant.components.switch import SwitchEntity from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import MhConfigEntry, MhDataUpdateCoordinato...
vooon/hass-myheat
custom_components/myheat/switch.py
.py
227fc470216e3615
7.63
17
"""Water Heater platform for MyHeat.""" from typing import Any from homeassistant.components.water_heater import ( STATE_OFF, STATE_ON, WaterHeaterEntity, WaterHeaterEntityFeature, ) from homeassistant.const import UnitOfTemperature from homeassistant.core import HomeAssistant, callback from homeassis...
vooon/hass-myheat
custom_components/myheat/water_heater.py
.py
59fa7825245ea9d1
7.63
17
"""Global fixtures for MyHeat integration.""" from unittest.mock import AsyncMock, patch import pytest from .const import MOCK_GET_DEVICE_INFO, MOCK_GET_DEVICES @pytest.fixture(autouse=True) def auto_enable_custom_integrations(enable_custom_integrations): yield # This fixture is used to prevent HomeAssistant...
vooon/hass-myheat
tests/conftest.py
.py
5468b8facfb76049
7.13
17
"""Helpers for MyHeat tests.""" from homeassistant.const import ATTR_FRIENDLY_NAME from pytest_homeassistant_custom_component.common import MockConfigEntry from custom_components.myheat.const import DOMAIN from .const import MOCK_CONFIG async def setup_mock_entry(hass) -> MockConfigEntry: """Set up the integra...
vooon/hass-myheat
tests/helpers.py
.py
e320e919ee47f0fc
8.13
17
"""Tests for MyHeat api.""" import asyncio import aiohttp from homeassistant.helpers.aiohttp_client import async_get_clientsession import pytest from custom_components.myheat.api import RPC_ENDPOINT, MhApiClient from .const import MOCK_GET_DEVICE_INFO, MOCK_GET_DEVICES, MOCK_NO_ERR def api_client(hass) -> MhApiCl...
vooon/hass-myheat
tests/test_api.py
.py
ce766ec17f4196c0
7.13
17
"""Test MyHeat config flow.""" from unittest.mock import patch from homeassistant import config_entries from homeassistant.data_entry_flow import FlowResultType import pytest from pytest_homeassistant_custom_component.common import MockConfigEntry from custom_components.myheat.const import BINARY_SENSOR # noqa: F40...
vooon/hass-myheat
tests/test_config_flow.py
.py
d0588512e1300cba
8.13
17
"""Mill API Client.""" from __future__ import annotations import asyncio import inspect import socket from datetime import UTC, datetime import aiohttp import async_timeout import json import websockets import homeassistant.util.ssl from .const import LOGGER HOST = "api.mill.com" AUTH_URL = f"https://{HOST}/app/v1...
theOrakle/mill
custom_components/mill/api.py
.py
fd453e525b4ede70
7.59
14
"""Binary sensor platform for mill.""" from __future__ import annotations from homeassistant.const import EntityCategory from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, BinarySensorEntityDescription, ) from .const import DOMAIN from .coordinator import Mil...
theOrakle/mill
custom_components/mill/binary_sensor.py
.py
68775fc10f4996d9
7.59
14
"""DataUpdateCoordinator for mill.""" from __future__ import annotations from datetime import timedelta from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( DataUpdateCoordinator, UpdateFailed, ) from homeassis...
theOrakle/mill
custom_components/mill/coordinator.py
.py
2fa3de42571555f9
7.59
14
"""MillEntity class.""" from __future__ import annotations from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, VERSION from .coordinator import MillDataUpdateCoordinator class MillEntity(CoordinatorEntity): """MillE...
theOrakle/mill
custom_components/mill/entity.py
.py
eabdc76862733b1c
7.59
14
"""Select platform for mill.""" from __future__ import annotations import asyncio from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.exceptions import ServiceValidationError from .const import DOMAIN, LOGGER from .coordinator import MillDataUpdateCoordinator from .en...
theOrakle/mill
custom_components/mill/select.py
.py
2ebd4852ef882918
7.59
14
"""Switch platform for mill.""" from __future__ import annotations from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription, SwitchDeviceClass from .const import DOMAIN, LOGGER from .coordinator import MillDataUpdateCoordinator from .entity import MillEntity ENTITY_DESCRIPTIONS = ( Switc...
theOrakle/mill
custom_components/mill/switch.py
.py
73dc5bed46a24641
7.59
14
from PIL import Image import requests import logging import os import re import base64 from io import BytesIO import markdown def include_css(st, filenames): content = "" for filename in filenames: with open(filename) as f: content += f.read() st.markdown(f"<style>{content}</style>", un...
WSE-research/image-to-ascii-art
util.py
.py
949eae3c54408d63
7.59
14
"""Markdown challenge notes.""" from datetime import datetime import typer from pwnv.utils import challenges_exists, config_exists app = typer.Typer(no_args_is_help=True, help="Manage challenge notes.") @app.command() @config_exists() @challenges_exists() def add( text: str, section: str = typer.Option("F...
CarixoHD/pwnv
pwnv/cli/note.py
.py
4255b6435cb3668a
7.57
13
from pathlib import Path import typer from pwnv.utils import config_exists app = typer.Typer(no_args_is_help=True, help="Back up and transfer workspaces.") @app.command() @config_exists() def backup( destination: Path = typer.Argument(Path("pwnv-backup")), force: bool = typer.Option(False, "--force", "-f")...
CarixoHD/pwnv
pwnv/cli/workspace.py
.py
0b0efd7e689c58a8
7.57
13
"""Utilities for loading and storing the ``pwnv`` configuration. The configuration is stored as JSON on disk. This module resolves the location of that file, exposes helpers to read and write it and provides simple accessor helpers used across the code base. """ import os from functools import lru_cache from pathlib...
CarixoHD/pwnv
pwnv/utils/config.py
.py
9420500e53734efe
7.57
13
import importlib import json import sys from typing import Iterable import pytest def _reload_modules(module_names: Iterable[str]) -> None: """Reload pwnv modules so they pick up fresh environment variables.""" importlib.invalidate_caches() for name in module_names: if name in sys.modules: ...
CarixoHD/pwnv
tests/conftest.py
.py
4119e4cdde2139ae
8.07
13
import uuid import pytest from pwnv.models import CTF, Challenge from pwnv.models.challenge import Category, Solved from pwnv.utils import ( add_challenge, add_ctf, get_challenges, get_ctfs, get_ctfs_path, is_duplicate, remove_challenge, remove_ctf, search_challenges, update_ch...
CarixoHD/pwnv
tests/test_crud_local.py
.py
2f403f08a24f44c4
8.07
13
""" Sensor calibration models compatible with the x-io/imufusion approach. Inertial calibration (accelerometer/gyroscope): calibrated = misalignment @ (diag(sensitivity) @ (raw - offset)) Magnetometer calibration: calibrated = soft_iron @ (raw - hard_iron) """ from dataclasses import dataclass, field from co...
uutzinger/pyIMU
pyIMU/calibration.py
.py
7c5e43a512f22182
7.66
20
""" Fusion-style AHRS based on Madgwick Chapter 7 concepts and xioTechnologies/Fusion behavior. Earth convention: NED (x: North, y: East, z: Down) """ from copy import copy import math from pyIMU.quaternion import Quaternion, Vector3D from pyIMU.utilities import accel2q, accelmag2q, clamp, clip try: from pyIMU i...
uutzinger/pyIMU
pyIMU/fusion.py
.py
1077b02f2c818365
7.66
20
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This is a python install script written for pyIMU python package. # pip3 install --upgrade setuptools wheel Cython build # # py -3 setup.py build_ext --inplace # py -3 setup.py bdist # py -3 setup.py sdist # py -3 setup.py bdist_wheel # pip3 install -e . # -e makes syml...
uutzinger/pyIMU
setup.py
.py
01556752077f5b59
7.66
20
import simplejson as json import logging import random import websocket import ExpertOptionAPI.api.global_values as global_value import pprint from functools import partial import pause from ExpertOptionAPI.api.constants import REGION import threading import ssl from ExpertOptionAPI._exceptions.Buying.BuyExceptions imp...
ChipaDevTeam/ExpertOptionApi
ExpertOptionAPI/api/backend/client.py
.py
a83c395466c38e94
7.45
7
"""Module for base ExpertOption base websocket chanel.""" class Base(object): """Class for base ExpertOption websocket chanel.""" # pylint: disable=too-few-public-methods add_token: bool = True def __init__(self, api): """ :param api: The instance of :class:`ExpertOptionAPI ...
ChipaDevTeam/ExpertOptionApi
ExpertOptionAPI/api/backend/ws/channels/base.py
.py
9588ee700f2afe68
7.45
7
"""Module for ExpertOption ping websocket chanel.""" from ExpertOptionAPI.api.backend.ws.channels.base import Base class Ping(Base): """Class for Binary ping websocket chanel.""" action = "ping" def __call__(self, ns: str = None, json=False): """Method to send message to ping websocket chanel. ...
ChipaDevTeam/ExpertOptionApi
ExpertOptionAPI/api/backend/ws/channels/ping.py
.py
a847d1f070e782d6
7.45
7
class RSI: def __init__(self) -> None: # NOTE: The data are the list of closes, if you use the Expert Option API as your data provider, you'll get the last item in each list (close) self.data = None # data are the candles # NOTE: THe avarage gain and loss will be accessible in the json `tr...
ChipaDevTeam/ExpertOptionApi
indicators.py
.py
aa7a23c8a622902f
7.45
7
import numpy as np import datetime import pandas as pd import json from ExpertOptionAPI.expert import EoApi as ExpertAPI class Stock: ticker = None dates = None closes = None highs = None lows = None opens = None volumes = None rsi = None def __init__(self): pass def l...
ChipaDevTeam/ExpertOptionApi
test2.py
.py
c73b3d560c1b37fb
7.95
7
from unittest.mock import patch import numpy as np import pytest import xarray as xr from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st import ozzy.core as oz @pytest.fixture def sample_dataset(): return oz.Dataset( { "x1": ("pid", np.random.rand(1000...
mtrocadomoreira/ozzy
tests/test_part_mixin.py
.py
4ffd5fe4e67fe966
7.98
8
""" Get-Content K/a.in | ./la_receta_definitiva.py > K/out/a.out """ from math import dist class UnionFind: def __init__(self, size: int): self.parent = list(range(size)) def find(self, node: int): if self.parent[node] != node: self.parent[node] = self.find(self.parent[node]) ...
algoritmiaUS/ada-byron
2025/regional-andaluza/K/code/py/la_receta_definitiva.py
.py
48c199e63ffd02a8
7.45
7
""" Get-Content K/a.in | ./la_receta_definitiva.py > K/out/a.out """ from math import dist class UnionFind: def __init__(self, size: int): self.parent = list(range(size)) def find(self, node: int): if self.parent[node] != node: self.parent[node] = self.find(self.parent[node]) ...
algoritmiaUS/ada-byron
2025/regional-andaluza/K/code/py/la_receta_definitiva_indices.py
.py
df9f214df4c1c414
7.45
7
from aiohttp import ClientError from yarl import URL class BaseHttpClientException(ClientError): """Base class for exceptions raised by `BaseHttpClient`.""" class UnhandledStatusException(BaseHttpClientException, KeyError): """Raised when a response status has no matching handler. Attributes: s...
andy-takker/asyncly
asyncly/client/handlers/exceptions.py
.py
5cdac81887dcfc0e
7.42
6
from asyncio import iscoroutinefunction from collections.abc import Awaitable, Callable from typing import Any from aiohttp import ClientResponse try: import orjson as json except ImportError: import json # type: ignore def parse_json( parser: Callable, loads: Callable = json.loads, ) -> Callable[[...
andy-takker/asyncly
asyncly/client/handlers/json.py
.py
e844a065d0043125
7.42
6
from collections.abc import Awaitable, Callable from typing import TypeVar from aiohttp import ClientResponse from pydantic import BaseModel T = TypeVar("T", bound=BaseModel) def parse_model(model: type[T]) -> Callable[[ClientResponse], Awaitable[T]]: """Build a response handler that validates the body into a P...
andy-takker/asyncly
asyncly/client/handlers/pydantic.py
.py
db25b276c2105145
7.42
6
import asyncio from http import HTTPStatus from time import perf_counter from types import TracebackType from typing import Any from aiohttp import BasicAuth, ClientResponse, ClientSession from yarl import URL from asyncly.client.base import ( BaseHttpClient, _unwrap_observable_transport_error, ) from asyncly...
andy-takker/asyncly
asyncly/client/metrics/instrumentable_client.py
.py
8a6032d4639ff2f4
7.42
6
from typing import Protocol, runtime_checkable @runtime_checkable class MetricsSink(Protocol): """Protocol for metrics backends used by `InstrumentableHttpClient`. Implement `observe_request` to record completed requests in any backend. `on_request_start` / `on_request_end` are **optional**: they bracke...
andy-takker/asyncly
asyncly/client/metrics/sinks/base.py
.py
16c81f1f87e7cb24
7.42
6
"""Normalize client exceptions into low-cardinality metric labels. The best-practice guidance for HTTP-client instrumentation splits failures into a small, fixed ``outcome`` set (for logical/operation success rate) and a slightly richer ``error_type`` set (for diagnosing *where* a failure happened). Putting the raw ex...
andy-takker/asyncly
asyncly/client/metrics/taxonomy.py
.py
381d34894959d4fe
7.42
6
"""Semi-automatic network-phase and connection-pool instrumentation. `InstrumentableHttpClient` records everything it can see from inside `_make_req`: the total request duration, status, outcome, and in-flight count. It cannot see *where* the time went — DNS resolution, waiting for a pooled connection, the TCP connect...
andy-takker/asyncly
asyncly/client/metrics/trace_config.py
.py
5400eaa6bac27ceb
7.42
6
"""Pytest plugin exposing `mock_routes` and `mock_service` fixtures. Users override `mock_routes` to declare the test server's API surface: @pytest.fixture def mock_routes(): return [MockRoute("GET", "/x", "x")] async def test_x(mock_service): mock_service.register("x", JsonResponse({"ok"...
andy-takker/asyncly
asyncly/pytest_plugin.py
.py
17743489c8d44c6b
7.92
6
class SrvMockerError(Exception): """Base exception for srvmocker.""" class SequenceExhausted(SrvMockerError): """Raised by SequenceResponse when responses run out and on_exhausted='raise'.""" class UnknownHandlerError(SrvMockerError): """Raised when register() is called with a name not declared in any M...
andy-takker/asyncly
asyncly/srvmocker/exceptions.py
.py
d054aaec089fc1b3
7.42
6
from collections.abc import Mapping, MutableMapping, MutableSequence from dataclasses import dataclass from types import MappingProxyType from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy from yarl import URL from asyncly.srvmocker.exceptions import UnknownHandlerError from asyncly.srvmoc...
andy-takker/asyncly
asyncly/srvmocker/models.py
.py
1c1cdf51b351002e
7.42
6
"""In-process forwarding HTTP proxy for tests. `start_proxy` spins up a real forward proxy (via aiohttp's ``RawTestServer``) that records every request passing through it and forwards it to the absolute target URL the client requested. Combined with :func:`start_service` it lets you test that a client genuinely route...
andy-takker/asyncly
asyncly/srvmocker/proxy.py
.py
f5014d45fa0b6ce6
7.42
6
from collections.abc import Mapping from http import HTTPStatus from aiohttp.web_request import Request from aiohttp.web_response import Response, StreamResponse from asyncly.srvmocker.responses.base import BaseMockResponse class DisconnectResponse(BaseMockResponse): """Disconnect the socket before response hea...
andy-takker/asyncly
asyncly/srvmocker/responses/faults.py
.py
341fffc7bd5ee586
7.42
6
from collections.abc import Mapping from http import HTTPStatus from typing import Any from aiohttp.web_request import Request from aiohttp.web_response import Response from asyncly.srvmocker.responses.base import BaseMockResponse from asyncly.srvmocker.responses.content import ContentResponse from asyncly.srvmocker....
andy-takker/asyncly
asyncly/srvmocker/responses/json.py
.py
0ca0595c3220f6df
7.42
6
from http import HTTPStatus from aiohttp.web_request import Request from aiohttp.web_response import Response from asyncly.srvmocker.responses.base import BaseMockResponse class RawResponse(BaseMockResponse): """Return arbitrary bytes with arbitrary headers — useful for testing client behavior on malformed ...
andy-takker/asyncly
asyncly/srvmocker/responses/raw.py
.py
08ac00f8cc1d0242
7.42
6
from asyncio import sleep from dataclasses import dataclass from aiohttp.web_request import Request from aiohttp.web_response import StreamResponse from asyncly.srvmocker.responses.base import BaseMockResponse TimeoutType = int | float @dataclass class LatencyResponse(BaseMockResponse): """Delay another respon...
andy-takker/asyncly
asyncly/srvmocker/responses/timeout.py
.py
6a605d1909798e1c
7.42
6
import torch from torch import nn class Classifier(nn.Module): """Linear node classifier.""" def __init__(self, hidden_size, num_classes): super().__init__() self.linear = nn.Linear(hidden_size, num_classes) self.reset_parameters() def forward(self, representations): logi...
yanliang3612/ReVar
layers/Classifier.py
.py
61a07740a62333f4
7.57
13
from collections import defaultdict import numpy as np import torch def make_label_dict(targets, mask): """Map each class label to its labeled node indices.""" label_dict = defaultdict(list) for index in mask.nonzero(as_tuple=False).view(-1).tolist(): label_dict[str(targets[index].item())].append...
yanliang3612/ReVar
src/sampling.py
.py
ce21dc7030b5f267
7.57
13
import random import numpy as np import torch from sklearn.metrics import balanced_accuracy_score, f1_score def set_random_seeds(seed=0): """Seed Python, NumPy, and PyTorch for deterministic repetitions.""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available...
yanliang3612/ReVar
src/utils.py
.py
3ba27aaa3f7b6adc
7.57
13
""" Constants for the METAR Weather integration. @license: MIT @github: https://github.com/smkrv/ha-metar-weather @source: https://github.com/smkrv/ha-metar-weather """ from __future__ import annotations import json from datetime import timedelta from enum import StrEnum from pathlib import Path from typing import D...
smkrv/ha-metar-weather
custom_components/ha_metar_weather/const.py
.py
de80aa22c8842a26
7.45
7
""" Storage handling for METAR Weather integration. @license: MIT @author: SMKRV @github: https://github.com/smkrv/ha-metar-weather @source: https://github.com/smkrv/ha-metar-weather """ from datetime import timedelta import logging from typing import Optional, Any import asyncio from copy import deepcopy from homeas...
smkrv/ha-metar-weather
custom_components/ha_metar_weather/storage.py
.py
dd316280dd59d07f
7.45
7
""" Aviation Weather Center (AWC) TAF API client. Minimal client for the AWC Data API's TAF endpoint (sibling of the METAR endpoint already used in awc_client.py). Currently only extracts the raw TAF string plus issue time - the taf sensor is the only TAF sensor this integration exposes right now, so nothing beyond th...
smkrv/ha-metar-weather
custom_components/ha_metar_weather/taf_client.py
.py
fc7818be6c5da664
7.45
7
""" Utility functions for METAR Weather integration. @license: MIT @github: https://github.com/smkrv/ha-metar-weather @source: https://github.com/smkrv/ha-metar-weather """ from __future__ import annotations import logging import re from typing import Any, Dict, Optional from homeassistant.const import UnitOfLength,...
smkrv/ha-metar-weather
custom_components/ha_metar_weather/utils.py
.py
a1bca66424187254
7.45
7
"""Statistics attributes follow the sensor's display unit. Issue #17: the state honoured the configured unit (°F) but historical_data / min_24h / max_24h / average_24h stayed in the internal base units (°C, km/h, km, hPa), so anything consuming the attributes on a non-metric setup read values wrong by a whole unit con...
smkrv/ha-metar-weather
tests/test_attribute_units.py
.py
7e068014e8f4c513
7.95
7
"""Full-stack tests for the cloud_layers sensor state (issues #11, #12). Real Home Assistant core + sensor platform with a mocked AWC response: assert the state string the user actually sees, including the localized French form from Gsyltc's reports ("clr Noneft" on clear sky, untranslated layer names). """ import py...
smkrv/ha-metar-weather
tests/test_integration_cloud_layers.py
.py
fa6e88a0fa544960
7.95
7
"""Regression tests for issue #8: AWC's quantized numerics must not clobber exact values derived from the raw METAR string. AWC's JSON reports visibility in statute miles, capped and quantized ("6+"), winds in whole knots (lossy for MPS stations) and altimeter as int hPa (lossy for US A-group reports). The raw METAR c...
smkrv/ha-metar-weather
tests/test_merge_policy.py
.py
2fee73c3f5bad5d2
7.95
7
"""Runway sensors must expose a valid default icon (issue #14). The descriptions used to point at "mdi:runway", which does not exist in the MDI set - the frontend silently rendered no icon at all. The fix switched both the aggregate and the per-runway sensors to "mdi:road-variant". """ import pytest from homeassistan...
smkrv/ha-metar-weather
tests/test_runway_icon.py
.py
659b50dc8168db0a
7.95
7
"""Integration services must survive an options-flow reload. update_station and clear_history were registered only in async_setup, while async_unload_entry removes them when the last entry unloads. An options-flow change reloads the entry - unload plus setup - and async_setup does not run again on reload, so both serv...
smkrv/ha-metar-weather
tests/test_services.py
.py
cbb2aada1411c567
7.95
7
"""Regression tests for issue #3: AWC and AVWX must produce identical output. The bug: the AWC (primary) path emitted raw codes ("-RA", "FEW") while the AVWX (fallback) path emitted parsed prose ("Light Rain", "Few (1-2 oktas)"), so the sensor state flipped representation depending on which source served the cycle. T...
smkrv/ha-metar-weather
tests/test_source_consistency.py
.py
b43dd0fa3c7e0d2c
7.95
7
"""Tests for unknown-vs-unavailable semantics (issue #13, PR #15). Fields legitimately absent from a METAR (no gust, no wind direction when the wind is calm or variable) must read "unknown", not "unavailable": most Lovelace cards decorate "unavailable" with a warning badge, which is wrong for normal, expected data gap...
smkrv/ha-metar-weather
tests/test_unknown_vs_unavailable.py
.py
545ffcac0170abc6
7.95
7
"""docker2mqtt type definitions.""" from datetime import datetime from typing import Literal, NotRequired, TypedDict ContainerEventStateType = Literal["on", "off"] """Container event state""" ContainerEventStatusType = Literal[ "paused", "running", "stopped", "destroyed", "created" ] """Container event docker st...
miaucl/docker2mqtt
docker2mqtt/type_definitions.py
.py
b0f8406cdb9b9fa9
7.5
9
import datetime import random from typing import Literal, Optional, List, TypedDict from pydantic import ConfigDict, Field from typing_extensions import override from nonebot.adapters import Event as BaseEvent from nonebot.compat import model_dump from .message import Message class Event(BaseEvent): to_user_id...
YangRucheng/nonebot-adapter-wxmp
nonebot/adapters/wxmp/event.py
.py
dc52da4967ac9f9b
7.52
10
import re from enum import Enum from pathlib import Path from typing import TYPE_CHECKING, Iterable, Optional, Type, TypedDict, Union, cast from pydantic import HttpUrl from typing_extensions import override from nonebot.adapters import ( Message as BaseMessage, ) from nonebot.adapters import ( MessageSegment...
YangRucheng/nonebot-adapter-wxmp
nonebot/adapters/wxmp/message.py
.py
91047ba031f6c1db
7.52
10
import base64 import hashlib import secrets from .utils import log try: from Crypto.Cipher import AES # type: ignore except ImportError: log("ERROR", "Please install nonebot-adapter-wxmp[crypto] to enable encrypt") def decrypt( encrypt_data: str, encoding_aes_key: str, appid: str, ) -> str: ...
YangRucheng/nonebot-adapter-wxmp
nonebot/adapters/wxmp/secret.py
.py
c7e651fdee6f20c8
7.52
10
import asyncio from nonebot.drivers import Response from .exception import OfficialReplyError class OfficialReplyResult: """ 公众号被动回复内容储存 """ def __init__(self) -> None: self._futures: dict[str, asyncio.Future] = {} def set_resp(self, event_id: str, resp: Response) -> None: """ 设置响应 """...
YangRucheng/nonebot-adapter-wxmp
nonebot/adapters/wxmp/store.py
.py
d93b6c16cb9bde64
7.52
10
import importlib.metadata import logging import os import urllib.request from datetime import datetime, timezone from email.utils import parsedate_to_datetime def env_flag(name: str, fallback: str | None = None) -> bool: """Return True if the environment variable ``name`` (or ``fallback``) is set to a truthy ...
PrivateCoffee/wikimore
src/wikimore/config.py
.py
1fd7756cb26ae302
7.52
10
import json import logging import urllib.error from concurrent.futures import ThreadPoolExecutor, as_completed from html import escape from typing import Dict, List, Tuple, Union from urllib.parse import quote from .cache import cache from .config import urlopen logger = logging.getLogger(__name__) # Per-wiki licens...
PrivateCoffee/wikimore
src/wikimore/fetchers.py
.py
d15d491f0ad0d72a
7.52
10
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import glob import yaml import yamale from yamale.validators import DefaultValidators def validateSiteConfigs(): schemaFile = os.path.join('sites', 'sites.schema') sitesYaml = glob.glob(os.path.join('sites', "*.yaml")) for file in sitesYam...
eCrimeLabs/cratos-fastapi
app/config.py
.py
58cef88d5cc98f19
7.57
13
import base64 import os import pytest import yaml from fastapi.testclient import TestClient from app import dependencies from app.config import GLOBALCONFIG from app.main import app client = TestClient(app) SALT = GLOBALCONFIG['salt'].encode() PASSWORD = GLOBALCONFIG['encryption_key'].encode() FIXTURE_FQDN = "crato...
eCrimeLabs/cratos-fastapi
tests/unit/test_auth.py
.py
a7b5e52805314d50
8.07
13
"""Catalogue map for ABS data.""" from functools import cache from io import StringIO from pandas import DataFrame, Index, Series, read_html from readabs.download_cache import CacheError, HttpError, get_file # Constants ABS_CATALOGUE_URL = "https://www.abs.gov.au/about/data-services/help/abs-time-series-directory" ...
bpalmer4/readabs
src/readabs/abs_catalogue.py
.py
f4339035a3b26f77
7.5
9
"""Support for working with ABS metadata.""" from dataclasses import dataclass @dataclass(frozen=True) class Metacol: """Column names for ABS metadata DataFrames. A frozen dataclass that holds standardized column names used in ABS metadata. The frozen property ensures immutability of the column name...
bpalmer4/readabs
src/readabs/abs_meta_data.py
.py
a776ce405bfc5499
7.5
9
"""download_cache.py - a module for downloading and caching data from the web. The default cache directory can be specified by setting the environment variable READABS_CACHE_DIR. """ # system imports import re from datetime import UTC, datetime from hashlib import sha256 from os import getenv, utime from pathlib impo...
bpalmer4/readabs
src/readabs/download_cache.py
.py
54c5885b11771048
7.5
9
"""Scan an ABS webpage for links to Excel and zip files.""" from pathlib import Path from typing import NotRequired, Unpack from urllib.parse import urlparse from bs4 import BeautifulSoup, Tag # local imports from readabs.download_cache import CacheError, FileKwargs, HttpError, get_file # --- Constants DEFAULT_ABS_...
bpalmer4/readabs
src/readabs/get_abs_links.py
.py
964af0b1b4ee2a3d
7.5
9
"""Find and extract DataFrames from an ABS webpage.""" # --- imports --- # standard library imports import zipfile from functools import cache from io import BytesIO from pathlib import Path from typing import Any, Unpack # analytic imports import pandas as pd from pandas import DataFrame from readabs.abs_catalogue ...
bpalmer4/readabs
src/readabs/grab_abs_url.py
.py
0e779a0b7f31b787
7.5
9
"""Extract links to RBA data files from the RBA website.""" import re from functools import cache from typing import Any from bs4 import BeautifulSoup, Tag from pandas import DataFrame from readabs.download_cache import CacheError, HttpError, get_file # Constants EXPECTED_PAIR_LENGTH = 2 @cache def rba_catalogue(...
bpalmer4/readabs
src/readabs/rba_catalogue.py
.py
e3a623c38163ac55
7.5
9
"""Get specific ABS data series by searching for the ABS data item descriptions. This module provides functionality to search and retrieve ABS data series by their descriptions rather than series IDs. """ import inspect from typing import Any # Analytic imports import pandas as pd # local imports from readabs.abs_m...
bpalmer4/readabs
src/readabs/read_abs_by_desc.py
.py
81668440440e806e
7.5
9
"""Download *timeseries* data from the Australian Bureau of Statistics. Download timeseries data from the Australian Bureau of Statistics (ABS) for a specified ABS catalogue identifier. """ import calendar from functools import cache from pathlib import Path from typing import Any, Unpack import pandas as pd from pa...
bpalmer4/readabs
src/readabs/read_abs_cat.py
.py
b922820557dde4df
7.5
9
"""Get specific ABS data series by their ABS series identifiers.""" from collections.abc import Sequence from typing import Unpack, cast from pandas import DataFrame, Index, PeriodIndex, concat from readabs.abs_meta_data import metacol from readabs.read_abs_cat import read_abs_cat from readabs.read_support import Re...
bpalmer4/readabs
src/readabs/read_abs_series.py
.py
e49385378d7a1215
7.5
9
"""Read a table from the RBA website and store it in a pandas DataFrame.""" import re from io import BytesIO from typing import Any, cast from pandas import ( DataFrame, DatetimeIndex, Index, Period, PeriodIndex, Series, Timestamp, period_range, read_excel, ) from readabs.download...
bpalmer4/readabs
src/readabs/read_rba_table.py
.py
68dd23818a62ad02
7.5
9
"""Support for reading ABS data functions. This module provides validation and default value handling for keyword arguments used across ABS data reading functions. It ensures consistent parameter handling and validates that at least one data source option is enabled. """ from typing import Any, NotRequired, TypedDict...
bpalmer4/readabs
src/readabs/read_support.py
.py
b6c25fc6bbe54bd1
7.5
9
"""Recalibrate a Series or DataFrame so the data is in the range -1000 to 1000.""" import sys from collections.abc import Callable from operator import mul, truediv from typing import Any import numpy as np from pandas import DataFrame, Series from readabs.datatype import Datatype as DataT # Constants NDIM_SERIES =...
bpalmer4/readabs
src/readabs/recalibrate.py
.py
c33e4794c63b10fc
7.5
9
"""Search a DataFrame of ABS meta data using search terms. Using a dictionary of search terms, identify the row or rows that match all of the search terms. """ from typing import Any from pandas import DataFrame, Index # local imports from readabs.abs_meta_data import metacol as mc from readabs.read_abs_cat import ...
bpalmer4/readabs
src/readabs/search_abs_meta.py
.py
b605f7608eedb59b
7.5
9
"""Utilities for working with ABS timeseries data.""" from typing import cast from numpy import nan from pandas import DataFrame, DatetimeIndex, PeriodIndex, Series from readabs.datatype import Datatype as DataT # --- constants MONTHS_IN_YEAR = 12 QUARTERS_IN_YEAR = 4 MONTHS_IN_QUARTER = 3 # --- exceptions class ...
bpalmer4/readabs
src/readabs/utilities.py
.py
a05b8227d434305d
7.5
9
"""Quick and dirty test code.""" import readabs as ra def clean_diagnostic_test(): """ A simple, untweaked script to demonstrate the raw error from readabs. This script contains no error handling and is expected to crash. """ catalogues_to_test = { #'3401.0': 'Overseas Migration', ...
bpalmer4/readabs
test/test.py
.py
4d940d009efd5540
7
9
"""Test the offline stale-cache fallback in download_cache.get_file(). These tests are fully hermetic: they monkeypatch ``requests`` so no network access is made. The point of the feature is to keep readabs working offline (e.g. on a plane) by falling back to previously cached data, so - fittingly - these tests can th...
bpalmer4/readabs
test/test_offline_fallback.py
.py
fbd1da000d8ce5f2
8
9
"""Test retrieving data using a direct URL for discontinued series.""" import readabs as ra def test_discontinued_retail_sales(): """ Test retrieving the discontinued Retail Trade series (8501.0) using a direct URL. This series was discontinued after June 2025 and is no longer in the ABS Time Series Dire...
bpalmer4/readabs
test/test_url_retrieval.py
.py
fe96af00430674d8
7
9