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
# Copyright 2026 Canonical Ltd. # See LICENSE file for licensing details. """Useful types for integration tests.""" from typing import NamedTuple class App(NamedTuple): """Holds deployed application information for app_fixture.""" name: str class Credentials(NamedTuple): """Credentials to login to an...
canonical/discourse-k8s-operator
tests/integration/types.py
.py
77e4d0848f6a217b
8.02
10
# Copyright 2026 Canonical Ltd. # See LICENSE file for licensing details. """Discourse K8s operator charm fixtures.""" import pytest from ops import testing from charm import CONTAINER_NAME from constants import DATABASE_NAME @pytest.fixture(name="base_state") def base_state_fixture(discourse_container, postgresql...
canonical/discourse-k8s-operator
tests/unit/conftest.py
.py
5dfcbcc934262554
8.02
10
# Copyright 2026 Canonical Ltd. # See LICENSE file for licensing details. """helpers for the unit tests.""" import contextlib import typing import unittest.mock from ops.model import Container from ops.testing import Harness from charm import DiscourseCharm DATABASE_NAME = "discourse" def start_harness( # pylin...
canonical/discourse-k8s-operator
tests/unit_harness/helpers.py
.py
9f5d89ee63a1a5f6
8.02
10
""" A base device abstraction for all the aduino devices that have RESTful API endpoints """ import abc import time from typing import Dict, Union, Optional import requests class BaseArduinoDevice(abc.ABC): def __init__(self, ip_address: str, port: int = 80): self.ip_address = ip_address self.por...
CederGroupHub/alab_control
alab_control/_base_arduino_device.py
.py
417cd55c016fd309
7.5
9
from __future__ import annotations import time from enum import IntEnum from struct import pack, unpack from serial import Serial from serial.tools.list_ports import comports class Commands(IntEnum): ROR = 1 ROL = 2 MST = 3 MVP = 4 SAP = 5 GAP = 6 RFS = 13 SIO = 14 GIO = 15 W...
CederGroupHub/alab_control
alab_control/_base_tmcl_stepper_motor_controller.py
.py
69ef2abc3fa023bb
7.5
9
import logging import time from enum import Enum from alab_control._base_arduino_device import BaseArduinoDevice logger = logging.getLogger(__name__) class BallDispenserState(Enum): STOPPED = "stopped" RUNNING = "running" class EmptyError(Exception): """An error that is raised when the ball dispenser ...
CederGroupHub/alab_control
alab_control/ball_dispenser/ball_dispenser.py
.py
eb03457728b074ab
7.5
9
import logging logger = logging.getLogger(__name__) import time from enum import Enum from alab_control._base_arduino_device import BaseArduinoDevice class CapDispenserState(Enum): RUNNING = "RUNNING" STOPPED = "STOPPED" class CapDispenser(BaseArduinoDevice): MAP ={ "A":1, "B":2, ...
CederGroupHub/alab_control
alab_control/cap_dispenser/cap_dispenser.py
.py
459a817d6c4a8a46
7.5
9
import logging logger = logging.getLogger(__name__) from enum import Enum from alab_control._base_arduino_device import BaseArduinoDevice class CapperState(Enum): OPEN = "open" CLOSE = "closed" class Capper(BaseArduinoDevice): ENDPOINTS = { "state": "/state", "open": "/open", "...
CederGroupHub/alab_control
alab_control/capper/capper.py
.py
8b84a65f518e54c4
7.5
9
from __future__ import annotations import time from enum import Enum from pymodbus.client.sync import ModbusSerialClient as ModbusClient from pymodbus.exceptions import ModbusException class RailInitializationStatus(Enum): NOT_INITIALIZING = 1 INITIALIZING = 0 class RailStatus(Enum): MOVING = 1 AR...
CederGroupHub/alab_control
alab_control/dh_linear_rail/dh_linear_rail.py
.py
54b5720f71e17aa9
7.5
9
from __future__ import annotations import time from enum import Enum from pymodbus.client.sync import ModbusSerialClient as ModbusClient from pymodbus.exceptions import ModbusException class InitializationStatus3G(Enum): NOT_INITIALIZED = 0 INITIALIZED = 1 INITIALIZING = 2 class RailStatus3G(Enum): ...
CederGroupHub/alab_control
alab_control/dh_linear_rail/dh_linear_rail_mce_3g.py
.py
29fecb12fbed1ab9
7.5
9
import logging logger = logging.getLogger(__name__) import re import numpy as np import xmltodict import socket import time import os from typing import List, Tuple, Union, Dict from enum import Enum ### Exceptions class AerisException(Exception): """Generic exception class for Aeris errors""" pass class S...
CederGroupHub/alab_control
alab_control/diffractometer_aeris/aeris.py
.py
b75f32151d52fb4e
7.5
9
import logging logger = logging.getLogger(__name__) import time from enum import Enum import socket import re from alab_control._base_arduino_device import BaseArduinoDevice class DoorControllerState(Enum): RUNNING = "RUNNING" STOP = "STOP" ERROR = "ERROR" class DoorController(BaseArduinoDevice): d...
CederGroupHub/alab_control
alab_control/door_controller/door_controller.py
.py
f8abb44f08bc92e1
7.5
9
import time from alab_control._base_arduino_device import BaseArduinoDevice class DoorController(BaseArduinoDevice): ALL_DOORS = ["A", "B"] def open_furnace(self, name: str, block: bool = True): if name not in self.ALL_DOORS: raise ValueError( f"Invalid door name: {name}....
CederGroupHub/alab_control
alab_control/door_controller/door_controller_gpss.py
.py
c214d9ab9f7acae7
7.5
9
from __future__ import annotations import subprocess import tempfile import time from pathlib import Path import qrcode from bson import ObjectId from PIL import Image, ImageDraw, ImageFont class DYMOLabelWriter: """ This is the label printer made by DYMO """ LABEL_WIDTH = 1 # inches LABEL_HEI...
CederGroupHub/alab_control
alab_control/dymo_labelwriter/dymo_labelwriter.py
.py
b0288d821b8a06ba
7.5
9
import time from enum import Enum from alab_control._base_arduino_device import BaseArduinoDevice class EnderCapperRelayState(Enum): RUNNING = "RUNNING" STOPPED = "STOPPED" class EnderCapperRelay(BaseArduinoDevice): ENDPOINTS = { "state": "/state", "open-top-gripper": "/open-top-gripper"...
CederGroupHub/alab_control
alab_control/ender_capper_relay/ender_capper_relay.py
.py
ebbe80ec4895e0bb
7.5
9
import logging import time from csv import DictReader from datetime import timedelta from enum import Enum, unique from pathlib import Path from threading import Lock from typing import NamedTuple, Optional, Dict, Any, Callable, List logger = logging.getLogger(__name__) from pymodbus.client.sync import ModbusSerialCli...
CederGroupHub/alab_control
alab_control/furnace_3216p/furnace_driver.py
.py
491e8cc2e9e7f1b8
7.5
9
import requests from typing import Dict, List, Literal, Union from ..error import LabmanError, LabmanCommunicationError from .enums import WorkflowValidationResult VALID_QUADRANTS = [1, 2, 3, 4] VALID_DOSING_HEADS = [i + 1 for i in range(24)] class LabmanAPI: REQUESTS_KWARGS = { "timeout": 5, } # ke...
CederGroupHub/alab_control
alab_control/labman/api/api.py
.py
b82a782c04506b74
7.5
9
""" A convenient wrapper for MongoClient. We can get a database object by calling ``get_collection`` function. """ from typing import Optional import pymongo from pymongo import collection, database from .db_lock import MongoLock class _GetMongoCollection: client: Optional[pymongo.MongoClient] = None db: Op...
CederGroupHub/alab_control
alab_control/labman/database/data_objects.py
.py
2ff6c6d37d4753d7
7.5
9
""" This file defines the database lock class, which can block other processes to access the database. """ import time from contextlib import contextmanager from typing import Optional from pymongo.collection import Collection from pymongo.errors import DuplicateKeyError class MongoLockAcquireError(Exception): ...
CederGroupHub/alab_control
alab_control/labman/database/db_lock.py
.py
a39fb5d793d86886
7.5
9
class LabmanError(Exception): """A generic error for the Labman""" class PowderLoadingError(LabmanError): """A generic error while loading powders into the Labman""" class WorkflowError(LabmanError): """A generic error for Labman workflows""" class WorkflowFullError(WorkflowError): """Error indica...
CederGroupHub/alab_control
alab_control/labman/error.py
.py
2d1f429d0d78ee0f
7.5
9
"""Configuration environment variables for the API.""" from pathlib import Path from typing import Any from pydantic import Field, computed_field from pydantic_settings import BaseSettings, SettingsConfigDict NEUROBAGEL_CONFIG_REPO = "neurobagel/communities" DEFAULT_NEUROBAGEL_CONFIG = "Neurobagel" # NOTE: We store...
neurobagel/api
app/api/env_settings.py
.py
4a29970d2e2e6a01
7.45
7
import logging from typing import NoReturn, Type def get_logger(name: str) -> logging.Logger: """Create and return a logger with the specified name.""" return logging.getLogger(name) def log_and_raise_error( logger: logging.Logger, exception_type: Type[Exception], message: str ) -> NoReturn: """ ...
neurobagel/api
app/api/logger.py
.py
c9170af1b82e76b5
7.45
7
"""Data models.""" from enum import Enum from fastapi.exceptions import HTTPException from pydantic import BaseModel, ConfigDict, Field, RootModel, model_validator from typing_extensions import Self CONTROLLED_TERM_REGEX = r"^[a-zA-Z]+[:]\S+$" # TODO: Check if version regex is too restrictive # Constrain version nu...
neurobagel/api
app/api/models.py
.py
b1c17d493f2a1886
7.45
7
from .. import crud, env_settings from ..env_settings import settings from ..models import StandardizedTermVocabularyResponse def create_get_instances_handler(data_element_uri: str): """Create the handler function (path function) for the base path of an attribute router.""" async def get_instances(): ...
neurobagel/api
app/api/routers/route_factory.py
.py
48b23d3e622426c6
7.45
7
"""Functions for handling authentication. Same ones as used in Neurobagel's federation API.""" import jwt from fastapi import HTTPException, status from fastapi.security.utils import get_authorization_scheme_param from jwt import PyJWKClient, PyJWTError from .env_settings import Settings, settings from .logger import...
neurobagel/api
app/api/security.py
.py
b9ecb71d9b78d61f
7.45
7
from typing import Literal from pydantic import BaseModel from pydantic.alias_generators import to_snake SPARQL_SELECTED_VARS = [ "dataset", "subject", ] def format_value(value): """Returns the SPARQL-formatted representation of a value.""" if isinstance(value, str): # If the value looks lik...
neurobagel/api
app/api/sparql_models.py
.py
39b815ba5ffe69a8
7.45
7
"""Main app.""" import logging from contextlib import asynccontextmanager import uvicorn from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html from fastapi.responses import HTMLResponse, RedirectResponse from .api ...
neurobagel/api
app/main.py
.py
e82725b33605f866
7.45
7
from app.api import crud BASE_ROUTE = "/pipelines" def test_get_pipeline_versions_response(test_app, monkeypatch): """ Given a request to /pipelines/{pipeline_term}/versions with a valid pipeline name, returns a dict where the key is the pipeline resource and the value is a list of pipeline versions. ...
neurobagel/api
tests/test_pipelines.py
.py
d14c35ce721adc99
7.95
7
import pytest from app.api import crud from app.main import app, favicon_url @pytest.mark.parametrize( "root_path", ["", "/node"], ) def test_root(test_app, root_path, monkeypatch): """ Given a GET request to the root endpoint as defined by the root_path, check for 200 status and expected content...
neurobagel/api
tests/test_routing.py
.py
0c197564dd913ea2
7.95
7
import logging import pytest from fastapi import HTTPException from app.api.env_settings import settings from app.api.security import verify_token def test_missing_client_id_raises_error_when_auth_enabled( test_app, monkeypatch, enable_auth, set_temp_datasets_metadata_file, caplog ): """Test that a missing ...
neurobagel/api
tests/test_security.py
.py
bf244b175f3cbecf
7.95
7
import pytest from app.api import crud, env_settings from app.main import settings ROUTE = "/subjects" @pytest.mark.parametrize( "valid_dataset_uuids", [ ["http://neurobagel.org/vocab/12345"], [ "http://neurobagel.org/vocab/12345", "http://neurobagel.org/vocab/67890",...
neurobagel/api
tests/test_subjects.py
.py
640e15027b25efb0
7.95
7
"""Telegram API client factories — cached main and service account instances. Extracted from ``_dependencies.common.misc`` to keep the ``common`` package free of messenger-specific dependencies. """ from functools import lru_cache from _dependencies.bot.telegram_api_wrapper import TGApiBase from _dependencies.common...
cherrytea-dev/la_searcher_bot
src/_dependencies/bot/messaging.py
.py
b28953ac1c603f43
7.56
12
"""Messenger client implementations — Telegram, VK, and MAX. Wraps existing low-level API clients (``TGApiBase``, ``VKApi``, ``maxapi.Bot``) into the abstract ``MessengerClient`` interface defined in ``_dependencies.commons``. """ import asyncio import random from collections.abc import Coroutine from typing import ...
cherrytea-dev/la_searcher_bot
src/_dependencies/bot/messenger_clients.py
.py
c7ab73cb0ea77597
7.56
12
import logging from datetime import datetime from enum import Enum import sqlalchemy from _dependencies.common.commons import ( Messenger, save_default_notification_settings, sqlalchemy_get_pool, ) class ManageUserAction(str, Enum): block_user = 'block_user' unblock_user = 'unblock_user' uns...
cherrytea-dev/la_searcher_bot
src/_dependencies/bot/users_management.py
.py
c501c55abb9d839b
7.56
12
import json import logging from functools import cache from typing import Any import httpx from _dependencies.common.commons import get_app_config class VkApiError(Exception): """Raised when VK API returns an error response. Attributes: error_code: VK API error code (e.g., 901, 914, 917) er...
cherrytea-dev/la_searcher_bot
src/_dependencies/bot/vk_api_client.py
.py
973bb2669d9d85a2
7.56
12
"""PostgreSQL advisory-lock based mutual exclusion for cloud functions.""" import logging from contextlib import contextmanager from typing import Iterator from sqlalchemy import text from sqlalchemy.engine import Engine logger = logging.getLogger(__name__) class FunctionLockError(Exception): """Raised when an...
cherrytea-dev/la_searcher_bot
src/_dependencies/common/lock_manager.py
.py
d17432a2c7ff1e50
7.56
12
import asyncio import datetime import json import math import random from dataclasses import dataclass, field from functools import wraps from typing import Any, Callable, Mapping, Sequence def time_counter_since_search_start(start_time: datetime.datetime) -> tuple[str, int]: """Count timedelta since the beginnin...
cherrytea-dev/la_searcher_bot
src/_dependencies/common/misc.py
.py
29b4770bf2d42677
7.56
12
import logging from enum import Enum from pydantic import BaseModel, RootModel from _dependencies.common.yandex_tools import ( Ctx as YandexCtx, ) from _dependencies.common.yandex_tools import ( make_api_call_cloud, process_pubsub_message_cloud, send_topic_cloud, ) Ctx = YandexCtx class Topics(Enum...
cherrytea-dev/la_searcher_bot
src/_dependencies/common/pubsub.py
.py
1338e5abe018ccfa
7.56
12
"""TelegramMessage — typed contract for Telegram outgoing messages. Replaces raw ``dict`` usage across the codebase: all ``send_message`` and ``edit_message_text`` calls now accept a typed model instead of assembling and disassembling a loose dictionary. The model deliberately excludes ``chat_id`` — the recipient is ...
cherrytea-dev/la_searcher_bot
src/_dependencies/common/telegram_message.py
.py
918dc7df847d18b2
7.56
12
"""Shared data models used by both Telegram and VK bots. These types were previously duplicated across communicate/_utils/common.py and vk_bot/_utils/database_common.py. They are consolidated here to avoid divergence and simplify maintenance. """ from dataclasses import dataclass from enum import Enum class DialogS...
cherrytea-dev/la_searcher_bot
src/_dependencies/models.py
.py
bfe6cf34f730dc80
7.56
12
"""Age preference management mixin — consolidated.""" import datetime import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase from _dependencies.models import AgePeriod class AgePrefMixin(DBClientMixinBase): """User age period preference operations.""" def save_age_preference(self, ...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/age_pref.py
.py
996ef0dfc436f073
7.56
12
"""Dialog state management mixin — consolidated.""" import datetime import logging import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase from _dependencies.models import DialogState class DialogStateMixin(DBClientMixinBase): """Bot dialog state tracking. Manages what kind of input...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/dialog_state.py
.py
5bba93fe1e3d4e1b
7.56
12
"""Forum attribute management mixin — consolidated.""" import datetime import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase class ForumAttributeMixin(DBClientMixinBase): """User forum attribute operations (linking forum account).""" def get_forum_attributes(self, user_id: int) ->...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/forum_attribute.py
.py
adec06d0d24acbc8
7.56
12
"""Geographic preferences (coordinates, radius) mixin — consolidated.""" import datetime import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase class GeoPrefMixin(DBClientMixinBase): """User geographic preference operations — coordinates and radius.""" def save_coordinates(self, us...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/geo_pref.py
.py
74f3a6428a934c67
7.56
12
"""Notification preference management mixin — consolidated.""" import sqlalchemy from _dependencies.common.commons import PREF_DICT from _dependencies.common.db_client import DBClientMixinBase class NotificationPrefMixin(DBClientMixinBase): """User notification preference operations.""" def get_all_user_pr...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/notification_pref.py
.py
8f2b1ef2bad26ba2
7.56
12
"""Region (forum folder) subscription management mixin — consolidated.""" import datetime import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase class RegionMixin(DBClientMixinBase): """User region (forum folder) subscription operations.""" def get_user_regions(self, user_id: int) ...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/region.py
.py
58fd13b052e06bf7
7.56
12
"""Search following (whitelist/blacklist) management mixin — consolidated.""" import datetime import sqlalchemy from _dependencies.common.commons import SearchFollowingMode from _dependencies.common.db_client import DBClientMixinBase class SearchFollowingMixin(DBClientMixinBase): """Search following (whitelist...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/search_following.py
.py
622f40f0d7e6a421
7.56
12
"""Reset user settings to registration defaults — consolidated mixin.""" import datetime import sqlalchemy from _dependencies.common.commons import save_default_notification_settings from _dependencies.common.db_client import DBClientMixinBase from _dependencies.user_repository.topic_type import default_topic_type_i...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/settings_reset.py
.py
d62b3772b1884560
7.56
12
"""Settings summary mixin — consolidated.""" import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase from _dependencies.models import UserSettingsSummary class SettingsSummaryMixin(DBClientMixinBase): """User settings summary operations.""" def get_settings_summary(self, user_id: int...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/settings_summary.py
.py
d0a734029620349c
7.56
12
"""System role management mixin — consolidated from communicate and VK bot.""" import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase class SystemRoleMixin(DBClientMixinBase): """User system role operations (admin, tester, etc.).""" def get_user_sys_roles(self, user_id: int) -> list...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/system_role.py
.py
8da3806ce91e28f7
7.56
12
"""Topic type preference management mixin — consolidated.""" import datetime import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase def default_topic_type_ids(user_role: str | None) -> list[int]: """Return default topic type IDs for a given user role. Single source of truth used bo...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/topic_type.py
.py
0059847bdfbc1441
7.56
12
"""User registration and onboarding mixin — consolidated.""" import datetime import logging import sqlalchemy from _dependencies.bot.users_management import ( ManageUserAction, register_new_user, save_onboarding_step, update_user_status, ) from _dependencies.common.commons import Messenger from _depe...
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/user.py
.py
8dcaabb8e6b6e59b
7.56
12
"""VK identity mixin — user resolution by VK ID, consolidated.""" from types import SimpleNamespace import sqlalchemy from _dependencies.common.db_client import DBClientMixinBase class VKIdentityMixin(DBClientMixinBase): """User resolution by VK ID. Methods for finding/linking users by their VKontakte ID....
cherrytea-dev/la_searcher_bot
src/_dependencies/user_repository/vk_identity.py
.py
12905bfd47940dbf
7.56
12
import hashlib import logging import re import urllib.parse from dataclasses import dataclass from functools import lru_cache import requests from retry import retry from _dependencies.common.commons import get_forum_proxies from _dependencies.common.pubsub import recognize_title_via_api from _dependencies.forum.cont...
cherrytea-dev/la_searcher_bot
src/check_first_posts_for_changes/_legacy/_utils/forum.py
.py
ea46fa897d84cd8b
7.56
12
"""Script does several things: 1. checks if the first posts of the searches were changed 2. checks active searches' status (Ищем, НЖ, НП, etc.) 3. checks active searches' visibility (accessible for everyone, restricted to a certain group or permanently deleted). Updates are either saved in PSQL or send via pub/sub to o...
cherrytea-dev/la_searcher_bot
src/check_first_posts_for_changes/_legacy/main.py
.py
7b70778336afb3b3
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT import datetime from typing import Protocol class AsyncDate(Protocol): """Интерфейс даты для вычисления с возможностью переключения контекста.""" async def date(self) -> datetime.date...
blablatdinov/tg-quranbot
src/app_types/async_date.py
.py
3737dc4dde6da5dd
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT import datetime as dt from typing import Protocol class AsyncDateTime(Protocol): """Интерфейс даты/времени для вычисления с возможностью переключения контекста.""" async def datetime(...
blablatdinov/tg-quranbot
src/app_types/async_date_time.py
.py
921c22f705f341eb
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Protocol class AsyncSupportsBool(Protocol): """Интерфейс объектов, которые можно привести к булевому значению.""" async def to_bool(self) -> bool: """Привед...
blablatdinov/tg-quranbot
src/app_types/async_supports_bool.py
.py
6a62e3a70d2960f0
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Protocol class AsyncSupportsStr(Protocol): """Интерфейс объектов, которые можно привести к строке.""" async def to_str(self) -> str: """Приведение к строке....
blablatdinov/tg-quranbot
src/app_types/async_supports_str.py
.py
cb2dc17807550eb5
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override from app_types.intable import AsyncInt @final class CachedAsyncInt(AsyncInt): # noqa: PEO200. Class has mutable state for caching """Кэшируемое число."...
blablatdinov/tg-quranbot
src/app_types/cached_async_int.py
.py
2044651df031e5f8
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Protocol class Counter(Protocol): """Протокол счетчика. Является интерфейсом для prometheus метрик """ def inc(self) -> None: """Увеличение значени...
blablatdinov/tg-quranbot
src/app_types/counter.py
.py
cae198311fa9868c
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT import datetime as dt from typing import Protocol class DateTime(Protocol): """Интерфейс даты/времени.""" def datetime(self) -> dt.datetime: """Дата/время."""
blablatdinov/tg-quranbot
src/app_types/date_time.py
.py
429d2b3dd1afd996
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import SupportsInt, final, override import attrs from app_types.intable import AsyncInt @final @attrs.define(frozen=True) class FkAsyncInt(AsyncInt): """Фейковое число.""" ...
blablatdinov/tg-quranbot
src/app_types/fk_async_int.py
.py
538dca128f8435f1
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs from app_types.async_int_or_none import AsyncIntOrNone @final @attrs.define(frozen=True) class FkAsyncIntOrNone(AsyncIntOrNone): """FkAsyn...
blablatdinov/tg-quranbot
src/app_types/fk_async_int_or_none.py
.py
d0be1817dd01439f
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Generic, final, override import attrs from app_types.listable import AsyncListable, ListElemT_co @final @attrs.define(frozen=True) class FkAsyncListable(AsyncListable, Gen...
blablatdinov/tg-quranbot
src/app_types/fk_async_listable.py
.py
e46c730be724d922
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs from app_types.async_supports_str import AsyncSupportsStr @final @attrs.define(frozen=True) class FkAsyncStr(AsyncSupportsStr): """Обертка...
blablatdinov/tg-quranbot
src/app_types/fk_async_str.py
.py
cf067999053247ab
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import SupportsFloat, final, override import attrs @attrs.define(frozen=True) @final class FkFloat(SupportsFloat): """Фейк для интерфейса SupportsFloat.""" _origin: float...
blablatdinov/tg-quranbot
src/app_types/fk_float.py
.py
80b7fd1551cffbe7
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs from app_types.runable import Runable @final @attrs.define(frozen=True) class FkRunable(Runable): """Fake runable.""" @override a...
blablatdinov/tg-quranbot
src/app_types/fk_runable.py
.py
079819a732477158
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs from app_types.stringable import SupportsStr @final @attrs.define(frozen=True) class FkString(SupportsStr): """Обертка для строки.""" ...
blablatdinov/tg-quranbot
src/app_types/fk_string.py
.py
19c5ec941f9303cd
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs import ujson from frozendict import frozendict from app_types.stringable import SupportsStr from app_types.update import Update @final @attrs....
blablatdinov/tg-quranbot
src/app_types/fk_update.py
.py
b4aabeadc268af3d
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Protocol class AsyncInt(Protocol): """Интерфейс объектов, которые можно привести к числу.""" async def to_int(self) -> int: """Приведение к числу с возможно...
blablatdinov/tg-quranbot
src/app_types/intable.py
.py
797d40d270050b69
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from collections.abc import Sequence from typing import Generic, Protocol, TypeVar ListElemT_co = TypeVar('ListElemT_co', covariant=True) class AsyncListable(Protocol, Generic[ListElemT_co]):...
blablatdinov/tg-quranbot
src/app_types/listable.py
.py
b0d581fa89ef987f
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import SupportsFloat, final, override import attrs @final @attrs.define(frozen=True) class Millis(SupportsFloat): """Миллисекунды.""" _millis: float @classmethod ...
blablatdinov/tg-quranbot
src/app_types/millis.py
.py
387f9852a4f0eccb
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import SupportsFloat, final, override import attrs @final @attrs.define(frozen=True) class RoundedFloat(SupportsFloat): """Округленное дробное число.""" _origin: Supports...
blablatdinov/tg-quranbot
src/app_types/rounded_float.py
.py
96523adc151f3e69
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Protocol, override class SupportsStr(Protocol): """Интерфейс объектов, которые можно привести к строке.""" @override def __str__(self) -> str: """Привед...
blablatdinov/tg-quranbot
src/app_types/stringable.py
.py
44edd48e51b02c30
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Protocol class SupportsBool(Protocol): """Интерфейс объектов, которые можно привести к булевому значению.""" def __bool__(self) -> bool: """Приведение к бул...
blablatdinov/tg-quranbot
src/app_types/supports_bool.py
.py
fecde26ecfd864fd
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Protocol class SyncRunable(Protocol): """Интерфейс блокирующего запускаемого объекта.""" def run(self, args: list[str]) -> int: """Запуск. :param a...
blablatdinov/tg-quranbot
src/app_types/sync_runable.py
.py
b5ba14cb6403804d
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs from app_types.stringable import SupportsStr @final @attrs.define(frozen=True) class UnwrappedString(SupportsStr): """Строки без переноса....
blablatdinov/tg-quranbot
src/app_types/unwrapped_string.py
.py
85d395dbb7e149ae
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import Protocol from frozendict import frozendict from app_types.stringable import SupportsStr class Update(SupportsStr, Protocol): """Интерфейс объектов, которые можно приве...
blablatdinov/tg-quranbot
src/app_types/update.py
.py
02e949959adce481
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT class BaseAppError(Exception): # noqa: FIN100 """Базовое исключение бота.""" class InternalBotError(BaseAppError): # noqa: FIN100 """Внутренняя ошибка бота.""" user_message = ''...
blablatdinov/tg-quranbot
src/exceptions/base_exception.py
.py
b958d2e19e3f78da
7.06
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs import httpx from redis.asyncio import Redis from sqlalchemy.ext.asyncio import AsyncEngine from app_types.fk_async_int import FkAsyncInt from a...
blablatdinov/tg-quranbot
src/handlers/concrete_podcast_answer.py
.py
91b19cbda2f4797e
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs import httpx from frozendict import frozendict from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncEngine from app_types.update ...
blablatdinov/tg-quranbot
src/handlers/decrement_skipped_prayer_answer.py
.py
c133de4a633b31ca
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs import httpx from redis.asyncio import Redis from sqlalchemy.ext.asyncio import AsyncEngine from app_types.logger import LogSink from app_types....
blablatdinov/tg-quranbot
src/handlers/favorites_answer.py
.py
849a20985a577db7
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs import httpx from redis.asyncio import Redis from sqlalchemy.ext.asyncio import AsyncEngine from app_types.logger import LogSink from app_types....
blablatdinov/tg-quranbot
src/handlers/paginate_by_search_ayat.py
.py
b945fd720c37c93b
7.56
12
# SPDX-FileCopyrightText: Copyright (c) 2018-2026 Almaz Ilaletdinov <a.ilaletdinov@yandex.ru> # SPDX-License-Identifier: MIT from typing import final, override import attrs import httpx from app_types.update import Update from integrations.tg.tg_answers.tg_answer import TgAnswer from services.match_many_json_path im...
blablatdinov/tg-quranbot
src/handlers/podcast_message_text_not_exists_safe_answer.py
.py
75547f19e136f368
7.56
12
"""Version information for :mod:`torch_max_mem`. Run with ``python -m torch_max_mem.version`` """ import os from subprocess import CalledProcessError, check_output __all__ = [ "VERSION", "get_git_hash", "get_version", ] VERSION = "0.1.7-dev" def get_git_hash() -> str: """Get the :mod:`torch_max_me...
mberr/torch-max-mem
src/torch_max_mem/version.py
.py
443ee3ccbbf3f6fb
7.63
17
"""Tests.""" import unittest from collections.abc import Hashable, Mapping, Sequence from typing import Any import pytest import torch from torch_max_mem import infer_maximum_batch_size, maximize_memory_utilization, set_memory_budget from torch_max_mem.api import ( KeyHasher, floor_to_nearest_multiple_of, ...
mberr/torch-max-mem
tests/test_decorator.py
.py
d657d6a5380ec944
8.13
17
import argparse import re from collections import Counter from urllib.parse import unquote, urlparse import psycopg2 import sqlglot MAX_JOINS = 3 QUESTIONS = {} TABLE_NAMES = {} TABLE_FIELDS = {} # 73 = TDB Pilotage département # 79 = Nouvelle stats public 2023 # 86 = Gestion des structures ADIE # 90 = Suivi du rem...
gip-inclusion/dora
analytics/metabase_scanner/metabase_scan.py
.py
3ca02b4aa446972a
7.42
6
# https://github.com/betagouv/itou/blob/master/config/settings/_sentry.py import logging import os import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger from sentry_sdk.integrations.redis import RedisIntegration d...
gip-inclusion/dora
back/config/settings/sentry.py
.py
84f3bf93910a23f7
7.42
6
from unittest.mock import patch import pytest from rest_framework.test import APIClient @pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(config, items): """Active automatiquement la gestion de la db""" for item in items: markers = {marker.name for marker in item.iter_markers()} ...
gip-inclusion/dora
back/dora/conftest.py
.py
edfa60eeef45c19f
7.92
6
""" Synchronise la table django_migrations avec les fichiers de migration présents sur le disque, sans exécuter les opérations. À utiliser après une réinitialisation des migrations Django : supprime les entrées existantes pour les apps dora, puis ré-insère une ligne par fichier de migration (ordre 0001, 0002, …) avec ...
gip-inclusion/dora
back/dora/core/management/commands/sync_migration_history.py
.py
704f527b27216f14
7.42
6
# Copyright 2023 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
canonical/postgresql-operator
lib/charms/data_platform_libs/v0/data_models.py
.py
7a49b2887b842fed
7.64
18
# Copyright 2022 Canonical Ltd. # See LICENSE file for licensing details. """In this class we manage certificates relation. This class handles certificate request and renewal through the interaction with the TLS Certificates Operator. This library needs that the following libraries are imported to work: - https://ch...
canonical/postgresql-operator
lib/charms/postgresql_k8s/v0/postgresql_tls.py
.py
a286ee5463ebf124
7.64
18
# Copyright 2023 Canonical Ltd. # See LICENSE file for licensing details. """Cluster topology changes observer.""" import json import subprocess import sys from ssl import CERT_NONE, create_default_context from time import sleep from urllib.parse import urljoin from urllib.request import urlopen import psycopg2 impo...
canonical/postgresql-operator
scripts/cluster_topology_observer.py
.py
4e90969118d76bd7
7.64
18
# Copyright 2023 Canonical Ltd. # See LICENSE file for licensing details. """Cluster topology changes observer.""" import logging import os import signal import subprocess from pathlib import Path from sys import version_info from typing import TYPE_CHECKING from ops.charm import CharmEvents from ops.framework impor...
canonical/postgresql-operator
src/cluster_topology_observer.py
.py
b71526455e3e94ee
7.64
18
#!/usr/bin/env python3 # Copyright 2023 Canonical Ltd. # See LICENSE file for licensing details. """Structured configuration for the PostgreSQL charm.""" import logging from typing import Annotated, Literal from charms.data_platform_libs.v0.data_models import BaseConfigModel from pydantic import Field, NonNegativeIn...
canonical/postgresql-operator
src/config.py
.py
d7b259de8caf27c5
7.64
18
# Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. """LDAP implementation.""" import logging from charms.glauth_k8s.v0.ldap import ( LdapProviderData, LdapReadyEvent, LdapRequirer, LdapUnavailableEvent, ) from ops import Relation from ops.framework import Object from ops.model ...
canonical/postgresql-operator
src/ldap.py
.py
314a882affe94b45
7.64
18
# Copyright 2022 Canonical Ltd. # See LICENSE file for licensing details. """Library containing the implementation of the legacy db and db-admin relations.""" import logging from collections.abc import Iterable from typing import TYPE_CHECKING from charms.postgresql_k8s.v0.postgresql import ( ACCESS_GROUP_RELATI...
canonical/postgresql-operator
src/relations/db.py
.py
3d3c9116241d4206
7.64
18
# Copyright 2022 Canonical Ltd. # See LICENSE file for licensing details. """Postgres client relation hooks & helpers.""" import logging from typing import TYPE_CHECKING from charms.data_platform_libs.v0.data_interfaces import ( DatabaseProvides, DatabaseRequestedEvent, ) from charms.postgresql_k8s.v0.postgr...
canonical/postgresql-operator
src/relations/postgresql_provider.py
.py
70c9c510ff7790df
7.64
18
# Copyright 2022 Canonical Ltd. # See LICENSE file for licensing details. """TLS Transfer Handler.""" import logging from collections.abc import Iterator from charms.certificate_transfer_interface.v0.certificate_transfer import ( CertificateAvailableEvent, CertificateRemovedEvent, CertificateTransferRequ...
canonical/postgresql-operator
src/relations/tls_transfer.py
.py
2feb8299e3efc815
7.64
18