def test_isnewtype(self): assert typechecks.is_newtype(NewType("foo", str)) assert not typechecks.is_newtype(type(NewType("foo", str)("bar"))) assert not typechecks.is_typeddict(str)
from typing import NewType TelegramID = NewType("TelegramID", int)
# Copyright©2020 Max-Planck-Gesellschaft zur Förderung # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute # for Intelligent Systems. All rights reserved. # # Contact: Vassilis Choutas, [email protected] import sys from typing import NewType, List, Dict import torch import torch.optim as optim from loguru import logger from torchtrustncg import TrustRegionNewtonCG Tensor = NewType('Tensor', torch.Tensor) def build_optimizer(parameters: List[Tensor], optim_cfg: Dict) -> Dict: ''' Creates the optimizer ''' optim_type = optim_cfg.get('type', 'sgd') logger.info(f'Building: {optim_type.title()}') num_params = len(parameters) parameters = list(filter(lambda x: x.requires_grad, parameters)) if num_params != len(parameters): logger.info(f'Some parameters have requires_grad off') if optim_type == 'adam': optimizer = optim.Adam(parameters, **optim_cfg.get('adam', {}))
"NVT_CVES_POS", "NVT_BIDS_POS", "NVT_XREFS_POS", "NVT_CATEGORY_POS", "NVT_TIMEOUT_POS", "NVT_FAMILY_POS", "NVT_NAME_POS", ] # Name of the namespace usage bitmap in redis. DBINDEX_NAME = "GVM.__GlobalDBIndex" logger = logging.getLogger(__name__) # Types RedisCtx = NewType('RedisCtx', redis.Redis) class OpenvasDB: """ Class to connect to redis, to perform queries, and to move from a KB to another.""" _db_address = None @classmethod def get_database_address(cls) -> Optional[str]: if not cls._db_address: settings = Openvas.get_settings() cls._db_address = settings.get('db_address')
"""Here we implement your custom types. """ from typing import NewType import asyncio import sys import slack import requests if sys.platform == 'win32': EventLoop = NewType('EventLoop', asyncio.windows_events._WindowsSelectorEventLoop) else: EventLoop = NewType('EventLoop', asyncio.unix_events._UnixSelectorEventLoop) RTMClient = NewType('RTMClient', slack.RTMClient) WebClient = NewType('WebClient', slack.WebClient) Response = NewType('Response', requests.models.Response)
from mgr_module import HandleCommandResult, MonCommandFailed from ceph.deployment.service_spec import ServiceSpec, RGWSpec from ceph.deployment.utils import is_ipv6, unwrap_ipv6 from orchestrator import OrchestratorError, DaemonDescription from cephadm import utils from mgr_util import create_self_signed_cert, ServerConfigException, verify_tls if TYPE_CHECKING: from cephadm.module import CephadmOrchestrator logger = logging.getLogger(__name__) ServiceSpecs = TypeVar('ServiceSpecs', bound=ServiceSpec) AuthEntity = NewType('AuthEntity', str) class CephadmDaemonSpec(Generic[ServiceSpecs]): # typing.NamedTuple + Generic is broken in py36 def __init__( self, host: str, daemon_id: str, spec: Optional[ServiceSpecs] = None, network: Optional[str] = None, keyring: Optional[str] = None, extra_args: Optional[List[str]] = None, ceph_conf: str = '', extra_files: Optional[Dict[str, Any]] = None, daemon_type: Optional[str] = None,
# Copyright (c) 2020 Tulir Asokan # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from typing import Optional, Dict, Any, List, NewType from uuid import UUID from attr import dataclass import attr from mautrix.types import SerializableAttrs, SerializableEnum GroupID = NewType('GroupID', str) @dataclass class Account(SerializableAttrs['Account']): device_id: int = attr.ib(metadata={"json": "deviceId"}) username: str filename: str registered: bool has_keys: bool subscribed: bool uuid: Optional[UUID] = None @dataclass(frozen=True, eq=False) class Address(SerializableAttrs['Address']): number: Optional[str] = None uuid: Optional[UUID] = None
from typing import Tuple, Set, List, Mapping, Any, Union, Callable, NewType try: from typing import Literal except ImportError: # pragma: nocover HAVE_LITERAL = False else: HAVE_LITERAL = True import pytest from hypothesis import given from hypothesis.strategies import builds, register_type_strategy, booleans from validobj.validation import parse_input, ValidationError stralias = NewType('stralias', str) class Attributes(enum.Flag): READ = enum.auto() WRITE = enum.auto() EXECUTE = enum.auto() class MemOptions(enum.Enum): SMALL = 'small' MEDIUM = 'medium' BIG = 'big' @dataclasses.dataclass(frozen=True)
self.round_robin: List[MonoQueue] = list() self.name = name def __str___(self) -> None: return f"{self.name}_SharedTransceiver" @abstractmethod def register_customers(self, ) -> None: raise NotImplementedError("Implement register_customers") @abstractmethod def run(self) -> None: raise NotImplementedError("Implement run") BGR = NewType('BGR', np.ndarray) class Frame(NamedTuple): timestamp: datetime frame: BGR class BBox(NamedTuple): left: int top: int right: int bottom: int class TrackedObject(NamedTuple):
import abc import collections from typing import TYPE_CHECKING, Deque, NewType, Optional, TypeVar from afancontrol.configparser import ConfigParserSection if TYPE_CHECKING: from afancontrol.temp import TempStatus T = TypeVar("T") FilterName = NewType("FilterName", str) def from_configparser( section: ConfigParserSection[FilterName]) -> "TempFilter": filter_type = section["type"] if filter_type == "moving_median": window_size = section.getint("window_size", fallback=3) return MovingMedianFilter(window_size=window_size) elif filter_type == "moving_quantile": window_size = section.getint("window_size", fallback=3) quantile = section.getfloat("quantile") return MovingQuantileFilter(quantile=quantile, window_size=window_size) else: raise RuntimeError( "Unsupported filter type '%s' for filter '%s'. " "Supported types: `moving_median`, `moving_quantile`." % (filter_type, section.name))
from __future__ import annotations from typing import NewType, List from abc import ABC, abstractmethod Move = NewType('Move', int) class Piece: @property def opposite(self) -> Piece: raise NotImplementedError("Should be implemented by subclasses.") class Board(ABC): @property @abstractmethod def turn(self) -> Piece: ... @abstractmethod def move(self, location: Move) -> Board: ... @property @abstractmethod def legal_moves(self) -> List[Move]: ... @property
timestamp_to_date, ts_now, ) from rotkehlchen.utils.serialization import rlk_jsondumps, rlk_jsonloads_dict if TYPE_CHECKING: from rotkehlchen.db.dbhandler import DBHandler logger = logging.getLogger(__name__) log = RotkehlchenLogsAdapter(logger) PRICE_HISTORY_FILE_PREFIX = 'cc_price_history_' T_PairCacheKey = str PairCacheKey = NewType('PairCacheKey', T_PairCacheKey) RATE_LIMIT_MSG = 'You are over your rate limit please upgrade your account!' CRYPTOCOMPARE_QUERY_RETRY_TIMES = 3 CRYPTOCOMPARE_RATE_LIMIT_WAIT_TIME = 60 CRYPTOCOMPARE_SPECIAL_CASES_MAPPING = { Asset('TLN'): A_WETH, Asset('BLY'): A_USDT, Asset('cDAI'): A_DAI, Asset('cCOMP'): A_COMP, Asset('cBAT'): Asset('BAT'), Asset('cREP'): Asset('REP'), Asset('cSAI'): Asset('SAI'), Asset('cUSDC'): Asset('USDC'), Asset('cUSDT'): A_USDT, Asset('cWBTC'): Asset('WBTC'),
import colorama from colorama import Fore, Style from jsonschema import ValidationError, validate from tabulate import tabulate import requests import semtk3 from semtk3.semtktable import SemtkTable import yaml __author__ = "Eric Mertens" __email__ = "*****@*****.**" # NOTE: Do **not** use the root logger via `logging.command(...)`, instead use `logger.command(...)` logger = logging.getLogger(__name__) Connection = NewType('Connection', str) Url = NewType('Url', str) class Graph(Enum): """Enumeration of SemTK graph types""" DATA = "data" MODEL = "model" class CLIMethod(Enum): """Enumeration of the CLI methods (for context in error reporting)""" DATA_IMPORT = "data import" MODEL_IMPORT = "model import" OTHER_CLI_METHOD = "..." # In the absence of overwrite, this will be the default cliMethod = CLIMethod.OTHER_CLI_METHOD
import calendar import re as regex from dataclasses import dataclass, field from datetime import datetime from enum import Enum from typing import List, Literal, NewType, Optional, Union from vocal.constants import ISO3166Country, PaymentMethodType from vocal.locale.en_us import USState, USAddress ChargeID = NewType('ChargeID', str) CustomerProfileID = NewType('CustomerProfileID', str) RecurringChargeID = NewType('RecurringChargeID', str) PaymentMethodID = NewType('PaymentMethodID', str) class ACHAccountType(Enum): Checking = 'checking' Savings = 'savings' BusinessChecking = 'business_checking' BusinessSavings = 'business_savings' @dataclass class PaymentCredential: method_type: PaymentMethodType method_family: str @property def expire_after_date(self) -> Optional[datetime]:
from enum import Enum from typing import NewType, Union import minknow.rpc.data_pb2 as data import minknow.rpc.data_pb2_grpc as data_rpc DataType = NewType("DataType", data.GetDataTypesResponse.DataType) import numpy as np DataTypeType = Enum(value="DataTypeType", names=data.GetDataTypesResponse.DataType.Type.items()) def get_numpy_type( dataType: DataType ) -> Union[np.uint8, np.uint16, np.uint32, np.int8, np.int16, np.int32, np.float]: datatype = (dataType.type, dataType.size) # Mapping of (type, size) to a numpy data type. type_and_size_to_numpy = { (DataTypeType.UNSIGNED_INTEGER.value, 1): np.uint8, (DataTypeType.UNSIGNED_INTEGER.value, 2): np.uint16, (DataTypeType.UNSIGNED_INTEGER.value, 4): np.uint32, (DataTypeType.SIGNED_INTEGER.value, 1): np.int8, (DataTypeType.SIGNED_INTEGER.value, 2): np.int16, (DataTypeType.SIGNED_INTEGER.value, 4): np.int32, (DataTypeType.FLOATING_POINT.value, 4): np.float, } numpy_type = type_and_size_to_numpy[datatype]
# limitations under the License. """Tracing functionality for Python control flow graph execution.""" import copy import dataclasses from typing import Dict, List, NewType, Text from absl import logging # pylint: disable=unused-import # Branch decisions: TRUE_BRANCH = 0 FALSE_BRANCH = 1 NO_BRANCH_DECISION = 2 Values = NewType("Values", Dict[Text, int]) @dataclasses.dataclass class Trace: """The sequence of statements that were run during a program execution. A Trace represents the sequence of statements that were run during the execution of a program and the branch decisions made along the way. cfg_node_index_values and statement_branch_decisions are indexed by statement index. cfg_node_index_values[3] gives the values of all variables after each execution of statement with index 3. Attributes: trace_cfg_node_indexes: index in cfg.nodes of statements run (in order of
from datetime import datetime, timedelta from logging import getLogger from typing import Any, Dict, Iterable, List, NewType from google.cloud import firestore import blotter.bigquery_helpers as bigquery_helpers import ib_insync from gcloud_service.error_handler import ErrorHandlerConfiguration from blotter.ib_helpers import IBThread, deserialize_contract, serialize_contract from blotter.tickers import load_tickers_into_dataframe from blotter.upload import upload_dataframe logger = getLogger(__name__) PollingID = NewType("PollingID", str) """A unique ID for market data polling.""" @dataclass(frozen=True) class _PollingJob: """ Metadata about a market data polling job which can be serialized, so that it can be resumed even across server restarts. """ serialized_contracts: List[Dict[str, Any]] """One or more `ib_insync.Contract`s serialized into dictionary form.""" polling_interval: timedelta """How often the polling should be performed."""
import struct from typing import ( Any, List, Type, Tuple, Union, TypeVar, Optional, Callable, NewType, ) P = TypeVar("P", bound="BasePacket") BOOL = NewType("BOOL", bool) INT8 = NewType("INT8", int) UINT8 = NewType("UINT8", int) INT16 = NewType("INT16", int) UINT16 = NewType("UINT16", int) INT32 = NewType("INT32", int) UINT32 = NewType("UINT32", int) INT64 = NewType("INT64", int) UINT64 = NewType("UINT64", int) FLOAT = NewType("FLOAT", float) DOUBLE = NewType("DOUBLE", float) BYTE = NewType("BYTE", bytes) BYTES = NewType("BYTES", bytes) STRING = NewType("STRING", str)
"""RPC types.""" from typing import Any, NamedTuple, NewType, Optional, Union from typing_extensions import Literal, TypedDict # noqa: F401 from solana.publickey import PublicKey from .commitment import Commitment, Max URI = NewType("URI", str) """Type for endpoint URI.""" RPCMethod = NewType("RPCMethod", str) """Type for RPC method.""" class RPCError(TypedDict): """RPC error.""" code: int """HTTP status code.""" message: str """Error message.""" class RPCResponse(TypedDict, total=False): """RPC Response.""" error: Union[RPCError, str] """RPC error.""" id: int
import random import warnings from dataclasses import dataclass from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import torch from torch.nn.utils.rnn import pad_sequence from ..tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTrainedTokenizerBase InputDataClass = NewType("InputDataClass", Any) """ A DataCollator is a function that takes a list of samples from a Dataset and collate them into a batch, as a dictionary of Tensors. """ DataCollator = NewType( "DataCollator", Callable[[List[InputDataClass]], Dict[str, torch.Tensor]]) def default_data_collator( features: List[InputDataClass]) -> Dict[str, torch.Tensor]: """ Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named: - ``label``: handles a single value (int or float) per object - ``label_ids``: handles a list of values per object Does not do any additional preprocessing: property names of the input object will be used as corresponding inputs to the model. See glue and ner for example of how it's useful. """
from typing import NewType, List, Tuple import torch TorchTensor = NewType("TorchTensor", torch.Tensor) TaggedSentence = NewType("TaggedSentence", List[Tuple])
from tgficbot import db from typing import NewType State = NewType('State', int) Empty = State(0) AddingAChannel = State(0xa31b2f1f) SelectingAChannelToFind = State(0x72db58bd) FindingInAChannel = State(0xfc757945) def onstate(state: State): def decorate(func): async def wrapper(event): user = await event.get_chat() if db.get_user_state(user) == state: return await func(event) return return wrapper return decorate
from datetime import datetime from typing import Dict, List, NewType, Optional, Set, Any, Tuple import aiohttp from galaxy.api.errors import (AccessDenied, AuthenticationRequired, BackendError, BackendNotAvailable, BackendTimeout, NetworkError, UnknownBackendResponse) from galaxy.api.types import Achievement, SubscriptionGame, Subscription from galaxy.http import HttpClient from yarl import URL logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) MasterTitleId = NewType("MasterTitleId", str) AchievementSet = NewType("AchievementSet", str) OfferId = NewType("OfferId", str) Timestamp = NewType("Timestamp", int) Json = Dict[str, Any] # helper alias for general purpose SubscriptionDetails = namedtuple('SubscriptionDetails', ['tier', 'end_time']) class CookieJar(aiohttp.CookieJar): def __init__(self): super().__init__() self._cookies_updated_callback = None def set_cookies_updated_callback(self, callback): self._cookies_updated_callback = callback
from enum import Enum from typing import Dict, List, NamedTuple, NewType, Optional, Tuple, Union from eth_utils.typing import ChecksumAddress from rotkehlchen.fval import FVal T_BinaryEthAddress = bytes BinaryEthAddress = NewType('BinaryEthAddress', T_BinaryEthAddress) T_Timestamp = int Timestamp = NewType('Timestamp', T_Timestamp) T_ApiKey = str ApiKey = NewType('ApiKey', T_ApiKey) T_ApiSecret = bytes ApiSecret = NewType('ApiSecret', T_ApiSecret) T_B64EncodedBytes = bytes B64EncodedBytes = NewType('B64EncodedBytes', T_B64EncodedBytes) T_B64EncodedString = str B64EncodedString = NewType('B64EncodedString', T_B64EncodedString) T_HexColorCode = str HexColorCode = NewType('HexColorCode', T_HexColorCode) class ApiCredentials(NamedTuple): """Represents Credentials for various APIs. Exchanges, Premium e.t.c.
def parking_ticket(self, val): self.parking_ticket = val class ParkingTicket: def __init__(self, start_time): self.id = None self.start_time = start_time self.end_time = None self.amount = None def status(self): pass Receipt = NewType('Receipt', ParkingTicket) class Payment(ABC): def __init__(self, details): self.type = None self.details = None @abstractmethod def pay(self): None class CreditCard(Payment): def pay(self): pass
from typing import NewType """simplest test case """ StringLxWtMXSJ = NewType("StringLxWtMXSJ", str)
"signatures" / c.Bytes(64)[V1_SIGNATURE_SLOTS], "code" / c.Bytes(c.this.code_length), c.Terminated, "embedded_onev2" / c.RestreamData(c.this.code, c.Optional(FirmwareOneV2)), ) # fmt: on class FirmwareFormat(Enum): TREZOR_ONE = 1 TREZOR_T = 2 TREZOR_ONE_V2 = 3 FirmwareType = NewType("FirmwareType", c.Container) ParsedFirmware = Tuple[FirmwareFormat, FirmwareType] def parse(data: bytes) -> ParsedFirmware: if data[:4] == b"TRZR": version = FirmwareFormat.TREZOR_ONE cls = FirmwareOne elif data[:4] == b"TRZV": version = FirmwareFormat.TREZOR_T cls = Firmware elif data[:4] == b"TRZF": version = FirmwareFormat.TREZOR_ONE_V2 cls = FirmwareOneV2 else: raise ValueError("Unrecognized firmware image type")
from dataclasses import dataclass, field, replace from enum import Enum from typing import NewType, TypeVar, Generic, Dict, Optional from decimal import Decimal, getcontext from raiden_contracts.constants import CONTRACTS_VERSION from raiden_installer import network_settings, default_settings Eth_T = TypeVar("Eth_T", int, Decimal, float, str, "Wei") Token_T = TypeVar("Token_T") TokenTicker = NewType("TokenTicker", str) class TokenError(Exception): pass class Wei(int): pass @dataclass class Currency: ticker: str wei_ticker: str decimals: int = 18 def format_value(self, wei_amount: Decimal): if wei_amount == 0: ticker = self.ticker value = wei_amount
from enum import IntEnum import numpy as np from typing import Tuple, List, Dict, NewType #The Coordinates type stores the positions of the cells Coordinates = NewType('Coordinatess', Tuple[int, int]) #The Pedestrian type stores the information which a pedestrian has (position and speed) Pedestrian = NewType('Pedestrian', Tuple[Coordinates, float]) class CellType(IntEnum): ''' This is an enum containing the different states a cell in the grid can be ''' EMPTY = 0 OBSTACLE = 2 TARGET = 3 class Grid: def __init__(self, rows: int, columns: int, pedestrians: List[Pedestrian], obstacles: List[Coordinates], target: Coordinates): """ :param rows: How many rows is the grid going to have :param columns: How many columns is the grid going to have :param pedestrians: A List filled with all the pedestrians :param obstacles: A List filled with the positions of all the obstacles :param target: The position of the target cell """ self.rows = rows
from uuid import uuid4 from typing import NewType UUID = NewType('UUID', str) def gen_uuid() -> UUID: return UUID(str(uuid4()))