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 |
|---|---|---|---|---|---|---|
""" example to de-register a notification """
import json
from typing import Any, Dict
from pvoutput import PVOutput
def get_apikey_systemid_sync() -> Dict[str, Any]:
"""non-asyncio config loader"""
with open("pvoutput.json", "r", encoding="utf8") as config_file:
config_data: Dict[str, Any] = json.loa... | yaleman/pvoutput | examples/sync_deregister_notification.py | .py | ec4aecbac8d3c951 | 7.54 | 11 |
""" get status example """
import json
from typing import Any, Dict
from pvoutput import PVOutput
def get_apikey_systemid_sync() -> Dict[str, Any]:
"""non-asyncio config loader"""
with open("pvoutput.json", "r", encoding="utf8") as config_file:
config_data: Dict[str, Any] = json.load(config_file)
... | yaleman/pvoutput | examples/sync_getstatus.py | .py | e6460ca7376a2fe4 | 7.54 | 11 |
""" register notification example """
import json
from typing import Any, Dict
from pvoutput import PVOutput
def get_apikey_systemid_sync() -> Dict[str, Any]:
"""non-asyncio config loader"""
with open("pvoutput.json", "r", encoding="utf8") as config_file:
config_data: Dict[str, Any] = json.load(config... | yaleman/pvoutput | examples/sync_register_notification.py | .py | 22ad00f74873f704 | 7.54 | 11 |
"""AsyncIO interface to the PVOutput API"""
import datetime
from typing import Any, Dict, Optional
import aiohttp
from pvoutput.exceptions import UnknownMethodError
from pvoutput.base import PVOutputBase
from pvoutput import utils
from pvoutput.parameters import (
ADDBATCHSTATUS_PARAMETERS,
ADDSTATUS_PARAMET... | yaleman/pvoutput | pvoutput/asyncio/__init__.py | .py | 6634ea1b9c15c79e | 7.54 | 11 |
"""base class for pvoutput"""
from datetime import datetime, time
from math import floor
import re
from typing import Any, Dict, Union
from .exceptions import InvalidRegexpError, DonationRequired
def round_to_base(number: Union[int, float], base: Union[int, float]) -> float:
"""rounds down to a specific base nu... | yaleman/pvoutput | pvoutput/base.py | .py | f3a4852e2d3dde52 | 7.54 | 11 |
"""Utilities"""
from datetime import date, datetime, timedelta
from typing import Any, Dict, List, Tuple
__all__ = [
"URLS",
"validate_delete_status_date",
"ALERT_TYPES",
]
BASE_URL = "https://pvoutput.org/service/r2/"
URLS = {
"addbatchstatus": {
"url": BASE_URL + "addbatchstatus.jsp",
... | yaleman/pvoutput | pvoutput/utils.py | .py | c74b54d01bf32bce | 7.54 | 11 |
"""tests synchronous api things"""
import datetime
import re
from typing import Any
import pytest
import requests_mock
import pvoutput
import pvoutput.parameters
import pvoutput.exceptions
# because we're testing, just grab everything.
URLMATCHER = re.compile(".*")
# used in test_datetime_fix
FAKE_TIME = datetime.... | yaleman/pvoutput | tests/test__mocked_sync.py | .py | e27fa50caf5858d3 | 7.04 | 11 |
"""test asyncio things"""
import datetime
import json
import os
from typing import Any, Dict
import pytest
try:
import aiohttp # pylint: disable=unused-import
except ImportError as error_message:
print(f"Failed to import aiohttp: {error_message}")
pytest.fail()
# All test coroutines will be treated as m... | yaleman/pvoutput | tests/test_live_async.py | .py | d4231fd72be7e5ec | 7.04 | 11 |
"""test sync things"""
import datetime
import json
import os
from typing import Any, Dict
import pytest
from pvoutput import PVOutput
@pytest.fixture
def config() -> Dict[str, Any]:
"""configuration fixture"""
if not os.path.exists(os.path.expanduser("~/.config/pvoutput.json")):
print("Failed to fi... | yaleman/pvoutput | tests/test_live_sync.py | .py | b4f656b33b24f77a | 8.04 | 11 |
"""tests parameters things"""
import copy
from datetime import datetime
from typing import Any, Dict
import pytest
from pvoutput import PVOutput
from pvoutput.base import PVOutputBase
from pvoutput.parameters import ADDSTATUS_PARAMETERS
def test_addstatus_default_date() -> None:
"""tests if the default date is s... | yaleman/pvoutput | tests/test_parameters.py | .py | 80c96b4948a4d9cd | 8.04 | 11 |
import os
from pathlib import Path
from setuptools import setup, Extension
from setuptools.command.build_clib import build_clib
from setuptools.command.build_ext import build_ext
import subprocess
import sys
from Cython.Build import cythonize
ROOT = Path(__file__).resolve().parent
ZLIB_DIR = str(ROOT / 'zlib_build')... | jeremymcrae/bgen | setup.py | .py | dc37897c1d14978f | 7.64 | 18 |
import sqlite3
import logging
import os
from typing import Optional, Union
import numpy as np
from numpy.typing import NDArray
class Index:
def __init__(self, path: Union[str, os.PathLike[str]]) -> None:
logging.debug(f'opening bgen index: {path}')
self.path = str(path)
self.conn = sqlite... | jeremymcrae/bgen | src/bgen/index.py | .py | 93f9042f45debda3 | 7.64 | 18 |
from pathlib import Path
import unittest
import pickle
import numpy as np
from bgen import BgenReader
class TestBgenVar(unittest.TestCase):
''' class to make sure BgenVar works correctly
'''
def setUp(self):
''' set path to folder with test data
'''
self.folder = Path(__file... | jeremymcrae/bgen | tests/test_bgenvar.py | .py | f17ca815cfb46dd6 | 8.14 | 18 |
from pathlib import Path
import unittest
import numpy as np
from bgen import BgenReader
from bgen.index import Index
from tests.utils import load_gen_data
class TestBgenIndex(unittest.TestCase):
''' class to make sure bgen.index.Index works correctly
'''
@classmethod
def setUpClass(cls):
cl... | jeremymcrae/bgen | tests/test_index.py | .py | b70a0d24c97a47ac | 8.14 | 18 |
from pathlib import Path
import unittest
import numpy as np
from bgen import BgenReader, BgenWriter
from tests.utils import load_gen_data, load_vcf_data, load_haps_data, arrays_equal
class TestExampleBgens(unittest.TestCase):
''' class to make sure we can load bgen files
'''
@classmethod
def setUpC... | jeremymcrae/bgen | tests/test_load_example_files.py | .py | 318076a3e8a12b7d | 8.14 | 18 |
from pathlib import Path
import re
import numpy as np
def can_cap_memory():
''' whether this platform can actually cap a child's address space
macOS defines RLIMIT_AS (aliased to RLIMIT_RSS in its headers), so the constant
existing does not mean setrlimit() on it works. The kernel there rejects the call... | jeremymcrae/bgen | tests/utils.py | .py | f7d08de4b71ab3b1 | 8.14 | 18 |
import numpy as np
from scipy.sparse import dok_matrix
import DNA as d
import warnings
import collections
import copy
from gpu import cp, GPU_AVAILABLE
class Node:
''' This is a root/parent class which creates objects with the basic structure of nodes. It does not have an features.'''
# nodeCount = 0
# ed... | AkandaAshraf/VirtualSoc | Node.py | .py | 778af3b4d1034f88 | 7.59 | 14 |
import copy
from collections import abc
from locust.contrib.fasthttp import FastHttpUser
from yaml import load
from .config import relay_address, generate_project_info, load_org_profiles, ProjectInfo
from .util import memoize, load_object
try:
from yaml import CFullLoader as FullLoader
except ImportError:
fr... | getsentry/ingest-load-tester | infrastructure/configurable_user.py | .py | a120237b7f558610 | 7.45 | 7 |
import pathlib
FIXTURE_PATH = pathlib.Path(__file__).parent.parent.parent / "test-events"
DEFAULT_MINIDUMP = "minidump.dmp"
def minidump_generator(filename: str = DEFAULT_MINIDUMP, **kwargs):
"""
minidump format is hard to synthesize, so we just use a single fixture which is read once at factory-build
... | getsentry/ingest-load-tester | infrastructure/generators/minidump.py | .py | 72c370df8e33bd60 | 7.45 | 7 |
import pathlib
import json
import random
import time
import uuid
import zlib
FIXTURE_PATH = pathlib.Path(__file__).parent.parent.parent / "test-events"
def replay_envelope_generator(
min_segments: int,
max_segments: int,
replay_type: str,
release: str | None,
environment: str | None,
compres... | getsentry/ingest-load-tester | infrastructure/generators/replay.py | .py | 1f884b4ab0f6f8de | 7.45 | 7 |
import random
from infrastructure.generators.util import version_generator
def tags_generator(min=0, max=100, tag_values_per_tag=100):
"""
Generate tags dictionary, at least `min` tags and at most `max`.
Tag names are very predictable such that you can directly control tag *key*
cardinality by incre... | getsentry/ingest-load-tester | infrastructure/generators/tags.py | .py | e34a6934cdeaf8f9 | 7.45 | 7 |
import random
def schema_generator(**fields):
"""
Generate a dictionary instance according to the schema outlined by the
provided kwargs. Supports:
* string
* number
* callable
* range object
* list of any of the above (random item will be selected)
"""
def inner():
r... | getsentry/ingest-load-tester | infrastructure/generators/util.py | .py | e260d562117c0665 | 7.45 | 7 |
import functools
import os
import re
from datetime import timedelta
from importlib import import_module
from typing import Optional
from uuid import uuid4
def full_path_from_module_relative_path(module_name, *args):
dir_path = os.path.dirname(os.path.realpath(module_name))
return os.path.abspath(os.path.join... | getsentry/ingest-load-tester | infrastructure/util.py | .py | d799e5cbad8a3d9b | 7.45 | 7 |
"""
Tasks and task helpers to be used to generate kafka events and outcomes
"""
import time
from infrastructure.configurable_user import get_project_info
from infrastructure.generators.event import base_event_generator
from infrastructure.kafka import Outcome, kafka_send_outcome, kafka_send_event
import random
from i... | getsentry/ingest-load-tester | tasks/kafka_tasks.py | .py | e9d576f04daa57ba | 7.45 | 7 |
#!/usr/bin/env python3
import configparser
import os
import sys
from io import StringIO
import pandas as pd
import psycopg2
config = configparser.ConfigParser()
workdir = os.path.dirname(os.path.abspath(__file__))
configfile = os.path.join(workdir, "config.ini")
config.read(configfile)
def pull_resource(connection=... | tagbase/tagbase-server | services/docker-cron/poll_metadata_and_obs_types.py | .py | f0afa4b3b2854b8a | 7.45 | 7 |
# coding: utf-8
from connexion.jsonifier import JSONEncoder as ConnexionJSONEncoder
from connexion.jsonifier import Jsonifier
from tagbase_server.models.base_model_ import Model
class ModelJSONEncoder(ConnexionJSONEncoder):
"""JSON encoder that serializes generated OpenAPI models."""
include_nulls = False
... | tagbase/tagbase-server | tagbase_server/tagbase_server/encoder.py | .py | e1fa6db9213fe01b | 7.45 | 7 |
import pprint
import typing
from tagbase_server import util
T = typing.TypeVar("T")
class Model(object):
# openapiTypes: The key is attribute name and the
# value is attribute type.
openapi_types: typing.Dict[str, type] = {}
# attributeMap: The key is attribute name and the
# value is json key ... | tagbase/tagbase-server | tagbase_server/tagbase_server/models/base_model_.py | .py | e97e9e88f5363266 | 7.45 | 7 |
# coding: utf-8
"""Unit-level ingest controller checks (no Postgres).
Full ingest success paths live under test/integration/.
"""
import shutil
from pathlib import Path
from tagbase_server.test.helpers import API_PREFIX, ETUFF_FIXTURE
def test_ingest_get_rejects_netcdf_ingest_file_type(client):
dest = Path("/... | tagbase/tagbase-server | tagbase_server/tagbase_server/test/test_ingest_controller.py | .py | 56777afd3d2e295a | 7.95 | 7 |
import datetime
import typing
from tagbase_server import typing_utils
def _deserialize(data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return Non... | tagbase/tagbase-server | tagbase_server/tagbase_server/util.py | .py | 94ad229a94171b10 | 7.45 | 7 |
import logging
import os
import psycopg2
from tagbase_server.models.response500 import Response500 # noqa: E501
from tagbase_server.telemetry import record_db_error
logger = logging.getLogger(__name__)
_SCHEMA_READY = False
def assert_schema_ready(conn):
"""Fail fast with a clear message when tagbase tables ... | tagbase/tagbase-server | tagbase_server/tagbase_server/utils/db_utils.py | .py | d2665c1794055c21 | 7.45 | 7 |
import hashlib
import logging
import os
import re
import tempfile
from time import time
from urllib.request import urlopen
from pyunpack import Archive
logger = logging.getLogger(__name__)
TEMP_DIR = tempfile.gettempdir()
_URL_SCHEME_PREFIX = re.compile(r"(?:file|ftp|https?)://[^/]*")
def compute_file_sha256(file_... | tagbase/tagbase-server | tagbase_server/tagbase_server/utils/io_utils.py | .py | ff3f3ff251d74317 | 7.45 | 7 |
"""Compatibility layer to handle systems that cannot run Playwright."""
# pylint: disable=unused-import
# mypy: ignore-errors
import sys
try:
from playwright.sync_api import Browser as PlaywrightBrowser
from playwright.sync_api import ElementHandle
from playwright.sync_api import ElementHandle as Playwr... | jacebrowning/pomace | pomace/compat.py | .py | f5c5a09c5d3a6f53 | 7.52 | 10 |
"""Configuration file for sniffer."""
import time
import subprocess
from sniffer.api import select_runnable, file_validator, runnable
try:
from pync import Notifier
except ImportError:
notify = None
else:
notify = Notifier.notify
watch_paths = ["pomace", "tests"]
class Options:
group = int(time.ti... | jacebrowning/pomace | scent.py | .py | d316c39b2f770664 | 7.52 | 10 |
"""Integration tests configuration file."""
# pylint: disable=unused-argument,redefined-outer-name
import os
import datafiles
import log
import pytest
from pomace import shared, utils
from pomace.config import settings as _settings
def pytest_configure(config):
log.init(debug=True)
log.silence("parse", "f... | jacebrowning/pomace | tests/conftest.py | .py | 0dde0e259f92f0fd | 8.02 | 10 |
# -*- coding: utf-8 -*-
"""Holds the Config class and an instance to use as global configuration."""
from pathlib import Path
from dataclasses import dataclass, asdict, field
import yaml
from astar_utils.cache_dir import get_write_cache_dir
from .exceptions import SpextraError
__all__ = ["config"]
__data_dir__ = Pa... | AstarVienna/speXtra | spextra/configuration.py | .py | 535d23509462d394 | 7.42 | 6 |
# -*- coding: utf-8 -*-
"""Database for speXtra."""
import shutil
from io import StringIO
from pathlib import Path
from dataclasses import dataclass
import yaml
from astar_utils import NestedMapping
from .downloads import fetch_data_file
from .configuration import config
__all__ = ["load_yamldict", "spextra_databa... | AstarVienna/speXtra | spextra/database.py | .py | 9194e22494c25edf | 7.42 | 6 |
# -*- coding: utf-8 -*-
"""Utility functions for downloads.
Cache locations are resolved through ``astar_utils.cache_dir``, which knows
about ScopeSim_Data and the shared ``~/.astar`` cache. All pooch-specific code
lives here in spextra, so that astar-utils stays dependency-free.
The pattern throughout is "check trus... | AstarVienna/speXtra | spextra/downloads.py | .py | a829afae55b47635 | 7.42 | 6 |
# -*- coding: utf-8 -*-
"""Spextra-specfic exceptions and errors, for encapsulation."""
__all__ = [
"SpextraError",
"NotInDatabaseError",
"NotInLibraryError",
"ArgumentError",
"ConstructorError",
]
class SpextraError(Exception):
"""Base class for errors in this Package."""
class NotInD... | AstarVienna/speXtra | spextra/exceptions.py | .py | 6a1ec0e9b2bbda0d | 7.42 | 6 |
import os
import json
import requests
APP_URL_FORMAT = "http://{}:8001/api/v2/applications/{}"
APPS = {'YouTube': '111299001912',
'Plex': '3201512006963',
'Prime Video': '3201512006785',
'Universal Guide': '3201710015067',
'Netflix': '11101200001',
'Apple TV': '3201807016597',
... | jakubpas/samsungctl | samsungctl/application.py | .py | e04dd0487eb52601 | 7.52 | 10 |
from telegram import Update
from telegram.ext import CallbackContext
from gym_bot_app import KISSING_HEART_EMOJI
from gym_bot_app.commands import Command
from gym_bot_app.decorators import get_trainee_and_group
from gym_bot_app.models import Trainee, Group
class SetCreatureCommand(Command):
"""Telegram gym bot s... | AsafSH6/GymBot | gym_bot_app/commands/set_creature.py | .py | e2b07687c80317c6 | 7.62 | 16 |
from mongoengine import QuerySet, DoesNotExist
class ExtendedQuerySet(QuerySet):
"""Extension of default QuerySet."""
def get(self, *q_objs, **query):
"""Override method to look for 'id' argument and cast it to str.
If object does not exist catches the exception and returns None.
""... | AsafSH6/GymBot | gym_bot_app/query_sets.py | .py | b182c72611ab4e90 | 7.62 | 16 |
from datetime import time, timedelta, datetime
from typing import List
from telegram import ParseMode
from gym_bot_app.models import Trainee, Group
from gym_bot_app.tasks import Task
from gym_bot_app.utils import get_trainees_that_selected_today_and_did_not_train_yet
from gym_bot_app.decorators import run_for_all_gro... | AsafSH6/GymBot | gym_bot_app/tasks/did_not_train_updater.py | .py | b41c35c4e02b2492 | 7.62 | 16 |
from datetime import time
from typing import List
from telegram import ParseMode
from gym_bot_app.models import Group, Trainee
from gym_bot_app.tasks import Task
from gym_bot_app.decorators import run_for_all_groups
from gym_bot_app.utils import get_trainees_that_selected_today_and_did_not_train_yet
class GoToGymTa... | AsafSH6/GymBot | gym_bot_app/tasks/go_to_gym.py | .py | af3715c2c106453c | 7.62 | 16 |
"""Guards on packaging metadata and repository hygiene."""
import os
import re
import subprocess
import unittest
import AutoClicker
REPO_ROOT = os.path.dirname(os.path.abspath(AutoClicker.__file__))
def read(*parts):
with open(os.path.join(REPO_ROOT, *parts), "r", encoding="utf-8") as handle:
return ha... | kai9987kai/AutoClicker | tests/test_packaging.py | .py | 99616fb87ee4584b | 8.14 | 18 |
"""Built-in matchers used by skivvy"""
# coding=utf-8
import inspect
import re
import uuid as uuid_module
from datetime import datetime
from math import fabs
import requests
from skivvy.util.scope import has, fetch, store
from skivvy.util import file_util
from skivvy.util import log
from skivvy.path_tracker import P... | hyrfilm/skivvy | src/skivvy/matchers.py | .py | 2e1b4ae65bfb9586 | 7.6 | 15 |
import json
from functools import partial
from typing import Dict, Mapping, Callable, Any
from urllib.parse import urljoin
from skivvy.brace_expansion import brace_expand_string
from skivvy.config import Settings, conf_get
from skivvy.util import dict_util, log, str_util, file_util
from skivvy.util.dict_util import ge... | hyrfilm/skivvy | src/skivvy/test_runner.py | .py | 7766dd9ccec6cffc | 8.1 | 15 |
import collections.abc
from functools import wraps
from operator import itemgetter
def subset(d: dict, keys: list[str], include_none=True) -> dict:
"""Returns a subset of a dictionary whose keys are included in keys."""
def should_include(key):
if include_none:
return key in d
els... | hyrfilm/skivvy | src/skivvy/util/dict_util.py | .py | 5a3381f7798cc9de | 7.6 | 15 |
# Based on https://github.com/jeffkaufman/icdiff
import difflib
import stat
from typing import Iterable, List, Optional, Tuple
from rich.console import Console
from rich.table import Table
from rich.text import Text
class RichConsoleDiff:
"""Side-by-side diff using Rich for colors/layout.
Keeps the spirit o... | hyrfilm/skivvy | src/skivvy/util/icdiff2.py | .py | 3d6a1e7ca67c0542 | 7.6 | 15 |
import difflib
import json
import re
from functools import cache, partial
from typing import AnyStr
def _colorize_diff(diff_text: str) -> str:
"""
Lightweight markup-based coloring for diff output when Rich rendering
isn't available. Uses red for removals, green for additions, yellow for
inline hints,... | hyrfilm/skivvy | src/skivvy/util/str_util.py | .py | fd0d8c1c38e7a3dd | 7.6 | 15 |
import uuid
import pytest
from skivvy import matchers
from skivvy.util import file_util, scope
@pytest.fixture
def isolated_matcher_state(monkeypatch):
# Matchers mutate global module state (registry + options), so tests that
# exercise matcher registration should run against a per-test snapshot.
monkey... | hyrfilm/skivvy | tests/conftest.py | .py | 556f7571e05e6d55 | 7.1 | 15 |
"""Tests for matcher syntax used inside array elements."""
import pytest
from skivvy.verify import verify
# --- Matchers on plain values inside arrays ---
def test_matcher_on_scalar_in_array_passes():
# $between matcher applied to a scalar element in an array
verify(["$between 1 3"], [1, 2, 3])
def test_m... | hyrfilm/skivvy | tests/test_array_matchers.py | .py | b5da83404ab43917 | 7.1 | 15 |
import sys
from skivvy.skivvy import run
from skivvy.util import file_util
# TODO: This a ugly and slow and bad and hacky since we're hitting the actual end-points but blabla fix laterrrz
def test_jsonplaceholder_examples():
cfg_file = "examples/typicode/default.json"
result = run_examples(cfg_file)
ass... | hyrfilm/skivvy | tests/test_examples.py | .py | 321e2aa8c4d70fa4 | 7.1 | 15 |
import json
def identity(x):
return x
def json_transform_str(data, transform=identity, sort_keys=True):
"""
Dump a mapping to a JSON string, optionally apply a transform function,
and return the resulting JSON string.
data: mapping (e.g. dict) to serialize.
transform: optional function taki... | hyrfilm/skivvy | tests/test_util.py | .py | ac505965bd243b51 | 8.1 | 15 |
from __future__ import annotations
import argparse
from typing import Any, Callable, Iterable
__all__ = ["Arg", "Group", "Subparsers", "Mutex"]
class Arg:
"""Argparse-passthrough marker attached to a model field via ``Annotated[T, Arg(...)]``.
``option_strings`` (``-f``, ``--foo``) make the field an option... | SunDoge/typed-args | src/typed_args/_arg.py | .py | 3599d2ecfc2fad53 | 7.59 | 14 |
from __future__ import annotations
import argparse
class DefaultHelpFormatter(argparse.HelpFormatter):
"""Show ``FOO`` instead of ``subcommand.FOO`` as the metavar.
The builder uses dotted dest names (``subcommand.file``) so values land in
the right nested slot; this formatter strips the dotted prefix b... | SunDoge/typed-args | src/typed_args/_formatter.py | .py | 9ccd51d0a0ea8e6c | 7.59 | 14 |
from __future__ import annotations
import argparse
from typing import Optional, Sequence, TypeVar
from pydantic import BaseModel, ConfigDict
from ._builder import _resolve_optional_subcommands, build_parser
M = TypeVar("M", bound=BaseModel)
T = TypeVar("T", bound="TypedArgs")
def _ns_to_tree(ns: argparse.Namespac... | SunDoge/typed-args | src/typed_args/_parser.py | .py | eba34cd0a1bf7f9f | 7.59 | 14 |
"""Integrating a library-exported Args into a host argparse parser."""
import argparse
from typing import Annotated
import typed_args as ta
class LibArgs(ta.TypedArgs):
host: Annotated[str, ta.Arg("--host", help="db host")] = "localhost"
port: Annotated[int, ta.Arg("-p")] = 5432
tls: Annotated[bool, ta.... | SunDoge/typed-args | tests/test_merge.py | .py | 3b07cec677592779 | 8.09 | 14 |
from dataclasses import dataclass
from functools import lru_cache
from typing import Final, Tuple
import re
class ArnException(ValueError):
"""Thrown when an arn cannot be parsed."""
AWS_ARN_REGEX: Final = re.compile(
r"""
^arn:
(?P<partition>.*?):
(?P<service>.*?):
(?P<region>.*?):
(?... | coveooss/coveo-python-oss | coveo-arnparse/coveo_arnparse/__init__.py | .py | ce288886ec108945 | 7.66 | 20 |
import pytest
from coveo_testing.markers import UnitTest
from coveo_testing.parametrize import parametrize
from coveo_arnparse import arnparse, ArnException
@UnitTest
@parametrize(
"arn",
[
"arn:aws:firehose:us-east-1:064790157154:deliverystream/ndev-document-status",
"arn:aws:firehose:us-eas... | coveooss/coveo-python-oss | coveo-arnparse/tests_coveo_arnparse/test_arnparse.py | .py | f024fb995d11be82 | 8.16 | 20 |
"""Annotation-related utilities."""
import sys
from dataclasses import InitVar
from typing import Type, Dict, get_type_hints, Callable, Union, Any
def find_annotations(
thing: Union[Type, Callable], globalns: Dict[str, Any] = None
) -> Dict[str, Type]:
"""Even though get_type_hints claims to follow inheritan... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/annotations.py | .py | 78338a5f230fad55 | 7.66 | 20 |
import functools
import re
from typing import Match, Iterable, Dict, Callable, Any, TypeVar, Mapping, Type, Final
import inflection
from .annotations import find_annotations
T = TypeVar("T")
# noinspection PyDefaultArgument
def snake_case(string: str, bad_casing: Iterable[str] = ()) -> str:
"""return the snak... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/casing.py | .py | 31d21dc43670887f | 7.66 | 20 |
"""singledispatch is too young and needs a little help..."""
from functools import singledispatch as _singledispatch, update_wrapper
import inspect
from typing import Any, Type, cast, Union, Callable, TypeVar
from typing_extensions import Protocol
T = TypeVar("T")
class SingleDispatch(Protocol[T]):
def register... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/dispatch.py | .py | 87170414a6009f51 | 7.66 | 20 |
from typing import Any
class CoveoFunctoolsException(Exception):
"""Base class for coveo-functools exceptions."""
class Flexception(CoveoFunctoolsException): # sorry for the pun :socanadian:
"""Base class for exceptions raised by the flex module."""
class UnsupportedAnnotation(Flexception, NotImplemented... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/exceptions.py | .py | fa6512d50deeab8d | 7.66 | 20 |
import enum
import inspect
import logging
import sys
import warnings
from collections import abc
from contextlib import contextmanager
from enum import Enum
from inspect import isabstract, isclass
from typing import (
Type,
TypeVar,
Optional,
Any,
Union,
Dict,
overload,
... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/flex/deserializer.py | .py | b79d805bf90e4d37 | 7.66 | 20 |
from typing import Dict, Type, Callable, Any, Optional, TypeVar
from coveo_functools.flex.types import TypeHint
T = TypeVar("T")
_factory_adapters: Dict[Type, Callable[[Any], TypeHint]] = {}
def register_factory_adapter(hint: TypeHint, factory: Callable[[Any], T]) -> None:
"""
Registers a custom factory f... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/flex/factory_adapter.py | .py | a632bdfce2af9df6 | 7.66 | 20 |
from dataclasses import InitVar
from inspect import isclass
from typing import (
Optional,
get_args,
get_origin,
Tuple,
List,
Sequence,
Literal,
Any,
)
from coveo_functools.exceptions import UnsupportedAnnotation
from coveo_functools.flex.types import TypeHint, PASSTHROUGH... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/flex/helpers.py | .py | 159dec24192423c1 | 7.66 | 20 |
from __future__ import annotations
from dataclasses import dataclass, field
from importlib import import_module
from inspect import isclass
from typing import Any, Dict, Optional
from coveo_functools.annotations import find_annotations
from coveo_functools.flex.types import TypeHint
@dataclass
class Ser... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/flex/serializer.py | .py | d57f57e3ff9cbd79 | 7.66 | 20 |
from typing import Dict, Type, Callable, Any, Optional, TypeVar
from coveo_functools.flex.types import TypeHint
T = TypeVar("T")
_subclass_adapters: Dict[Type, Callable[[Any], TypeHint]] = {}
def register_subclass_adapter(hint: TypeHint, adapter: Callable[[Any], TypeHint]) -> None:
"""
Registe... | coveooss/coveo-python-oss | coveo-functools/coveo_functools/flex/subclass_adapter.py | .py | 0af5112c1d256877 | 7.66 | 20 |
"""Tests the annotation module."""
import attr
from coveo_testing.markers import UnitTest
from coveo_functools.annotations import find_return_annotation, find_annotations
@attr.s(auto_attribs=True)
class MockDataClassBase:
a: int = int # type: ignore
b: str = str # type: ignore
@attr.s(auto_attribs=Tru... | coveooss/coveo-python-oss | coveo-functools/tests_functools/test_annotations.py | .py | 95babeadb7535919 | 8.16 | 20 |
import logging
import sys
from dataclasses import dataclass, InitVar
from enum import Enum
from typing import Final, List, Any, Optional, Union, Dict, Type, Tuple, Literal
import pytest
from _pytest.logging import LogCaptureFixture
from coveo_functools.flex.helpers import resolve_hint
from coveo_testing.mar... | coveooss/coveo-python-oss | coveo-functools/tests_functools/test_flex_deserializer.py | .py | bc69707d2daf581f | 7.16 | 20 |
"""Tests the wait method features"""
import datetime
from typing import List, Type, Tuple, TypedDict
from coveo_testing.markers import UnitTest
from coveo_testing.parametrize import parametrize
import pytest
from coveo_functools import wait
from coveo_functools.wait import TimeoutValue, Backoff, NoBackoff, MaxBackof... | coveooss/coveo-python-oss | coveo-functools/tests_functools/test_wait.py | .py | ec9e9e70561cb4c7 | 8.16 | 20 |
"""
This is a copy of the old distutils.version module, which is deprecated.
We need to migrate to packaging.version, but it's not a trivial change.
note: the deprecation warning has been removed.
"""
import re
class Version:
"""Abstract base class for version numbering classes. Just provides
constructor (... | coveooss/coveo-python-oss | coveo-pypi-cli/coveo_pypi_cli/_distutils.py | .py | 186940900e13741a | 7.66 | 20 |
from coveo_pypi_cli._distutils import Version, StrictVersion
from typing import List, Type, TypeVar, Optional
from coveo_settings.settings import StringSetting
import requests
from .exceptions import VersionException
from .versions import StrictVersionHelper
PYPI_CLI_INDEX = StringSetting("pypi.cli.index", fallback... | coveooss/coveo-python-oss | coveo-pypi-cli/coveo_pypi_cli/pypi.py | .py | f06facf84f108dfb | 7.66 | 20 |
"""version-related helpers"""
from coveo_pypi_cli._distutils import StrictVersion, Version
from typing import Union, Optional
class StrictVersionHelper(StrictVersion):
"""internal helper 'coz tuple juggling is no fun!"""
def __init__(self, vstring: Union[Version, str] = None) -> None:
super().__init... | coveooss/coveo-python-oss | coveo-pypi-cli/coveo_pypi_cli/versions.py | .py | 0fe50d010badcc7c | 7.66 | 20 |
#!/usr/bin/env python3
# coding: utf-8
__author__ = 'Mário Antunes'
__version__ = '1.0'
__email__ = 'mario.antunes@ua.pt'
__status__ = 'Development'
__license__ = 'MIT'
__copyright__ = '''
Copyright (c) 2021-2023 Stony Brook University
Copyright (c) 2021-2023 The Research Foundation of SUNY
'''
import logging
import... | mariolpantunes/knee | examples/plot_journal_filters.py | .py | cabb2f8404c71d32 | 7.45 | 7 |
#!/usr/bin/env python3
# coding: utf-8
__author__ = 'Mário Antunes'
__version__ = '1.0'
__email__ = 'mario.antunes@ua.pt'
__status__ = 'Development'
__license__ = 'MIT'
__copyright__ = '''
Copyright (c) 2021-2023 Stony Brook University
Copyright (c) 2021-2023 The Research Foundation of SUNY
'''
import tqdm
import lo... | mariolpantunes/knee | examples/plot_journal_mrc.py | .py | f70f81ec5b972a88 | 7.45 | 7 |
#!/usr/bin/env python3
"""
Measure how well a simplified curve still represents the original, and
optionally render the result.
Runs each RDP variant over the same curve and reports, per variant, how many
points survived and what that reduction costs under every available metric -
using `evaluation.compute_global_seg... | mariolpantunes/knee | examples/rdp_cost_and_frames.py | .py | 80c1c1275dde7f08 | 7.45 | 7 |
#!/usr/bin/env python3
"""
Score how sharp a corner is, using `postprocessing.triangle_area`.
The area of the triangle formed by a point and its two neighbours is a cheap,
local measure of how hard the curve bends there: collinear points enclose
nothing, a sharp corner encloses a lot. On evenly spaced x it is exactly... | mariolpantunes/knee | examples/triangle_area_corners.py | .py | 98a3fa65b0e34ce9 | 7.45 | 7 |
'''
The following module provides knee detection based on the AutoElbow method.
AutoElbow scores each point by a ratio of squared distances to three fixed
references, and takes the largest. It has no tuning parameters and runs in a
single pass, which makes it a useful counterweight to the threshold-driven
methods els... | mariolpantunes/knee | src/kneeliverse/autoelbow.py | .py | 9d84b39ab108f8ad | 7.45 | 7 |
'''
The following module provides knee detection method
based on equation curvature.
'''
__author__ = 'Mário Antunes'
__version__ = '1.0'
__email__ = 'mario.antunes@ua.pt'
__status__ = 'Development'
__license__ = 'MIT'
__copyright__ = '''
Copyright (c) 2021-2023 Stony Brook University
Copyright (c) 2021-2023 The Rese... | mariolpantunes/knee | src/kneeliverse/curvature.py | .py | 49cd8786389c38f0 | 7.45 | 7 |
"""
Read the parsed JSON artifact and sync spiders to Airtable.
Runs in the privileged workflow (workflow_run, base-repo context).
The JSON is treated as untrusted input — it was produced by a workflow
running on a fork PR's code. Validate before doing anything with it.
"""
import json
import re
import sys
from pathl... | City-Bureau/city-scrapers-core | .github/scripts/sync_from_json.py | .py | 129c4ea326e8988b | 7.48 | 8 |
from functools import wraps
def ignore_processed(func):
"""Method decorator to ignore processed items passed to pipeline by middleware.
This should be used on the ``process_item`` method of any additional custom
pipelines used to handle :class:`Meeting` objects to make sure that ``dict`` items
passed... | City-Bureau/city-scrapers-core | city_scrapers_core/decorators.py | .py | 25a55a2ae7c732bc | 7.48 | 8 |
from scrapy.extensions.feedexport import BlockingFeedStorage
class AzureBlobFeedStorage(BlockingFeedStorage):
"""
Subclass of :class:`scrapy.extensions.feedexport.BlockingFeedStorage` for writing
scraper results to Azure Blob Storage.
:param uri: Azure Blob Storage URL including an account name, cred... | City-Bureau/city-scrapers-core | city_scrapers_core/extensions/azure_storage.py | .py | 9a789be6cfa9fa1c | 7.48 | 8 |
from datetime import datetime
import pytz
from scrapy import Spider, signals
from scrapy.crawler import Crawler
RUNNING = "running"
FAILING = "failing"
STATUS_COLOR_MAP = {RUNNING: "#44cc11", FAILING: "#cb2431"}
STATUS_ICON = """
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width... | City-Bureau/city-scrapers-core | city_scrapers_core/extensions/status.py | .py | d7fbef145bf91565 | 7.48 | 8 |
from scrapy import Item, Spider
from ..constants import NOT_CLASSIFIED, TENTATIVE
from ..decorators import ignore_processed
class DefaultValuesPipeline:
"""Pipeline for setting default values on scraped Item objects"""
@ignore_processed
def process_item(self, item: Item, spider: Spider) -> Item:
... | City-Bureau/city-scrapers-core | city_scrapers_core/pipelines/default.py | .py | 997f5e994f4c72bb | 7.48 | 8 |
from datetime import datetime, timedelta
from scrapy import Item, Spider
from ..decorators import ignore_processed
class MeetingPipeline:
"""General pipeline for setting some defaults on meetings, can be subclassed for
additional processing.
"""
@ignore_processed
def process_item(self, item: It... | City-Bureau/city-scrapers-core | city_scrapers_core/pipelines/meeting.py | .py | f58ebd9e565b0581 | 7.48 | 8 |
from datetime import datetime
from typing import Mapping
from uuid import uuid1
import pytz
from scrapy import Spider
from ..decorators import ignore_processed
class OpenCivicDataPipeline:
"""Pipeline for transforming Meeting items into the `Open Civic Data Event format
<https://opencivicdata.readthedocs.io... | City-Bureau/city-scrapers-core | city_scrapers_core/pipelines/ocd.py | .py | 690cd1d3cf63f6f2 | 7.48 | 8 |
import logging
from collections import defaultdict
from typing import Mapping
from jsonschema.validators import Draft7Validator
from scrapy import Spider
from scrapy.crawler import Crawler
logger = logging.getLogger(__name__)
class ValidationPipeline:
"""Pipeline for validating whether a scraper's results match... | City-Bureau/city-scrapers-core | city_scrapers_core/pipelines/validation.py | .py | 25e85c9732c41d30 | 7.48 | 8 |
import re
from datetime import datetime
from typing import Mapping, Optional
from pytz import timezone
from scrapy import Spider
from ..constants import CANCELLED, PASSED, TENTATIVE
class CityScrapersSpider(Spider):
"""Base Spider class for City Scrapers projects. Provides a few utilities for common
tasks l... | City-Bureau/city-scrapers-core | city_scrapers_core/spiders/spider.py | .py | 11f25ca429d43ddd | 7.48 | 8 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# https://git-cral.univ-lyon1.fr/MUSE/mpdaf/-/blob/23d52ba059fe76df5e1655542b17a28a7137cf20/LICENSE
"""
The classes in the astropy docs are documented by their API location,
which is not necessarily where they are defined in the source. This
causes a prob... | City-Bureau/city-scrapers-core | docs/ext/smart_resolver.py | .py | 917003f6a0eb4eb8 | 7.48 | 8 |
#! /usr/bin/env python
'''Setup file for genie.trafficgen Namespace Package
See:
https://packaging.python.org/en/latest/distributing.html
'''
import re
import os
from setuptools import setup, find_namespace_packages
def read(*paths):
'''read and return txt content of file'''
with open(os.path.join(os.p... | CiscoTestAutomation/genietrafficgen | setup.py | .py | 90a4eb44986b5a79 | 7.56 | 12 |
import os
import unittest
import importlib
from ipaddress import IPv4Address
from unittest.mock import Mock, patch
from ixnetwork_restpy.errors import BadRequestError
from genie.harness.exceptions import GenieTgnError
from pyats.topology import loader
class chassis_mock:
State = 'ready'
class mock_session:
S... | CiscoTestAutomation/genietrafficgen | src/genie/trafficgen/tests/test_ixiarestpy.py | .py | f93e51ee80486c4a | 8.06 | 12 |
#! /usr/bin/env python
'''Setup file for pyats.contrib
See:
https://packaging.python.org/en/latest/distributing.html
'''
import os
import re
from setuptools import setup, find_namespace_packages
from os import listdir
from os.path import join, dirname
def read(*paths):
'''read and return txt content of fil... | CiscoTestAutomation/pyats.contrib | setup.py | .py | 0d22df137a6e415f | 7.65 | 19 |
# Python
import logging
from time import sleep, time
# pyAts
from pyats.async_ import pcall
from pyats.log.utils import banner
from pyats.easypy.plugins.bases import BasePlugin
# Logger
log = logging.getLogger('ats.easypy.%s' % __name__)
class TopologyUpPlugin(BasePlugin):
'''
Runs before job starts, to ver... | CiscoTestAutomation/pyats.contrib | src/pyats/contrib/plugins/topoup_plugin/topoup.py | .py | f4f832a57b6f6613 | 7.65 | 19 |
import json
import logging
import os
import socket
import requests
from pyats.configuration import configuration as cfg
from pyats.easypy.plugins.bases import BasePlugin
logger = logging.getLogger(__name__)
MESSAGE_URL = 'https://webexapis.com/v1/messages'
MESSAGE_TEMPLATE = """
## JOB RESULT REPORT
```
Job ID ... | CiscoTestAutomation/pyats.contrib | src/pyats/contrib/plugins/webex_plugin/webex.py | .py | b7cb013c0630339e | 7.65 | 19 |
#! /usr/bin/env python
import os
import re
from setuptools import setup, find_packages
def read(*paths):
'''read and return txt content of file'''
with open(os.path.join(*paths)) as fp:
return fp.read()
def find_version(*paths):
'''reads a file and returns the defined __version__ value'''
... | CiscoTestAutomation/pyats-image-builder | setup.py | .py | 0a80e48154de7b3e | 7.52 | 10 |
import re
import shutil
import logging
import pathlib
import tempfile
class Context(object):
def __init__(self,
keep=False,
logger=logging.getLogger(__name__),
prefix='pyats-image.'):
'''
a temp directory used as docker build context directory
... | CiscoTestAutomation/pyats-image-builder | src/pyatsimagebuilder/context.py | .py | 4706ef14de81cc41 | 7.52 | 10 |
#! /bin/env python
'''Setup file for Libs
See:
https://packaging.python.org/en/latest/distributing.html
'''
import os
import re
from setuptools import setup, find_namespace_packages
# generate package dependencies
install_requires = ['selenium']
def read(*paths):
'''read and return txt content of file'''
... | CiscoTestAutomation/geniewebdriver | setup.py | .py | 3537d45ba2195303 | 7.5 | 9 |
from selenium.webdriver.common.by import By
# mapping for converting func(By.ID, 'value') to func(id = value)
LOCATOR_MAPPING = dict(id = By.ID,
xpath = By.XPATH,
link = By.LINK_TEXT,
link_text = By.LINK_TEXT,
partial_link = By... | CiscoTestAutomation/geniewebdriver | src/genie/webdriver/utils.py | .py | cbdf197e0a759616 | 7.5 | 9 |
from __future__ import with_statement
import os
from logging.config import fileConfig
from alembic import context
from oslo_config import cfg
from sqlalchemy import create_engine, pool
# this is the shipyard config object
CONF = cfg.CONF
# this is the Alembic Config object, which provides
# access to the values wit... | airshipit/shipyard | src/bin/shipyard_airflow/alembic/env.py | .py | 51e3c5a17ef62a2a | 7.65 | 19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.