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
"""Test f_lib.logging._extendable_highlighter.""" from __future__ import annotations from typing import TYPE_CHECKING from unittest.mock import Mock, call from f_lib.logging._extendable_highlighter import ExtendableHighlighter if TYPE_CHECKING: from pytest_mock import MockerFixture class TestExtendableHighlig...
finleyfamily/f-lib
tests/unit/logging/test__extendable_highlighter.py
.py
343e9ebb41ad585e
7.65
1
"""Test f_lib.logging._log_level.""" from __future__ import annotations import pytest from f_lib.logging._log_level import LogLevel class TestLogLevel: """Test LogLevel.""" @pytest.mark.parametrize( ("verbosity", "level"), [ (0, LogLevel.FATAL), (1, LogLevel.INFO), ...
finleyfamily/f-lib
tests/unit/logging/test__log_level.py
.py
e28453744b878ec4
7.65
1
"""Test f_lib.logging._logger.""" from __future__ import annotations from typing import TYPE_CHECKING from unittest.mock import Mock import pytest from f_lib.logging._log_level import LogLevel from f_lib.logging._logger import Logger, LoggerSettings if TYPE_CHECKING: from pytest_mock import MockerFixture @py...
finleyfamily/f-lib
tests/unit/logging/test__logger.py
.py
8ee4de023ef67435
7.65
1
"""Test f_lib.logging._prefix_adaptor.""" from __future__ import annotations from typing import TYPE_CHECKING import pytest from f_lib.logging._log_level import LogLevel from f_lib.logging._logger import Logger from f_lib.logging._prefix_adaptor import PrefixAdaptor if TYPE_CHECKING: from unittest.mock import ...
finleyfamily/f-lib
tests/unit/logging/test__prefix_adaptor.py
.py
122d08b7b64dcebf
7.65
1
#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # Copyright 2019 The Meson development team ''' Generates release notes for new releases of Meson build system ''' import argparse import subprocess import re import shutil import datetime from pathlib import Path RELNOTE_TEMPLATE = '''--- title: Release ...
sailfishos-mirror/meson
docs/genrelnotes.py
.py
6853f3e7ef4c252b
7
0
# SPDX-License-Identifier: Apache-2.0 # Copyright 2021 The Meson development team from .generatorbase import GeneratorBase import re import json from .model import ( ReferenceManual, Function, Method, Object, ObjectType, Type, DataTypeInfo, ArgBase, PosArg, VarArgs, Kwarg, ...
sailfishos-mirror/meson
docs/refman/generatormd.py
.py
b2b01ab503560ebf
7
0
# SPDX-License-Identifier: Apache-2.0 # Copyright 2021 The Meson development team import typing as T # The following variables define the current version of # the JSON documentation format. This is different from # the Meson version VERSION_MAJOR = 1 # Changes here indicate breaking format changes (changes to exist...
sailfishos-mirror/meson
docs/refman/jsonschema.py
.py
357d03f93ddfda9f
7
0
# SPDX-License-Identifier: Apache-2.0 # Copyright 2021 The Meson development team ''' This module soly exists to work around a pathlib.resolve bug on certain Windows systems: https://github.com/mesonbuild/meson/issues/7295 https://bugs.python.org/issue31842 It should **never** be used directly. I...
sailfishos-mirror/meson
mesonbuild/_pathlib.py
.py
eda44692c9f468dd
7
0
# SPDX-License-Identifier: Apache-2.0 # Copyright 2020 The Meson development team # Copyright © 2020-2024 Intel Corporation """Meson specific typing helpers. Holds typing helper classes, such as the ImmutableProtocol classes """ __all__ = [ 'Protocol', 'ImmutableListProtocol' ] import typing # We can chang...
sailfishos-mirror/meson
mesonbuild/_typing.py
.py
47900acf2a989a73
7
0
"""conftest.py module.""" import re from doctest import ELLIPSIS from typing import Any from sybil import Sybil from sybil.parsers.rest import PythonCodeBlockParser from scottbrian_utils.doc_checker import DocCheckerTestParser, DocCheckerOutputChecker from scottbrian_utils.time_hdr import get_datetime_match_string ...
ScottBrian/scottbrian_utils
conftest.py
.py
a4c2e2401384a24e
7.5
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 28 19:54:08 2020 @author: Scott Tuttle """ from doctest import OutputChecker from unittest import mock import pytest class DateTimeOutputChecker(OutputChecker): """This class is used to intercept the output of doctest examples. The date...
ScottBrian/scottbrian_utils
src/conftest.py
.py
360a2eb16b2d55e0
7.5
0
"""Module validator. ========= Validator ========= The Validator class is an abstract class used to create custom validation classes to use when instantiation a class. Also included are some basic validation routines that can be used: 1) Number: used to validate a number as being int or float and optionally having...
ScottBrian/scottbrian_utils
src/scottbrian_utils/validator.py
.py
1267c328e76bead2
7
0
""" Cached metadata functions for MaterializationEngine. This module provides cached versions of frequently accessed metadata functions to reduce database load and improve performance. """ from cachetools import TTLCache, cached from materializationengine.database import dynamic_annotation_cache from materializatione...
CAVEconnectome/MaterializationEngine
materializationengine/blueprints/client/cache.py
.py
d26a541c241691bb
7
0
import numbers from typing import Literal, NamedTuple, Optional, Union, cast from collections.abc import Sequence import struct from neuroglancer import coordinate_space, viewer_state import numpy as np class Annotation(NamedTuple): id: int encoded: bytes relationships: Sequence[Sequence[int]] _PROPERTY...
CAVEconnectome/MaterializationEngine
materializationengine/blueprints/client/precomputed.py
.py
9004ec1a493ad2f5
7
0
import logging from datetime import datetime, timezone from typing import Dict, List, Optional, Set, Tuple import marshmallow as mm import pandas as pd import numpy as np from emannotationschemas import get_schema from emannotationschemas.models import make_model_from_schema from emannotationschemas.schemas.base impor...
CAVEconnectome/MaterializationEngine
materializationengine/blueprints/upload/processor.py
.py
0af0b6b032a51923
7
0
from typing import Dict, Any, Optional, Tuple, Generator, BinaryIO from dataclasses import dataclass from google.cloud import storage from google.auth.transport.requests import AuthorizedSession from google.resumable_media.requests import ResumableUpload import pandas as pd import time import json from datetime import ...
CAVEconnectome/MaterializationEngine
materializationengine/blueprints/upload/storage.py
.py
a8bb68ef287a7650
7
0
import requests from celery.utils.log import get_task_logger import os celery_logger = get_task_logger(__name__) def post_message_to_slack(text: str, attachment: dict = None): """Post slack message Args: text (str): text message to post attachment (dict, optional): Append extra info. Default...
CAVEconnectome/MaterializationEngine
materializationengine/celery_slack.py
.py
d32a907a21f0c05a
7
0
from caveclient.chunkedgraph import ChunkedGraphClient from caveclient.auth import AuthClient from caveclient.auth import default_global_server_address import os default_server_address = os.environ.get( "GLOBAL_SERVER_URL", default_global_server_address ) # The read deployment, not the write one. Every call this...
CAVEconnectome/MaterializationEngine
materializationengine/chunkedgraph_gateway.py
.py
2bc0e298c0b208d6
7
0
import cloudvolume import os # Number of parallel threads CloudVolume uses internally for fetching data. # Default of 10 matches the urllib3 pool_maxsize (10) used by cloud-files/google-cloud-storage, # avoiding connection pool overflow. Override with CLOUDVOLUME_PARALLEL env var. _CV_PARALLEL = int(os.environ.get("CL...
CAVEconnectome/MaterializationEngine
materializationengine/cloudvolume_gateway.py
.py
2e9a89c2260b5342
7
0
import json import logging import os import sys from datetime import timedelta from flask import Flask from flask.logging import default_handler _TRUE_VALUES = frozenset(("1", "true", "yes", "on")) _FALSE_VALUES = frozenset(("0", "false", "no", "off", "")) def as_bool(value, default=False, name="value"): """Co...
CAVEconnectome/MaterializationEngine
materializationengine/config.py
.py
337d6b2cfb097c74
7
0
from contextlib import contextmanager from urllib.parse import urlparse from dynamicannotationdb import DynamicAnnotationInterface from flask import current_app from sqlalchemy import MetaData, create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.pool import QueuePool from materializa...
CAVEconnectome/MaterializationEngine
materializationengine/database.py
.py
1ab883cd79a3bebe
7
0
from flask_limiter import Limiter from flask_limiter.util import get_remote_address from flask import g import os import json def _load_categories(env_var): try: categories = json.loads(os.environ.get(env_var, "{}")) except json.JSONDecodeError: return {} return categories if isinstance(ca...
CAVEconnectome/MaterializationEngine
materializationengine/limiter.py
.py
3c05c3badfc601b2
7
0
"""Per-request memory accounting, designed to survive the request being killed. Why this exists --------------- On minniev7 the api pods run on e2-small nodes (1358Mi allocatable) whose memory is 99% committed by requests, and the materialize container has no memory limit. A request that allocates a few hundred MB the...
CAVEconnectome/MaterializationEngine
materializationengine/memory_audit.py
.py
e4d8f9345745621a
7
0
import os from celery.utils.log import get_task_logger from redis import ConnectionError, StrictRedis from materializationengine.celery_init import celery from materializationengine.utils import get_config_param celery_logger = get_task_logger(__name__) REDIS_CLIENT = StrictRedis( host=get_config_param("REDIS_H...
CAVEconnectome/MaterializationEngine
materializationengine/monitor.py
.py
35157d00860cf620
7
0
#!/usr/bin/python # -*- coding: UTF-8 -*- import json, os, sys import logging import argparse import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent logging.basicConfig(level=logging.INFO, format='%(asctime)24s - %(levelname)8s - %(message)s', filem...
HeiTang/FCU-CourseData
Coursedump.py
.py
fb3baca974ad6928
7.39
5
#!/usr/bin/env python # coding: utf-8 # In[ ]: """ NMTF_alpha """ # Author: Hoseinipour Saeid <saeidhoseinipour@aut.ac.ir> # License: ?????????? import itertools from math import * from scipy.io import loadmat, savemat import sys import numpy as np import scipy.sparse as sp from sklearn...
Saeidhoseinipour/NMTFcoclust
Models/NMTFcoclust_NMTF_alpha.py
.py
fe4218875917536d
7.35
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: """ ONMTF_alpha """ # Author: Hoseinipour Saeid <saeidhoseinipour@aut.ac.ir> # License: ?????????? import itertools from math import * from scipy.io import loadmat, savemat import sys import numpy as np import scipy.sparse as sp from sklear...
Saeidhoseinipour/NMTFcoclust
Models/NMTFcoclust_ONMTF_alpha.py
.py
eb7b5031d97b238d
7.35
4
#!/usr/bin/env python # coding: utf-8 # In[1]: """ OSNMTF """ # Author: Hoseinipour Saeid <saeidhoseinipour@aut.ac.ir> # License: ?????????? import itertools from math import * from scipy.io import loadmat, savemat import sys import numpy as np import scipy.sparse as sp from sklearn.utils import check_rand...
Saeidhoseinipour/NMTFcoclust
Models/NMTFcoclust_OPNMTF_alpha.py
.py
dfeb48c2367ca25e
7.35
4
#!/usr/bin/env python # coding: utf-8 # In[1]: """ PNMTF """ # Author: Hoseinipour Saeid <saeidhoseinipour@aut.ac.ir> # License: ?????????? import itertools from math import * from scipy.io import loadmat, savemat import sys import numpy as np import scipy.sparse as sp from sklearn.util...
Saeidhoseinipour/NMTFcoclust
Models/NMTFcoclust_PNMTF.py
.py
5f8c31c4f1965568
7.35
4
# SPDX-License-Identifier: MIT import functools import types from ._make import __ne__ _operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="} def cmp_using( eq=None, lt=None, le=None, gt=None, ge=None, require_same_type=True, class_name="Comparable", ): """ ...
sailfishos-mirror/attrs
src/attr/_cmp.py
.py
dcd9f54e3c659546
7
0
# SPDX-License-Identifier: MIT import sys import threading from collections.abc import Mapping, Sequence # noqa: F401 from typing import Callable, _GenericAlias PYPY = sys.implementation.name == "pypy" PY_3_11_PLUS = sys.version_info[:2] >= (3, 11) PY_3_12_PLUS = sys.version_info[:2] >= (3, 12) PY_3_13_PLUS = sys....
sailfishos-mirror/attrs
src/attr/_compat.py
.py
aa4df995064dde6f
7
0
# SPDX-License-Identifier: MIT __all__ = ["get_run_validators", "set_run_validators"] _run_validators = True def set_run_validators(run): """ Set whether or not validators are run. By default, they are run. .. deprecated:: 21.3.0 It will not be removed, but it also will not be moved to new ``at...
sailfishos-mirror/attrs
src/attr/_config.py
.py
0499fe7dced578ea
7
0
# SPDX-License-Identifier: MIT from functools import total_ordering from ._funcs import astuple from ._make import attrib, attrs @total_ordering @attrs(eq=False, order=False, slots=True, frozen=True) class VersionInfo: """ A version object that can be compared to tuple of length 1--4: >>> attr.Version...
sailfishos-mirror/attrs
src/attr/_version_info.py
.py
c3847e1580b734af
7
0
# SPDX-License-Identifier: MIT """ Commonly useful converters. """ from ._compat import _AnnotationExtractor from ._make import NOTHING, Converter, Factory, pipe __all__ = [ "default_if_none", "optional", "pipe", "to_bool", ] def optional(converter): """ A converter that allows an attribut...
sailfishos-mirror/attrs
src/attr/converters.py
.py
be3ce4f8ee6feb27
7
0
# SPDX-License-Identifier: MIT """ Testing strategies for Hypothesis-based tests. """ import functools import keyword import string from collections import OrderedDict from hypothesis import strategies as st import attr from .utils import make_class optional_bool = st.one_of(st.none(), st.booleans()) def gen_...
sailfishos-mirror/attrs
tests/strategies.py
.py
b58d18e6ad23be69
7.5
0
# SPDX-License-Identifier: MIT """ Tests for compatibility against other Python modules. """ import pytest from hypothesis import given from .strategies import simple_classes cloudpickle = pytest.importorskip("cloudpickle") class TestCloudpickleCompat: """ Tests for compatibility with ``cloudpickle``. ...
sailfishos-mirror/attrs
tests/test_3rd_party.py
.py
82ffcfff1a44a7e1
7.5
0
# SPDX-License-Identifier: MIT import abc import inspect import pytest import attrs from attr._compat import PY_3_12_PLUS class TestUpdateAbstractMethods: def test_abc_implementation(self, slots): """ If an attrs class implements an abstract method, it stops being abstract. """...
sailfishos-mirror/attrs
tests/test_abc.py
.py
2ea0bd487c98c7a8
7.5
0
# SPDX-License-Identifier: MIT """ Tests for `attr._config`. """ import pytest from attr import _config class TestConfig: def test_default(self): """ Run validators by default. """ assert True is _config._run_validators def test_set_run_validators(self): """ ...
sailfishos-mirror/attrs
tests/test_config.py
.py
968a38cc8caa9837
7.5
0
""" Tests for behavior specific to forward references via PEP 749. """ from attrs import define, fields, resolve_types def test_forward_class_reference(): """ Class A can reference B even though it is defined later. """ @define class A: b: B class B: pass resolve_types(...
sailfishos-mirror/attrs
tests/test_forward_references.py
.py
ca3eb5b3dfbf4672
7
0
# SPDX-License-Identifier: MIT import attr import attrs class TestImportStar: def test_from_attr_import_star(self): """ import * from attr """ # attr_import_star contains `from attr import *`, which cannot # be done here because *-imports are only allowed on module level. ...
sailfishos-mirror/attrs
tests/test_import.py
.py
c85434216ffe541d
7.5
0
# SPDX-License-Identifier: MIT from importlib import metadata import pytest import attr import attrs @pytest.fixture(name="mod", params=(attr, attrs)) def _mod(request): return request.param class TestLegacyMetadataHack: def test_version(self, mod, recwarn): """ __version__ returns the c...
sailfishos-mirror/attrs
tests/test_packaging.py
.py
e13f9905b5c8d3f8
7.5
0
from .utils import simple_class class TestSimpleClass: """ Tests for the testing helper function `make_class`. """ def test_returns_class(self): """ Returns a class object. """ assert type is simple_class().__class__ def test_returns_distinct_classes(self): ...
sailfishos-mirror/attrs
tests/test_utils.py
.py
3e570bef589393b5
7
0
import codecs import os import re from xml.dom import minidom from xml.etree import ElementTree __author__ = 'sinlov' class Py3MiniDom: """ use as python2 minidom from tools.py2_xml import Py2MiniDom dom = minidom.parse('test.xml') Py2MiniDom.beauty_write(dom, 'test_test.xml') """ def...
sinlov/python3-playground
src/serialization_utils/Py3XML.py
.py
43f958a02019cfed
7.24
2
# flake8: noqa __author__ = 'sinlov' import shlex import subprocess from subprocess import CompletedProcess class ExecUtil: def __init__(self): pass """ 执行默认超时时间 3 * 60 * 1 秒 """ out_of_time_default = int(3 * 60 * 1) @staticmethod def run(cli_string, cwd=None, timeout=int(5 * 6...
sinlov/python3-playground
src/sys_utils/ExecUtil.py
.py
a8b78a2961a687d9
7.24
2
import threading import time from . import _logging class PyTimer: on_stop = None """ on_stop: function Callback object which is called when we get error. on_error has 1 arguments. The 1st argument is this class object. """ on_error = None """ on_error...
sinlov/python3-playground
src/thread_util/PyTimer.py
.py
c14b9c69432b2cd7
7.24
2
import datetime import time class Py3TimeUtils: def __init__(self): pass @staticmethod def now_unix_timestamp(): # type: () -> float return time.time() @staticmethod def now_unix_timestamp_second(): # type: () -> int """ now unix timestamp second ...
sinlov/python3-playground
src/time_utils/Py3TimeUtils.py
.py
3e67f0d58f5ca021
7.24
2
# /// script # requires-python = ">=3.13" # /// """Copilot Audit Failure Log — postToolUseFailure hook for tool error logging. Reads a JSON tool-failure payload from stdin and appends a one-line JSON log entry to ~/.copilot/audit-failures.jsonl. Only fires when a tool handler explicitly reports an error (e.g. view on ...
torumakabe/dotfiles
home/private_dot_copilot/hooks/scripts/executable_audit-failure.py
.py
45056721a5498e11
7.24
2
# /// script # requires-python = ">=3.13" # /// """Copilot Audit Log — postToolUse hook for recording tool invocations. Reads a JSON tool-call from stdin and appends a one-line JSON log entry to ~/.copilot/audit.jsonl. The postToolUse output is ignored by Copilot CLI, so this script is purely for logging/auditing purp...
torumakabe/dotfiles
home/private_dot_copilot/hooks/scripts/executable_audit-log.py
.py
85ab5037f2e040c4
7.24
2
"""Shared helpers for the test suite. Always import these as `from tests._helpers import ...`. A bare `import _helpers` resolves only under `unittest discover -s tests`; the dotted form additionally keeps `uv run -m unittest tests.test_copilot_guard` working, which docs/copilot-cli.md and docs/operations.md document. ...
torumakabe/dotfiles
tests/_helpers.py
.py
2531b92ce7c9120c
7.74
2
"""Verify the three audit-redaction regexes stay identical across scripts. All three scripts keep a local copy of the redaction regex (self-contained per ADR style). This test guards against drift: if any of them change without the others, CI fails. """ import pathlib import unittest from tests._helpers import load_s...
torumakabe/dotfiles
tests/test_audit_redaction_sync.py
.py
b303ec938fb15093
7.74
2
"""Guard the chezmoi config template against losing prompted values. ``home/.chezmoi.toml.tmpl`` asks for ``windowsUser`` / ``corpUser`` only when stdin is a TTY. ``promptStringOnce`` would return the stored answer without prompting, but the TTY guard skips the call entirely, so a non-interactive ``chezmoi init`` (scr...
torumakabe/dotfiles
tests/test_chezmoi_config_template.py
.py
6d4109a6afa5ba75
7.74
2
"""Exercise the git un-shadowing step from the Linux package bootstrap. Codespaces / Dev Container base images build git from source into /usr/local (devcontainers git feature, version=latest, ppa=false, prefix=/usr/local). /usr/local/bin precedes /usr/bin in PATH, so installing a newer git through ppa:git-core/ppa le...
torumakabe/dotfiles
tests/test_git_shadow_resolution.py
.py
e8f05ae7d68df99d
7.74
2
"""Shared benchmark fixtures: every register from ``harp.benchmarks.register_models`` paired with whether its frames carry a timestamp. Both ``generate.py`` (writes the .bin corpora) and ``benchmark.py`` (times parsing) import :data:`BENCHMARK_REGISTERS` from here so the two stay in lock-step. Payloads are synthesized...
harp-tech/python
src/packages/harp-benchmarks/src/harp/benchmarks/_registers.py
.py
a4ed07c2c5903713
7.39
5
import argparse from pathlib import Path import numpy as np from harp.benchmarks._registers import BENCHMARK_REGISTERS, DATA_DIR, BenchmarkedRegister _SEED = 42 def corpus_path(reg: BenchmarkedRegister, data_dir: Path = DATA_DIR): """Path to ``reg``'s corpus file under ``data_dir``.""" return data_dir / re...
harp-tech/python
src/packages/harp-benchmarks/src/harp/benchmarks/generate.py
.py
d7b707d079c14729
7.39
5
import re from collections.abc import Callable, Mapping from datetime import datetime from os import PathLike from pathlib import Path from typing import Any, Generic, TypeVar, overload import pandas as pd from harp.device.schema import ( DeviceModule, DeviceModuleLike, create_device_module, parse_devi...
harp-tech/python
src/packages/harp-data/src/harp/data/_dataset.py
.py
116337b74594fb1d
7.39
5
from datetime import datetime from typing import Any import pandas as pd from harp.protocol import ( PayloadType, RegisterBase, RegisterFloat, RegisterFloatArray, RegisterS8, RegisterS8Array, RegisterS16, RegisterS16Array, RegisterS32, RegisterS32Array, RegisterS64, Regi...
harp-tech/python
src/packages/harp-data/src/harp/data/_read.py
.py
b27fc786aafa9f8d
7.39
5
"""Load Harp register data into pandas DataFrames.""" from datetime import datetime from pathlib import Path from typing import Any, BinaryIO import numpy as np import pandas as pd from harp.protocol import RegisterBase from numpy.typing import NDArray Source = str | Path | bytes | bytearray | memoryview | BinaryIO ...
harp-tech/python
src/packages/harp-data/src/harp/data/_reader.py
.py
d576dbe0c8330677
7.39
5
"""Write Harp register data to a binary buffer or file, the inverse of the readers. Thin wrappers over :meth:`RegisterBase.format_bulk` giving a pandas-package home and a file sink. Useful for round-tripping data and generating typed test corpora. """ from os import PathLike from typing import Any import numpy as np...
harp-tech/python
src/packages/harp-data/src/harp/data/_write.py
.py
807bb98ed2ba3c66
7.39
5
"""Byte transport abstraction for Harp devices.""" from typing import Protocol, runtime_checkable class TransportError(Exception): """Raised by a transport when the underlying byte channel fails.""" @runtime_checkable class ITransport(Protocol): """Byte channel a :class:`~harp.device.client.Device` drives....
harp-tech/python
src/packages/harp-device/src/harp/device/client/_transport.py
.py
fc877f565a47ca57
7.39
5
# This file was automatically generated and should not be edited directly. # To make changes, edit the device metadata and regenerate the interface. """The core register set every Harp device carries, and its address space.""" import enum from typing import Any, ClassVar import numpy as np from harp.protocol import ...
harp-tech/python
src/packages/harp-device/src/harp/device/core/__init__.py
.py
3247cc8471de0c33
7.39
5
"""Emit a Python module of register classes from a device schema. A generated device package is already a module: register classes at module level and a ``REGISTER_MAP`` beside them (see the ``harp-device`` README). :func:`create_device_module` builds that same shape at runtime from a ``device.yml``, so a schema-drive...
harp-tech/python
src/packages/harp-device/src/harp/device/schema/_module.py
.py
6bb29ee0f47a585a
7.39
5
"""How a schema identifier becomes a Python one. The runtime emitter must produce the *same* identifiers as the statically generated device packages, so code written against either lines up name for name: * enum members -> :func:`enum_member_name` (``DIPort0`` -> ``DI_PORT0``) * payload fields -> :func:`field_name...
harp-tech/python
src/packages/harp-device/src/harp/device/schema/_naming.py
.py
6f42561bb0ba6b8d
7.39
5
"""Harp message container.""" import struct from typing import Any, ClassVar, Generic, Protocol, TypeVar, cast from typing_extensions import Sentinel from ._builder import build_message_frame from ._checksum import validate as _validate_checksum from ._constants import ( _DEFAULT_PORT, _HEADER_LEN, _MIN_...
harp-tech/python
src/packages/harp-protocol/src/harp/protocol/_message.py
.py
2c436f477e9e2fee
7.39
5
from enum import IntEnum class MessageType(IntEnum): """Represents the a message type from the harp protocol""" Read = 1 Write = 2 Event = 3 _RESERVED_MASK = 0b11110100 """Bits 7, 6, 5, 4 and 2 must be 0. Bit 3 is error and bits 1:0 are the type.""" _VALID_TYPES = frozenset(t.value for t in Messag...
harp-tech/python
src/packages/harp-protocol/src/harp/protocol/_message_type.py
.py
f6ed6e878781cd6b
7.39
5
"""Static conformance checks for the documented public API. Nothing here runs. Every function is a type-checker fixture, asserting the type a documented expression resolves to, so a change that silently degrades an inferred type fails the build rather than being noticed downstream. """ from typing import Any, ClassVa...
harp-tech/python
tests/conformance.py
.py
484ad64dbbd1dcc4
7.89
5
"""Pytest configuration, shared fixtures and helpers for all suites.""" from pathlib import Path import pytest from tests.fixtures import ( # re-export so conftest-aware code still works TIMESTAMP_1S, make_frame_from_raw, ) __all__ = ["make_frame_from_raw", "TIMESTAMP_1S"] # Shared schema assets, usable a...
harp-tech/python
tests/conftest.py
.py
2347f36ca84257b8
7.89
5
from typing import Any import numpy as np from numpy.typing import NDArray from harp.protocol import Converter class DataConverter(Converter[int]): """Maps two raw little-endian signed bytes to and from a Python int. Models interfaceType: int over a two-byte sub-region of the CustomMemberConverter payload....
harp-tech/python
tests/device/converters.py
.py
f4edab1d09ac9fda
7.89
5
# This file was automatically generated and should not be edited directly. # To make changes, edit the device metadata and regenerate the interface. import enum from typing import Any, ClassVar import numpy as np from numpy.typing import NDArray from harp.protocol import ( AnonymousPayload, BitMask, BoolC...
harp-tech/python
tests/device/expected_device.py
.py
dc17082f5eed3bfd
7.89
5
"""The naming convention must match ``FirmwareNamingConvention`` in harp-tech/generators. Every pair below is taken from the committed expected output of the generator (``tests/ExpectedOutput/{core,device}.py`` against ``tests/Metadata/{core,device}.yml``), so these lock the port to the C# behavior rather than to a re...
harp-tech/python
tests/device/test_naming.py
.py
3dc5e944de11a2f8
7.89
5
"""Authorization helpers.""" import base64 import email.utils import hashlib import hmac from beartype import beartype @beartype def _compute_hmac_base64(*, key: bytes, data: bytes) -> bytes: """ Return the Base64 encoded HMAC-SHA1 hash of `data` using the `key`. """ hashed = hmac.new(key=key, m...
VWS-Python/vws-auth-tools
src/vws_auth_tools/__init__.py
.py
7daeadc8e6bd7008
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import zipfile import os import glob import re import requests import time import urllib.parse from . import config from .console import Console from .check import Check from .cleepapi import resolve_rpc_url import subprocess requests.packages.urllib3.disab...
CleepDevice/cleep-cli
cleepcli/ci.py
.py
4d095903c8cdc0e5
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import logging from . import config from .console import Console import requests import json import urllib.parse requests.packages.urllib3.disable_warnings() # Cleep 0.1+ serves HTTPS by default; older versions listen on HTTP only. DEFAULT_RPC_URLS =...
CleepDevice/cleep-cli
cleepcli/cleepapi.py
.py
216e0554578f1805
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from .console import Console import logging from . import config class File(): """ Handle file operations """ def __init__(self): self.logger = logging.getLogger(self.__class__.__name__) def core_sync(self): """ Sync...
CleepDevice/cleep-cli
cleepcli/file.py
.py
079c9f6091d92fa7
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os from .console import EndlessConsole, Console import logging import time from . import config from .check import Check from .docs import Docs from .test import Test from github import Github from zipfile import ZipFile, ZIP_DEFLATED from tempfile import...
CleepDevice/cleep-cli
cleepcli/package.py
.py
7033452616881129
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re import os import time import logging from . import config from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler, EVENT_TYPE_MODIFIED import watchdog.events as events from threading import Thread from .cleepapi ...
CleepDevice/cleep-cli
cleepcli/watch.py
.py
82ea56c54a8dad62
7
0
"""공식문서 fetch + robots.txt 준수 + 본문 텍스트 추출.""" from __future__ import annotations import time from urllib.parse import urlparse from urllib.robotparser import RobotFileParser import requests from bs4 import BeautifulSoup _robots_cache: dict[str, RobotFileParser | None] = {} def _robots_for(base: str, user_agent: st...
lmj00/lmj00.github.io
generator/fetcher.py
.py
e2cef4a798fcb690
7
0
"""하루 1회 실행: 공식문서 기반 학습 노트 1편 생성 → _posts/ai-notes/ 에 작성. 수동 트리거 시 환경변수 FORCE_TOPIC_ID 로 특정 주제 강제 가능. 주제가 모두 소진되면 아무것도 생성하지 않고 정상 종료(exit 0). """ from __future__ import annotations import json import os import re import sys from pathlib import Path import random import fetcher import llm import dedup import post_wr...
lmj00/lmj00.github.io
generator/main.py
.py
1a4c02f5bdc691f5
7
0
import asyncio from abc import ABC, abstractmethod from typing import Any from gen3.file import Gen3File from gen3.jobs import Gen3Jobs from cdislogging import get_logger from gen3.auth import Gen3Auth from export_user_data_library.config import ConfigProvider import requests logger = get_logger(__name__) class L...
uc-cdis/sower-jobs
export-user-data-library/export_user_data_library/export.py
.py
0db35020e6ce42e0
7
0
import pytest from unittest.mock import Mock, AsyncMock, patch @pytest.fixture def mock_config(): """Mock ConfigProvider - used by multiple ListExporter tests""" config = Mock() config.get_access_token.return_value = "test-token" config.get_data_library_service.return_value = "http://test-library" ...
uc-cdis/sower-jobs
export-user-data-library/tests/conftest.py
.py
4e00e2119713358c
7.5
0
import csv import random import requests from datetime import datetime import string import logging import boto3 from botocore.exceptions import ClientError from botocore.config import Config def randomString(stringLength=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase ...
uc-cdis/sower-jobs
manifest_indexing/utils.py
.py
c7de9ab6c894657c
7
0
import csv import random import requests from datetime import datetime import string import logging import boto3 from botocore.exceptions import ClientError from botocore.config import Config def randomString(stringLength=10): """ Generate a random string of fixed length Arg: stringLength(str): t...
uc-cdis/sower-jobs
manifest_merging/utils.py
.py
0acb562cc40057ea
7
0
import csv import random import requests from datetime import datetime import string import logging import boto3 from botocore.exceptions import ClientError from botocore.config import Config def download_file(url, filename): """ Download data from url and save the content to filename """ r = requests...
uc-cdis/sower-jobs
metadata_ingestion/utils.py
.py
cf6eef7ef2bab03f
7
0
"""Python wrapper for getting air quality data from GIOS.""" import asyncio import logging from collections.abc import Generator from http import HTTPStatus from typing import Any, Final, Self, cast from aiohttp import ClientSession from dacite import from_dict from yarl import URL from .const import ( ATTR_AQI,...
bieniu/gios
gios/__init__.py
.py
de976f65a6741b4f
7.24
2
"""Type definitions for GIOS.""" from dataclasses import dataclass @dataclass class Sensor: """Data class for sensor.""" name: str id: int | None index: str | None = None value: float | str | None = None @dataclass class GiosSensors: """Data class for polutants.""" aqi: Sensor | None ...
bieniu/gios
gios/model.py
.py
f7f9f07d6f941800
7.24
2
"""Perfiles de sitio: agregar un sitio de genealogía nuevo es escribir un archivo chico en este paquete, sin tocar el resto del código. Un perfil es un :class:`SiteProfile`: un nombre, una descripción, y un diccionario de *overrides* con la misma forma que un YAML de configuración (``--config``) — de hecho se aplican ...
lol-protocol/experiment
genealog_scraper/genealog/profiles/__init__.py
.py
76ac415ae336062c
7
0
"""Inversa del paso DRY: página destilada + chrome -> página completa. Existe por dos razones. La primera es práctica: poder abrir en el navegador cualquier página del archivo tal como era. La segunda es de higiene: si el paso DRY es reversible, entonces guardar la plantilla una sola vez no perdió nada, y eso se puede...
lol-protocol/experiment
genealog_scraper/genealog/rehydrate.py
.py
384648d28a37fbd3
7
0
"""This module holds classes related to a fero asset.""" import pandas as pd from fero import FeroError from marshmallow import Schema, fields, EXCLUDE from typing import Union, Optional, Mapping from .common import FeroObject class AssetSchema(Schema): """A schema to store data related to a fero asset.""" ...
FeroLabs/fero_client
fero/asset.py
.py
8c78b08fe5614f14
7.3
3
"""This module defines classes and functions used in multiple places throughout the fero client.""" import fero import time import requests from typing import Any, Callable, TypeVar from marshmallow import Schema from fero.exceptions import FeroError class FeroObject: """ A base class for fero-related objec...
FeroLabs/fero_client
fero/common.py
.py
30c63bdb6733874f
7.3
3
"""This Module defines classes related to a fero datasource.""" import os import time import requests import fero from fero import FeroError from typing import Optional, Union from marshmallow import ( Schema, fields, validate, EXCLUDE, ) from .common import FeroObject # 1 Mb CHUNK_SIZE = 1048576 ...
FeroLabs/fero_client
fero/datasource.py
.py
e132ed8648456008
7.3
3
"""This module defines an error to be used for fero-specific exceptions.""" class FeroError(Exception): """A base error for fero-specific exceptions.""" def __init__(self, *args): """ Create a `FeroError` with arbitrary positional arguments. :param args: an argument list of arbitrary...
FeroLabs/fero_client
fero/exceptions.py
.py
93a51814b6da96c1
7.3
3
"""This module holds classes representing live predictions and optimizations from Fero. Fero runs four kinds of live prediction against an analysis -- point predictions and optimizations, each in a standard and a "flexible" variant. A flexible prediction evaluates the same request against several scenarios at once, so...
FeroLabs/fero_client
fero/live_predictions.py
.py
d93ad89adfea1189
7.3
3
"""This module defines classes related to a fero process.""" import time import fero import requests from tempfile import NamedTemporaryFile from functools import lru_cache as memoized from typing import Sequence, Optional, Union from .common import FeroObject, poll from marshmallow import ( Schema, fields, ...
FeroLabs/fero_client
fero/process.py
.py
1bbc99fbee1861ab
7.3
3
"""This module holds the `Workspace` class and its schema.""" from marshmallow import ( Schema, fields, EXCLUDE, ) from .common import FeroObject class WorkspaceSchema(Schema): """A schema for a workspace.""" class Meta: """ Specify that unknown fields included on this schema sho...
FeroLabs/fero_client
fero/workspace.py
.py
81c4ad543e676008
7.3
3
"""A module to test `DataSource` and related classes.""" import pytest from fero import FeroError from fero.datasource import UploadedFileStatus @pytest.fixture def file_status_data(): """Get sample data matching the `UploadedFileStatus` class structure.""" return { "uuid": "5351ab61-a50b-428d-adbb-8...
FeroLabs/fero_client
tests/test_datasource.py
.py
7628c6851560e964
7.8
3
from dns import resolver from dns.exception import DNSException import itertools import collections import multiprocessing.pool def worker(arg): """ query dns for (hostname, qname) and return (qname, [rdata,...]) """ try: url, qname, nameserver = arg custom_resolver = resolver.Resolver() # Log pro...
fartbagxp/aas-cidr-ranges
src/async_dns.py
.py
41112dea8cc8d081
7.3
3
''' The range of Atlassian services IPs are provided in this location: Atlassian includes a suite of cloud services such as Statuspage, Jira, Confluence, etc. This is a parser for the set of IPs / IP ranges in CIDR notation. ''' import requests class AtlassianCidrDownloader(): def get_range(self): try: ...
fartbagxp/aas-cidr-ranges
src/dl/download_atlassian.py
.py
824bcfc333d402a2
7.3
3
''' The range of Amazon Web Service (AWS) IPs are provided in this location: https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html Another list for Cloudfront can be found here: https://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips but the data is already included. This is a parser for the set of ...
fartbagxp/aas-cidr-ranges
src/dl/download_aws.py
.py
20d885aa6bcf1a0a
7.3
3
''' The range of Cloudflare IPs are provided in this location: https://www.cloudflare.com/ips/ This is a parser for the set of IPs / IP ranges in CIDR notation. ''' import requests class CloudflareCidrDownloader(): def get_range_v4(self): try: URL = 'https://www.cloudflare.com/ips-v4' r = request...
fartbagxp/aas-cidr-ranges
src/dl/download_cloudflare.py
.py
61fa1c2f52940e5f
7.3
3
''' The range of Datadog HQ https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html This is a parser for the set of IPs / IP ranges in CIDR notation. ''' import requests class DatadogCidrDownloader(): def __init__(self): self.source = 'https://ip-ranges.datadoghq.com/' def get_range(self): try...
fartbagxp/aas-cidr-ranges
src/dl/download_datadog.py
.py
c1a87e0ba8796c26
7.3
3
''' IANA is the Internet Assigned Numbers Authority, an organization which governs IP address allocation. We use IANA as the official source of truth for private IP address range allocation. Private IP ranges typically include only IP addresses (ex. 10.0.0.1, 127.0.0.1) that are only active within a local area network...
fartbagxp/aas-cidr-ranges
src/dl/download_iana.py
.py
cfd42de9f2971682
7.3
3