Ejemplo n.º 1
0
PlayerData = TypedDict(
    "PlayerData",
    {
        "season": int,
        "round": str,
        "date": str,
        "local_start_time": str,
        "venue": str,
        "attendance": int,
        "home_team": str,
        "hq1g": int,
        "hq1b": int,
        "hq2g": int,
        "hq2b": int,
        "hq3g": int,
        "hq3b": int,
        "hq4g": int,
        "hq4b": int,
        "home_score": int,
        "away_team": str,
        "aq1g": int,
        "aq1b": int,
        "aq2g": int,
        "aq2b": int,
        "aq3g": int,
        "aq3b": int,
        "aq4g": int,
        "aq4b": int,
        "away_score": int,
        "first_name": str,
        "surname": str,
        "id": int,
        "jumper_no": int,
        "playing_for": str,
        "kicks": int,
        "marks": int,
        "handballs": int,
        "goals": int,
        "behinds": int,
        "hit_outs": int,
        "tackles": int,
        "rebounds": int,
        "inside_50s": int,
        "clearances": int,
        "clangers": int,
        "frees_for": int,
        "frees_against": int,
        "brownlow_votes": int,
        "contested_possessions": int,
        "uncontested_possessions": int,
        "contested_marks": int,
        "marks_inside_50": int,
        "one_percenters": int,
        "bounces": int,
        "goal_assists": int,
        "time_on_ground": int,
        "substitute": int,
        "umpire_1": str,
        "umpire_2": str,
        "umpire_3": str,
        "umpire_4": str,
        "group_id": int,
    },
)
Ejemplo n.º 2
0
def internal_dissolve_vector(
    vector: Union[str, ogr.DataSource],
    attribute: Optional[str] = None,
    out_path: str = None,
    overwrite: bool = True,
    add_index: bool = True,
    process_layer: int = -1,
) -> str:
    """Clips a vector to a geometry."""
    type_check(vector, [str, ogr.DataSource], "vector")
    type_check(attribute, [str], "attribute", allow_none=True)
    type_check(out_path, [str], "out_path", allow_none=True)
    type_check(overwrite, [bool], "overwrite")
    type_check(add_index, [bool], "add_index")
    type_check(process_layer, [int], "process_layer")

    vector_list, path_list = ready_io_vector(vector, out_path)
    out_name = path_list[0]
    out_format = path_to_driver_vector(out_name)

    driver = ogr.GetDriverByName(out_format)

    ref = open_vector(vector_list[0])
    metadata = internal_vector_to_metadata(ref)

    Layer_info = TypedDict(
        "Layer_info",
        {
            "name": str,
            "geom": str,
            "fields": List[str]
        },
    )

    layers: List[Layer_info] = []

    if process_layer == -1:
        for index in range(len(metadata["layers"])):
            layers.append({
                "name": metadata["layers"][index]["layer_name"],
                "geom": metadata["layers"][index]["column_geom"],
                "fields": metadata["layers"][index]["field_names"],
            })
    else:
        layers.append({
            "name":
            metadata["layers"][process_layer]["layer_name"],
            "geom":
            metadata["layers"][process_layer]["column_geom"],
            "fields":
            metadata["layers"][process_layer]["field_names"],
        })

    destination: ogr.DataSource = driver.CreateDataSource(out_name)

    # Check if attribute table is valid
    for index in range(len(metadata["layers"])):
        layer = layers[index]
        if attribute is not None and attribute not in layer["fields"]:
            layer_fields = layer["fields"]
            raise ValueError(
                f"Invalid attribute for layer. Layers has the following fields: {layer_fields}"
            )

        geom_col = layer["geom"]
        name = layer["name"]

        sql = None
        if attribute is None:
            sql = f"SELECT ST_Union({geom_col}) AS geom FROM {name};"
        else:
            sql = f"SELECT {attribute}, ST_Union({geom_col}) AS geom FROM {name} GROUP BY {attribute};"

        result = ref.ExecuteSQL(sql, dialect="SQLITE")
        destination.CopyLayer(result, name, ["OVERWRITE=YES"])

    if add_index:
        vector_add_index(destination)

    destination.FlushCache()

    return out_name
Ejemplo n.º 3
0
import os

from mypy_extensions import TypedDict

Environment = TypedDict(
    "Environment",
    {
        "permission_url": str,
        "media_url": str,
        "datastore_reader_url": str,
        "datastore_writer_url": str,
    },
)

DEFAULTS = {
    "PERMISSION_PROTOCOL": "http",
    "PERMISSION_HOST": "localhost",
    "PERMISSION_PORT": "9005",
    "PERMISSION_PATH": "/internal/permission",
    "MEDIA_PROTOCOL": "http",
    "MEDIA_HOST": "localhost",
    "MEDIA_PORT": "9006",
    "MEDIA_PATH": "/internal/media",
    "DATASTORE_READER_PROTOCOL": "http",
    "DATASTORE_READER_HOST": "localhost",
    "DATASTORE_READER_PORT": "9010",
    "DATASTORE_READER_PATH": "/internal/datastore/reader",
    "DATASTORE_WRITER_PROTOCOL": "http",
    "DATASTORE_WRITER_HOST": "localhost",
    "DATASTORE_WRITER_PORT": "9011",
    "DATASTORE_WRITER_PATH": "/internal/datastore/writer",
Ejemplo n.º 4
0
class SearchResults(NamedTuple):
    """Represents a set of search results."""

    total_hits: int
    previous_page: Optional[int]
    current_page: int
    next_page: Optional[int]
    limit: int
    start: int
    end: int
    total: int
    scored_hits: int
    results: List[SearchResult]


class IndexablePage(NamedTuple):
    """Representation of a source page suitable for indexing."""

    page: SourcePage
    indexable_content: str


SiteTreePart = TypedDict('SiteTreePart', {
    'children': 'SiteTree',
    'title': str,
    'path': str
})

SiteTree = Dict[str, SiteTreePart]
import asyncio
import time
from typing import List, Any, Dict, Union, Awaitable, Optional

from mypy_extensions import TypedDict

from aiocrypto_prices._api_requests import fetch_price_data, fetch_coin_list
from aiocrypto_prices.exceptions import CurrencyNotFound, UnfetchedInformation

CurrencyKwargs = TypedDict(
    'CurrencyKwargs', {
        'cache': int,
        'target_currencies': List[str],
        'full': bool,
        'historical': Optional[str],
        'human': bool
    })


class Prices:
    """Prices object"""
    def __init__(self, currency: 'Currency') -> None:
        self._prices: Dict[str, float] = {}
        self._currency = currency

    async def get(self, target_currency: str, default: float = 0.0) -> float:
        """
        Gets the price for a specified currency, if currency is not in target currencies,
        it's added there for the specific currency

        :param target_currency:     Currency to get converted price for
Ejemplo n.º 6
0
config = ConfigHandler()
"""
Final entry point to get an set config variables. To get a config variable
use x = config[...], to set it use config[...] = x.
"""


T = TypeVar('T')
ChoiceType = Optional[Iterable[Dict[str, str]]]
ChoiceCallableType = Union[ChoiceType, Callable[[], ChoiceType]]
ValidatorsType = Iterable[Callable[[T], None]]
OnChangeType = Callable[[], None]
ConfigVariableDict = TypedDict('ConfigVariableDict', {
    'key': str,
    'default_value': Any,
    'input_type': str,
    'label': str,
    'help_text': str,
    'choices': ChoiceType,
})


class ConfigVariable:
    """
    A simple object class to wrap new config variables.

    The keyword arguments 'name' and 'default_value' are required.

    The keyword arguments 'input_type', 'label', 'help_text' and 'hidden'
    are for rendering a HTML form element. The 'input_type is also used for
    validation. If you set 'input_type' to 'choice' you have to provide
    'choices', which is a list of dictionaries containing a value and a
Ejemplo n.º 7
0
RawDeckDescription = TypedDict(
    'RawDeckDescription',
    {
        'name': str,  # Name of Deck
        'url': str,  # Source URL of Deck
        'source': str,  # Source name
        'identifier': str,  # Unique ID
        'cards': CardsDescription,  # Contents of Deck
        'archetype': Optional[str],
        'created_date':
        float,  # Date deck was created.  If null, current time will be used.
        # One of these three usernames is required:
        'mtgo_username': Optional[str],
        'tappedout_username': Optional[str],
        'mtggoldfish_username': Optional[str],

        # TappedOut Variables
        'resource_uri': Optional[str],
        'featured_card': Optional[str],
        'score': Optional[int],
        'thumbnail_url': Optional[str],
        'small_thumbnail_url': Optional[str],
        'slug': Optional[str],
        'user': Optional[str],  # This is mapped to tappedout_username

        # Competition variables (League/Gatherling)
        'competition_id': Optional[int],
        'finish': Optional[int],
        'wins': int,
        'losses': int,
        'draws': int,
    },
    total=False)
Ejemplo n.º 8
0
"""
Final entry point to get an set config variables. To get a config variable
use x = config[...], to set it use config[...] = x.
"""

T = TypeVar("T")
ChoiceType = Optional[Iterable[Dict[str, str]]]
ChoiceCallableType = Union[ChoiceType, Callable[[], ChoiceType]]
ValidatorsType = Iterable[Callable[[T], None]]
OnChangeType = Callable[[], None]
ConfigVariableDict = TypedDict(
    "ConfigVariableDict",
    {
        "key": str,
        "default_value": Any,
        "input_type": str,
        "label": str,
        "help_text": str,
        "choices": ChoiceType,
    },
)


class ConfigVariable:
    """
    A simple object class to wrap new config variables.

    The keyword arguments 'name' and 'default_value' are required.

    The keyword arguments 'input_type', 'label', 'help_text' and 'hidden'
    are for rendering a HTML form element. The 'input_type is also used for
Ejemplo n.º 9
0
    to_dict, )
from mypy_extensions import (
    TypedDict, )

from ssz.exceptions import (
    DeserializationError, )
from ssz.hash import (
    hash_eth2, )
from ssz.sedes.base import (
    BaseSedes,
    LengthPrefixedSedes,
)
from ssz.utils import (
    get_duplicates, )

AnyTypedDict = TypedDict("AnyTypedDict", {})
TAnyTypedDict = TypeVar("TAnyTypedDict", bound=AnyTypedDict)


class Container(LengthPrefixedSedes[TAnyTypedDict, Dict[str, Any]]):

    length_bytes = 4

    def __init__(self, fields: Sequence[Tuple[str, BaseSedes[Any,
                                                             Any]]]) -> None:
        field_names = tuple(field_name for field_name, field_sedes in fields)
        duplicate_field_names = get_duplicates(field_names)
        if duplicate_field_names:
            raise ValueError(
                f"The following fields are duplicated {','.join(sorted(duplicate_field_names))}"
            )
Ejemplo n.º 10
0
from mypy_extensions import TypedDict
from speclib import array

curve448_test = TypedDict('curve448_test', {
    'private': str,
    'public': str,
    'result': str,
    'valid': bool
})

curve448_test_vectors: array[curve448_test] = array([{
    'private':
    '3d262fddf9ec8e88495266fea19a34d28882acef045104d0d1aae121700a779c984c24f8cdd78fbff44943eba368f54b29259a4f1c600ad3',
    'public':
    '06fce640fa3487bfda5f6cf2d5263f8aad88334cbd07437f020f08f9814dc031ddbdc38c19c6da2583fa5429db94ada18aa7a7fb4ef8a086',
    'result':
    'ce3e4ff95a60dc6697da1db1d85e6afbdf79b50a2412d7546d5f239fe14fbaadeb445fc66a01b0779d98223961111e21766282f73dd96b6f',
    'valid': True
}, {
    'private':
    '203d494428b8399352665ddca42f9de8fef600908e0d461cb021f8c538345dd77c3e4806e25f46d3315c44e0a5b4371282dd2c8d5be3095f',
    'public':
    '0fbcc2f993cd56d3305b0b7d9e55d4c1a8fb5dbb52f8e9a1e9b6201b165d015894e56c4d3570bee52fe205e28a78b91cdfbde71ce8d157db',
    'result':
    '884a02576239ff7a2f2f63b2db6a9ff37047ac13568e1e30fe63c4a7ad1b3ee3a5700df34321d62077e63633c575c1c954514e99da7c179d',
    'valid': True
}, {
    'private':
    '9a8f4925d1519f5775cf46b04b5800d4ee9ee8bae8bc5565d498c28dd9c9baf574a9419744897391006382a6f127ab1d9ac2d8c0a598726b',
    'public':
    '3eb7a829b0cd20f5bcfc0b599b6feccf6da4627107bdb0d4f345b43027d8b972fc3e34fb4232a13ca706dcb57aec3dae07bdc1c67bf33609',
Ejemplo n.º 11
0
    Hash32,
    HexStr,
)
from mypy_extensions import (
    TypedDict,
)

if TYPE_CHECKING:
    from eth.abc import VirtualMachineAPI  # noqa: F401


JournalDBCheckpoint = NewType('JournalDBCheckpoint', int)

AccountDetails = TypedDict('AccountDetails',
                           {'balance': int,
                            'nonce': int,
                            'code': bytes,
                            'storage': Dict[int, int]
                            })
AccountState = Dict[Address, AccountDetails]

AccountDiff = Iterable[Tuple[Address, str, Union[int, bytes], Union[int, bytes]]]

GeneralState = Union[
    AccountState,
    List[Tuple[Address, Dict[str, Union[int, bytes, Dict[int, int]]]]]
]

GenesisDict = Dict[str, Union[int, BlockNumber, bytes, Hash32]]

BytesOrView = Union[bytes, memoryview]
Ejemplo n.º 12
0
    # notifications to match the model of push notifications
    # above.
    if idle and (private_message or mentioned):
        # We require RabbitMQ to do this, as we can't call the email handler
        # from the Tornado process. So if there's no rabbitmq support do nothing
        if not already_notified.get("email_notified"):
            queue_json_publish("missedmessage_emails", notice,
                               lambda notice: None)
            notified['email_notified'] = True

    return notified


ClientInfo = TypedDict(
    'ClientInfo', {
        'client': ClientDescriptor,
        'flags': Optional[Iterable[str]],
        'is_sender': bool,
    })


def get_client_info_for_message_event(event_template, users):
    # type: (Mapping[str, Any], Iterable[Mapping[str, Any]]) -> Dict[str, ClientInfo]
    '''
    Return client info for all the clients interested in a message.
    This basically includes clients for users who are recipients
    of the message, with some nuances for bots that auto-subscribe
    to all streams, plus users who may be mentioned, etc.
    '''

    send_to_clients = {}  # type: Dict[str, ClientInfo]
Ejemplo n.º 13
0
from typing import Any, Dict, List, Optional, Set, Union

import simplejson as json
from mypy_extensions import TypedDict

from ...shared.filters import Filter as FilterInterface
from ...shared.filters import FilterData
from ...shared.interfaces import Event, WriteRequestElement
from ...shared.patterns import Collection, FullQualifiedId
from .deleted_models_behaviour import DeletedModelsBehaviour

GetManyRequestData = TypedDict(
    "GetManyRequestData",
    {
        "collection": str,
        "ids": List[int],
        "mapped_fields": List[str]
    },
    total=False,
)


class GetManyRequest:
    """
    Encapsulates a single GetManyRequest to be used for get_many requests to the
    datastore.
    """

    mapped_fields: Optional[Set[str]]

    def __init__(
Ejemplo n.º 14
0
class MesosState(TypedDict):
    slaves: List
    frameworks: List
    orphan_tasks: List


MesosMetrics = TypedDict(
    "MesosMetrics",
    {
        "master/cpus_total": int,
        "master/cpus_used": int,
        "master/disk_total": int,
        "master/disk_used": int,
        "master/gpus_total": int,
        "master/gpus_used": int,
        "master/mem_total": int,
        "master/mem_used": int,
        "master/tasks_running": int,
        "master/tasks_staging": int,
        "master/tasks_starting": int,
        "master/slaves_active": int,
        "master/slaves_inactive": int,
    },
)


class MesosMaster:
    def __init__(self, config):
        self.config = config

    def __str__(self):
Ejemplo n.º 15
0
tracer = jaeger_config.initialize_tracer()

app = Starlette(debug=True)
app.add_middleware(CORSMiddleware,
                   allow_origins=["*"],
                   allow_methods=["*"],
                   allow_headers=["*"])

SPANS: typing.Dict[str, opentracing.Span] = {}

StartSpanExtractRequest = TypedDict(
    "StartSpanExtractRequest",
    {
        "name": str,
        "reference": dict,
        "relationship": typing.Union[Literal["child_of"],
                                     Literal["follows_from"]],
    },
)

StartSpanRequest = TypedDict(
    "StartSpanRequest",
    {
        "name": str,
        "reference": dict,
        "relationship": typing.Union[Literal["child_of"],
                                     Literal["follows_from"]],
    },
)
Ejemplo n.º 16
0
from collections import OrderedDict, defaultdict
from functools import partial
from itertools import chain
from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Tuple
from warnings import warn

from . import place
from .comments import parse as parse_comments
from .deprecated.finders import FindersManager
from .settings import DEFAULT_CONFIG, Config

if TYPE_CHECKING:
    from mypy_extensions import TypedDict

    CommentsAboveDict = TypedDict("CommentsAboveDict", {
        "straight": Dict[str, Any],
        "from": Dict[str, Any]
    })

    CommentsDict = TypedDict(
        "CommentsDict",
        {
            "from": Dict[str, Any],
            "straight": Dict[str, Any],
            "nested": Dict[str, Any],
            "above": CommentsAboveDict,
        },
    )


def _infer_line_separator(contents: str) -> str:
    if "\r\n" in contents:
Ejemplo n.º 17
0
if TYPE_CHECKING:
    from mypy_extensions import TypedDict
else:

    def TypedDict(*args, **kwargs):
        pass


Span = TypedDict(
    "Span",
    {
        "trace_id": str,
        "parent_span_id": str,
        "span_id": str,
        "start_timestamp": float,
        "timestamp": float,
        "same_process_as_parent": bool,
        "op": str,
        "description": Optional[str],
        "fingerprint": Optional[Sequence[str]],
        "tags": Optional[Any],
        "data": Optional[Any],
    },
)

# A callable strategy is a callable that when given a span, it tries to
# returns a fingerprint. If the strategy does not apply to the span, it
# should return `None` to indicate that the strategy should not be used
# and to try a different strategy. If the strategy does apply, it should
# return a list of strings that will serve as the span fingerprint.
CallableStrategy = Callable[[Span], Optional[Sequence[str]]]
Ejemplo n.º 18
0
    from mypy_extensions import TypedDict

    from pip._internal.distributions import AbstractDistribution
    from pip._internal.index.package_finder import PackageFinder
    from pip._internal.models.link import Link
    from pip._internal.network.download import Downloader
    from pip._internal.req.req_install import InstallRequirement
    from pip._internal.req.req_tracker import RequirementTracker
    from pip._internal.utils.hashes import Hashes

    if PY2:
        CopytreeKwargs = TypedDict(
            'CopytreeKwargs',
            {
                'ignore': Callable[[str, List[str]], List[str]],
                'symlinks': bool,
            },
            total=False,
        )
    else:
        CopytreeKwargs = TypedDict(
            'CopytreeKwargs',
            {
                'copy_function': Callable[[str, str], None],
                'ignore': Callable[[str, List[str]], List[str]],
                'ignore_dangling_symlinks': bool,
                'symlinks': bool,
            },
            total=False,
        )
Ejemplo n.º 19
0
from paasta_tools.utils import load_system_paasta_config
from paasta_tools.utils import paasta_print
from paasta_tools.utils import PaastaColors
from paasta_tools.utils import print_with_indent
from paasta_tools.utils import set_paasta_print_file

log = logging.getLogger('paasta_metastatus')
logging.basicConfig()
# kazoo can be really noisy - turn it down
logging.getLogger("kazoo").setLevel(logging.CRITICAL)
logging.getLogger("paasta_tools.autoscaling.autoscaling_cluster_lib").setLevel(
    logging.ERROR)

ServiceInstanceStats = TypedDict('ServiceInstanceStats', {
    'mem': float,
    'cpus': float,
    'disk': float,
    'gpus': int
})


class FatalError(Exception):
    def __init__(
        self,
        exit_code: int,
    ) -> None:
        self.exit_code = exit_code


def parse_args(argv):
    parser = argparse.ArgumentParser(description='', )
    parser.add_argument(
Ejemplo n.º 20
0
import six
from six.moves import urllib, zip_longest
from mypy_extensions import TypedDict

# no imports from cwltool allowed


if os.name == 'posix':
    import subprocess32 as subprocess  # type: ignore # pylint: disable=import-error,unused-import
else:
    import subprocess  # type: ignore # pylint: disable=unused-import

windows_default_container_id = "frolvlad/alpine-bash"

Directory = TypedDict('Directory',
                      {'class': Text, 'listing': List[Dict[Text, Text]],
                       'basename': Text})

DEFAULT_TMP_PREFIX = "tmp"

processes_to_kill = collections.deque()  # type: Deque[subprocess.Popen]

def versionstring():
    # type: () -> Text
    '''
    version of CWLtool used to execute the workflow.
    '''
    pkg = pkg_resources.require("cwltool")
    if pkg:
        return u"%s %s" % (sys.argv[0], pkg[0].version)
    return u"%s %s" % (sys.argv[0], "unknown version")
Ejemplo n.º 21
0
 def make_builtin_typed_dict(self, name, annotations, total):
     return TypedDict(name, annotations, total=total)
Ejemplo n.º 22
0
        return timezone_info['error_message']
    if timezone_info['status'] == 'ZERO_RESULTS':
        raise TooFewItemsException(timezone_info['status'])
    try:
        timezone = dtutil.timezone(timezone_info['timeZoneId'])
    except KeyError as e:
        raise TooFewItemsException(
            f'Unable to find a timezone in {timezone_info}')
    return {
        current_time(timezone, twentyfour):
        [info['results'][0]['formatted_address']]
    }


WISDateType = TypedDict('WISDateType', {
    'exact': str,
    'rough': str,
})

WISSetInfoType = TypedDict(
    'WISSetInfoType', {
        'name': str,
        'code': str,
        'codename': str,
        'mtgoCode': str,
        'symbol': str,
        'enterDate': WISDateType,
        'exitDate': WISDateType,
    })

WISSchemaType = TypedDict('WISSchemaType', {
    'deprecated': bool,
Ejemplo n.º 23
0
    healthcheck_interval_seconds: float
    healthcheck_max_consecutive_failures: int
    healthcheck_mode: str
    healthcheck_timeout_seconds: float
    healthcheck_uri: str
    instances: int
    max_instances: int
    min_instances: int
    nerve_ns: str
    registrations: List[str]
    replication_threshold: int
    bounce_priority: int


# Defined here to avoid import cycles -- this gets used in bounce_lib and subclassed in marathon_tools.
BounceMethodConfigDict = TypedDict('BounceMethodConfigDict', {"instances": int})


class ServiceNamespaceConfig(dict):

    def get_healthcheck_mode(self) -> str:
        """Get the healthcheck mode for the service. In most cases, this will match the mode
        of the service, but we do provide the opportunity for users to specify both. Default to the mode
        if no healthcheck_mode is specified.
        """
        healthcheck_mode = self.get('healthcheck_mode', None)
        if not healthcheck_mode:
            return self.get_mode()
        else:
            return healthcheck_mode
Ejemplo n.º 24
0
use x = config[...], to set it use config[...] = x.
"""


T = TypeVar("T")
ChoiceType = Optional[Iterable[Dict[str, str]]]
ChoiceCallableType = Union[ChoiceType, Callable[[], ChoiceType]]
ValidatorsType = Iterable[Callable[[T], None]]
OnChangeType = Callable[[], None]
ConfigVariableDict = TypedDict(
    "ConfigVariableDict",
    {
        "defaultValue": Any,
        "inputType": str,
        "label": str,
        "helpText": str,
        "choices": ChoiceType,
        "weight": int,
        "group": str,
        "subgroup": Optional[str],
    },
)


class ConfigVariable:
    """
    A simple object class to wrap new config variables.

    The keyword arguments 'name' and 'default_value' are required.

    The keyword arguments 'input_type', 'label', 'help_text' and 'hidden'
Ejemplo n.º 25
0
    healthcheck_interval_seconds: float
    healthcheck_max_consecutive_failures: int
    healthcheck_mode: str
    healthcheck_timeout_seconds: float
    healthcheck_uri: str
    instances: int
    max_instances: int
    min_instances: int
    nerve_ns: str
    registrations: List[str]
    replication_threshold: int
    bounce_start_deadline: float


# Defined here to avoid import cycles -- this gets used in bounce_lib and subclassed in marathon_tools.
BounceMethodConfigDict = TypedDict("BounceMethodConfigDict",
                                   {"instances": int})


class ServiceNamespaceConfig(dict):
    def get_healthcheck_mode(self) -> str:
        """Get the healthcheck mode for the service. In most cases, this will match the mode
        of the service, but we do provide the opportunity for users to specify both. Default to the mode
        if no healthcheck_mode is specified.
        """
        healthcheck_mode = self.get("healthcheck_mode", None)
        if not healthcheck_mode:
            return self.get_mode()
        else:
            return healthcheck_mode

    def get_mode(self) -> str:
Ejemplo n.º 26
0
from pytest import approx  # type: ignore


def test_temperature():
    assert temperature(f_temp=72) == {"c_temp": approx(22.22222), "f_temp": 72}
    assert temperature(c_temp=22.2) == {
        "c_temp": 22.2,
        "f_temp": approx(71.96)
    }


from mypy_extensions import TypedDict

TempDict = TypedDict("TempDict", {
    "c_temp": float,
    "f_temp": float,
})


def temperature_d(*,
                  f_temp: Optional[float] = None,
                  c_temp: Optional[float] = None) -> TempDict:
    """Convert between Fahrenheit temperature and
    Celsius temperature.

    :key f_temp: Temperature in °F.
    :key c_temp: Temperature in °C.
    :returns: dictionary with two keys:
        :f_temp: Temperature in °F.
        :c_temp: Temperature in °C.
    """
Ejemplo n.º 27
0
        else:
            return all([
                res.get("since", 0) < (time.time() - self.delay)
                for res in results
            ])


class StatusCodeNotAcceptableError(Exception):
    pass


UrlSpec = TypedDict(
    'UrlSpec',
    {
        'url_format': str,
        'method': str,
        'success_codes': str,
    },
    total=False,
)


@register_drain_method('http')
class HTTPDrainMethod(DrainMethod):
    """This drain policy issues arbitrary HTTP calls to arbitrary URLs specified by the parameters. The URLs are
    specified as format strings, and will have variables such as {host}, {port}, etc. filled in."""
    def __init__(
        self,
        service: str,
        instance: str,
        registrations: List[str],
Ejemplo n.º 28
0
 def rewrite_TypedDict(self, typed_dict):
     return TypedDict(typed_dict.__name__, {
         name: self.rewrite(typ)
         for name, typ in typed_dict.__annotations__.items()
     },
                      total=typed_dict.__total__)
Ejemplo n.º 29
0
    UserProfile,
    UserMessage,
    Reaction,
    get_usermessage_by_message_id,
)

from typing import Any, Dict, List, Optional, Set, Tuple, Union, Sequence
from mypy_extensions import TypedDict

RealmAlertWords = Dict[int, List[str]]

RawUnreadMessagesResult = TypedDict(
    'RawUnreadMessagesResult', {
        'pm_dict': Dict[int, Any],
        'stream_dict': Dict[int, Any],
        'huddle_dict': Dict[int, Any],
        'mentions': Set[int],
        'muted_stream_ids': List[int],
        'unmuted_stream_msgs': Set[int],
    })

UnreadMessagesResult = TypedDict(
    'UnreadMessagesResult', {
        'pms': List[Dict[str, Any]],
        'streams': List[Dict[str, Any]],
        'huddles': List[Dict[str, Any]],
        'mentions': List[int],
        'count': int,
    })

# We won't try to fetch more unread message IDs from the database than
Ejemplo n.º 30
0
import traceback
from datetime import date
from email.utils import formatdate
from glob import glob

import magic
from debian.deb822 import Deb822

from . import message_catalogs, sourcefileprocessing, umc
from .helper import make_parent_dir

try:
	from typing import Any, Dict, Iterable, Iterator, List, Optional, Pattern, Tuple, Type  # noqa F401
	from types import TracebackType  # noqa
	from mypy_extensions import TypedDict
	BaseModule = TypedDict('BaseModule', {'module_name': str, 'binary_package_name': str, 'abs_path_to_src_pkg': str, 'relative_path_src_pkg': str})
except ImportError:
	pass


REFERENCE_LANG = 'de'
UMC_MODULES = '.umc-modules'
# Use this set to ignore whole sub trees of a given source tree
DIR_BLACKLIST = {
	'doc',
	'umc-module-templates',
	'test',
	'testframework',
}
# do not translate modules with these names, as they are examples and thus not worth the effort
MODULE_BLACKLIST = {