Exemplo n.º 1
0
import numpy as np
import pandas as pd
import seaborn as sns

from subject import Subject, load_subjects
from pathlib import Path
from typing import List, NewType
import datetime

ROOT_DIR = Path(f"{Path.home()}/data/ds000030_R1.0.5/derivatives/freesurfer/")
LUT_PATH = ROOT_DIR.joinpath('FreeSurferColorLUT.txt')

CTX_SUP_FRONTAL = 'ctx-lh-superiorfrontal'
LEFT_THALAMUS = 'Left-Thalamus-Proper'

BoudingBox2D = NewType('BoundingBox2D', ((float, float), (float, float)))
BoudingBox3D = NewType('BoundingBox3D',
                       ((float, float, float), (float, float, float)))

# This bounding box is the biggest bounding box
# that encompesses the structures below in all subjects.
# Se `bouding_box_statistics` for details.

BOUNDING_BOXES = {
    'ctx-lh-superiorfrontal': ((102, 30, 70), (173, 172, 221)),
    'Left-Amygdala': ((134, 100, 107), (167, 196, 160))
}


class FreeSurferLUT:
    """
Exemplo n.º 2
0
from typing import Dict, List, NewType, Any, Tuple

from proxies.assignation_proxy import AssignationProxy

ProxyAssignationByHashType = NewType('ProxyAssignationByHashType',
                                     Dict[str, List[AssignationProxy]])
Exemplo n.º 3
0
import re
from typing import NewType, List, Dict, NamedTuple

import pybtex.database as bibtex
from pybtex.database.input.bibtex import Parser as BibParser

SEMAPI_ID_FIELD = "semapi_id"
ABSTRACT_FIELD = "_abstract"

Person = bibtex.Person

PaperId = NewType("PaperId", str)



class Paper(object):

    def __init__(self,
                 fields: Dict,
                 authors: List[Person],
                 id: PaperId,
                 type_="article",
                 bibtex_id=None):
        self.fields = fields
        self.authors = authors
        self.type_ = type_
        self.id = id or bibtex_id
        self.bibtex_id = bibtex_id


    def __getattr__(self, name):
Exemplo n.º 4
0
import os
from typing import List, Tuple, NewType
from random import shuffle
from collections import namedtuple
import numpy as np
import torch
from torch.utils.data import Dataset
from ..common.mapper import Catalogue, concept2index, Concept
from ..datagen.convert2th import EncodedExample
from .builder import HyperparemetersSmtagModel
from ..common.progress import progress
from ..common.utils import tokenize, cd
from .. import config

# symbolic class for 3D Tensor in the Batch x Channel x Length format
BxCxL = NewType('BxCxL', torch.Tensor)

# symbolic class for 2D ByteTensors in Batch x Length format
BxL = NewType('BxL', torch.Tensor)

# items return by __get_item__() from Datasets
Item = namedtuple('Item',
                  ['text', 'provenance', 'input', 'output', 'target_class'])

# minibatches returned after collating a list of Item()
Minibatch = namedtuple(
    'Minibatch', ['text', 'provenance', 'input', 'output', 'target_class'])


class Data4th(Dataset):
    def __init__(self, hp: HyperparemetersSmtagModel, subdir_list: List[str]):
Exemplo n.º 5
0
import numpy as np

from numpy.linalg import inv

from typing import Tuple, NewType

Dim = NewType("Dim", Tuple[int, int])


def white_var(X: np.ndarray, e: np.ndarray, *var_args) -> np.ndarray:

    inverse = inv(X.T @ X)

    # construct diagonal array
    omega = np.diag(np.diag(e @ e.T))

    var_matrix = X.T @ omega @ X

    return inverse @ var_matrix @ inverse


# TODO: The two white can be abstracted


def white_var_2sls(W: np.ndarray, Z: np.ndarray,
                   e: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:

    N_T, K = W.shape

    omega = np.diag(np.diag(e @ e.T))
    S_hat = (Z.T @ omega @ Z) / N_T
Exemplo n.º 6
0
from contextlib import contextmanager
import logging
from typing import Generator, List, NewType, Optional, Tuple, Union

from psycopg2 import connect as psycopg2_connect, errorcodes, ProgrammingError
from psycopg2.extensions import connection as Connection, cursor as Cursor
from psycopg2.extras import NamedTupleCursor

from .common import Collect, Password, Result, State, Unset


LOG = logging.getLogger(__name__)

# Type alias for external callers, who need not be aware of the internal structure when chaining
# calls (e.g. get_user/create_user -> reset_password).
Role = NewType("Role", Tuple[str, bool])

_ROLE_SELECT = "SELECT rolname, rolcanlogin FROM pg_roles"


def _format(sql: str, *literals: str) -> str:
    # Psycopg2 won't format values normally enclosed in double quotes, so handle these ourselves.
    if any('"' in lit for lit in literals):
        raise ValueError("Double quotes forbidden in identifiers")
    params = ('"{}"'.format(lit) for lit in literals)
    return sql.format(*params)


def connect(host: str, db: Optional[str] = None) -> Connection:
    """
    Create a PostgreSQL connection using Psycopg2 and namedtuple cursors.
Exemplo n.º 7
0
# DATAGERRY - OpenSource Enterprise CMDB
# Copyright (C) 2019 NETHINKS GmbH
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
from typing import NewType, List

Query = NewType('Query', dict)
Pipeline = NewType('Pipeline', List[dict])
Exemplo n.º 8
0
from org.pyut.ogl.OglAssociation import OglAssociation
from org.pyut.ogl.OglAssociation import CENTER
from org.pyut.ogl.OglAssociation import DEST_CARD
from org.pyut.ogl.OglAssociation import SRC_CARD

from org.pyut.ogl.sd.OglSDInstance import OglSDInstance

from org.pyut.model.PyutStereotype import getPyutStereotype
from org.pyut.ogl.OglLinkFactory import getOglLinkFactory
from org.pyut.ogl.sd.OglSDMessage import OglSDMessage
from org.pyut.persistence.converters.PyutXmlConstants import PyutXmlConstants

from org.pyut.ui.UmlFrame import UmlFrame

OglObjects     = NewType('OglObjects',     Dict[int, OglObject])
OglClasses     = NewType('OglClasses',     Dict[int, OglClass])
OglNotes       = NewType('OglNotes',       Dict[int, OglNote])
OglActors      = NewType('OglActors',      Dict[int, OglActor])
OglUseCases    = NewType('OglUseCases',    Dict[int, OglUseCase])
OglSDInstances = NewType('OglSDInstances', Dict[int, OglSDInstance])
OglSDMessages  = NewType('OglSDMessages',  Dict[int, OglSDMessage])
PyutMethods    = NewType('PyutMethods',    List[PyutMethod])
PyutFields     = NewType('PyutFields',     List[PyutField])
ControlPoints  = NewType('ControlPoints',  List[ControlPoint])
Links          = NewType('Links',          Union[OglLink, OglSDInstance])
OglLinks       = NewType('OglLinks',       List[Links])


class MiniDomToOgl:
Exemplo n.º 9
0
from typing import List, Optional, NewType
import ecdsa  # type: ignore
import hashlib
import secrets

PublicKey = NewType('PublicKey', bytes)
Signature = NewType('Signature', bytes)
BlockHash = NewType('BlockHash', bytes)  # This will be the hash of a block
TxID = NewType("TxID", bytes)  # this will be a hash of a transaction

GENESIS_BLOCK_PREV = BlockHash(
    b"Genesis"
)  # these are the bytes written as the prev_block_hash of the 1st block.


class Transaction:
    """Represents a transaction that moves a single coin
    A transaction with no source creates money. It will only be created by the bank."""
    def __init__(self, output: PublicKey, input: Optional[TxID],
                 signature: Signature) -> None:
        self.output: PublicKey = output  # DO NOT change these field names.
        self.input: Optional[TxID] = input  # DO NOT change these field names.
        self.signature: Signature = signature  # DO NOT change these field names.

    def get_txid(self) -> TxID:
        """Returns the identifier of this transaction. This is the sha256 of the transaction contents."""
        raise NotImplementedError()


class Block:
    """This class represents a block."""
Exemplo n.º 10
0
from PyQt5.QtWidgets import QWidget, QGridLayout, QLineEdit, QPushButton, QLabel, \
    QComboBox, QMessageBox
from typing import NewType, List
from utilities import open_file_dialogue
from widgets.formatting import HorizontalLineWidget
from widgets.warning import WarningMessage


ConverterWidget = NewType('ConverterWidget', QWidget)


class ELANFileField(QWidget):
    def __init__(self, parent: ConverterWidget) -> None:
        super().__init__()
        self.parent = parent
        self.layout = QGridLayout()
        self.field = QLineEdit()
        self.init_ui()

    def init_ui(self) -> None:
        self.field.setReadOnly(True)
        self.field.setText('Load an ELAN (*.eaf) file.')
        self.layout.addWidget(self.field, 0, 0, 1, 7)
        load_button = QPushButton('Load')
        load_button.clicked.connect(self.on_click_load)
        self.layout.addWidget(load_button, 0, 7, 1, 1)
        self.setLayout(self.layout)

    def on_click_load(self) -> None:
        file_name = open_file_dialogue()
        if file_name:
Exemplo n.º 11
0
The schemas contained in this file define the stable API between kubernetes and
the special agent.
The schemas should not be affected by different kubernetes server or client versions.

This file should not contain any code and should not import from anywhere
except the python standard library or pydantic.
"""

import enum
from typing import Dict, List, Literal, Mapping, NewType, Optional, Protocol, Sequence, Union

from pydantic import BaseModel
from pydantic.class_validators import validator
from pydantic.fields import Field

PodUID = NewType("PodUID", str)
LabelName = NewType("LabelName", str)
LabelValue = NewType("LabelValue", str)


class Label(BaseModel):
    name: LabelName
    value: LabelValue


Labels = Mapping[LabelName, Label]
Timestamp = NewType("Timestamp", float)

# This information is from the one-page API overview v1.22
# Restart policy for all containers within the pod. Default to Always. More info:
RestartPolicy = Literal["Always", "OnFailure", "Never"]
Exemplo n.º 12
0
Arquivo: type.py Projeto: MrMeta/yui
    'SubteamID',
    'SubteamPrefs',
    'TeamID',
    'Ts',
    'UnixTimestamp',
    'UnknownChannel',
    'UnknownUser',
    'User',
    'UserID',
    'UserProfile',
    'cast',
    'is_container',
)

#: :type:`type` User ID type. It must start with 'U'.
UserID = NewType('UserID', str)

#: :type:`type` Public Channel ID type. It must start with 'C'.
PublicChannelID = NewType('PublicChannelID', str)

#: :type:`type` IM(as known as Direct Message) Channel ID type.
#: It must start with 'D'.
DirectMessageChannelID = NewType('DirectMessageChannelID', str)

#: :type:`type` Group(as known as Private Channel) ID type.
#: It must start with 'G'.
PrivateChannelID = NewType('PrivateChannelID', str)

ChannelID = Union[PublicChannelID, DirectMessageChannelID, PrivateChannelID, ]

#: :type:`type` File ID type. It must start with 'F'.
Exemplo n.º 13
0
import abc
import io
from typing import Callable, NamedTuple, NewType, Optional

Notice = NewType("Notice", str)


class SavesGateway(abc.ABC):
    @abc.abstractmethod
    def fetch_save(self, player_id: str) -> Optional[io.BytesIO]:
        ...

    @abc.abstractmethod
    def update_save(self, player_id: str, save: io.BytesIO) -> None:
        ...


class GameEngine(abc.ABC):
    @abc.abstractmethod
    def resume(self, save: io.BytesIO) -> None:
        ...

    @abc.abstractmethod
    def start(self) -> str:
        ...

    @abc.abstractmethod
    def do_command(self, command: str) -> str:
        ...

    @abc.abstractmethod
Exemplo n.º 14
0
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import json
import random
from math import ceil
from typing import NewType, Any

from logs_ingest import dynatrace_client

log_message = "WALTHAM, Mass.--(BUSINESS WIRE)-- Software intelligence company Dynatrace (NYSE: DT) announced today its entry into the cloud application security market with the addition of a new module to its industry-leading Software Intelligence Platform. The Dynatrace® Application Security Module provides continuous runtime application self-protection (RASP) capabilities for applications in production as well as preproduction and is optimized for Kubernetes architectures and DevSecOps approaches. This module inherits the automation, AI, scalability, and enterprise-grade robustness of the Dynatrace® Software Intelligence Platform and extends it to modern cloud RASP use cases. Dynatrace customers can launch this module with the flip of a switch, empowering the world’s leading organizations currently using the Dynatrace platform to immediately increase security coverage and precision.;"

request_body_len_max = len(log_message.encode("UTF-8")) * 3 + 20

MonkeyPatchFixture = NewType("MonkeyPatchFixture", Any)


def create_log_entry_with_random_len_msg():
    random_len = random.randint(1, len(log_message))
    random_len_str = log_message[0:random_len]

    return {
        'content': random_len_str,
        'cloud.provider': 'AWS',
        'severity': 'INFO'
    }


def test_prepare_serialized_batches(monkeypatch: MonkeyPatchFixture):
    monkeypatch.setenv("DYNATRACE_LOG_INGEST_REQUEST_MAX_SIZE",
Exemplo n.º 15
0
import copy
import os

import cv2
import numpy as np
import torch
import torchvision
import torchvision.transforms.functional as F
from typing import NewType, Tuple
import yaml

from modules.posenet import PoseNet
from modules.utils import Config

VideoRead = NewType('VideoRead', cv2.VideoCapture)
VideoWrite = NewType('VideoWrite', cv2.VideoWriter)


def main(cfg):
    cfg = Config(cfg)

    print("Loading '{}'".format(cfg.input))

    # Load the video
    cap, origin_fps, frames, width, height = load_video(cfg.input)
    writer = video_writer(cfg.output_path, origin_fps, width, height)

    device = torch.device(
        f"cuda:{cfg.gpu_id}" if torch.cuda.is_available() else "cpu")

    # Load model
Exemplo n.º 16
0
from typing import NewType

JournalDBCheckpoint = NewType('JournalDBCheckpoint', int)
Exemplo n.º 17
0
import struct
import subprocess
from enum import Enum, auto

from dataclasses import dataclass, field
from pathlib import Path
from typing import (
    Mapping,
    NewType,
    Optional,
    Sequence,
)

logger = logging.getLogger(__name__)

Environment = NewType("Environment", Mapping[str, str])


class Libc(Enum):
    glibc = auto()
    musl = auto()


@dataclass
class BuilderConfig:
    libc: Libc
    concurrent_jobs: int = None


class StavesError(Exception):
    pass
Exemplo n.º 18
0
from collections.abc import Collection, Mapping
from dataclasses import dataclass
from typing import NewType

from apischema import deserialize


@dataclass
class Foo:
    bar: str


MyInt = NewType("MyInt", int)

assert deserialize(Foo, {"bar": "bar"}) == Foo("bar")
assert deserialize(MyInt, 0) == MyInt(0) == 0
assert deserialize(Mapping[str, Collection[Foo]], {"key": [{"bar": "42"}]}) == {
    "key": (Foo("42"),)
}
Exemplo n.º 19
0
# 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/.

import csv
import re
from datetime import datetime
from typing import Dict, Iterator, List, NewType, Optional

import tenacity
from dateutil.relativedelta import relativedelta
from libmozdata.bugzilla import Bugzilla
from tqdm import tqdm

from bugbug import db, utils

BugDict = NewType("BugDict", dict)

BUGS_DB = "data/bugs.json"
db.register(
    BUGS_DB,
    "https://community-tc.services.mozilla.com/api/index/v1/task/project.bugbug.data_bugs.latest/artifacts/public/bugs.json.zst",
    6,
)

PRODUCTS = (
    "Add-on SDK",
    "Android Background Services",
    "Core",
    "Core Graveyard",
    "DevTools",
    "DevTools Graveyard",
Exemplo n.º 20
0
from .base.entity import (EntityTypeId, Entity, EntityLifeCycle)
from .event import EcsManagerWithEvents, EventManager, Event
from .component import ComponentManager

# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------


@enum.unique
class EntityEventType(enum.Enum):
    COMPONENT_ATTACH = enum.auto()
    COMPONENT_DETACH = enum.auto()


EntityOrNull = NewType('EntityOrNull', Union[Entity, Null])

# -----------------------------------------------------------------------------
# Code
# -----------------------------------------------------------------------------


class EntityEvent(Event,
                  name_dotted='veredi.game.ecs.entity.event',
                  name_string='entity'):
    ...


class EntityLifeEvent(EntityEvent,
                      name_dotted='veredi.gamececs.entity.event.life',
                      name_string='entity.life'):
Exemplo n.º 21
0
from dataclasses import dataclass, field
from typing import NewType

from pytest import raises

from apischema import ValidationError, deserialize, schema, serialize

Tag = NewType("Tag", str)
schema(min_len=3, pattern=r"^\w*$", examples=["available", "EMEA"])(Tag)


@dataclass
class Resource:
    id: int
    tags: list[Tag] = field(
        default_factory=list,
        metadata=schema(description="regroup multiple resources",
                        max_items=3,
                        unique=True),
    )


with raises(ValidationError) as err:  # pytest check exception is raised
    deserialize(Resource, {
        "id": 42,
        "tags": ["tag", "duplicate", "duplicate", "bad&", "_"]
    })
assert serialize(err.value) == [
    {
        "loc": ["tags"],
        "err":
from typing import TYPE_CHECKING, NewType, Optional, Sequence, Type

from rest_framework.authentication import BaseAuthentication, TokenAuthentication

from rest_registration.exceptions import AuthTokenNotFound, AuthTokenNotRevoked

AuthToken = NewType('AuthToken', str)

if TYPE_CHECKING:
    from django.contrib.auth.base_user import AbstractBaseUser


class AbstractAuthTokenManager:
    def get_authentication_class(self) -> Type[BaseAuthentication]:
        """
        Return authentication class which is able to parse the token.
        This is used to ensure that the class is added
        in ``REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES']`` setting.
        """
        raise NotImplementedError()

    def get_app_names(self) -> Sequence[str]:
        """
        Return the Django app names which need to be installed so
        this token manager class works properly.

        Overriding this method is not required but recommended as it provides
        additional check during the Django startup.
        """
        return []
Exemplo n.º 23
0
class Domain(
    MultiAgent, Parallel, Environment, Events, History, PartiallyObservable, Rewards
):
    """This is the highest level domain class (inheriting top-level class for each mandatory domain characteristic).

    This helper class can be used as the main base class for domains.

    Typical use:
    ```python
    class D(Domain, ...)
    ```

    with "..." replaced when needed by a number of classes from following domain characteristics (the ones in
    parentheses are optional):

    - **agent**: MultiAgent -> SingleAgent
    - **concurrency**: Parallel -> Sequential
    - **(constraints)**: Constrained
    - **dynamics**: Environment -> Simulation -> UncertainTransitions -> EnumerableTransitions
      -> DeterministicTransitions
    - **events**: Events -> Actions -> UnrestrictedActions
    - **(goals)**: Goals
    - **(initialization)**: Initializable -> UncertainInitialized -> DeterministicInitialized
    - **memory**: History -> FiniteHistory -> Markovian -> Memoryless
    - **observability**: PartiallyObservable -> TransformedObservable -> FullyObservable
    - **(renderability)**: Renderable
    - **value**: Rewards -> PositiveCosts
    """

    T_state = NewType("T_state", object)
    T_observation = NewType("T_observation", object)
    T_event = NewType("T_event", object)
    T_value = NewType("T_value", object)
    T_predicate = NewType("T_predicate", object)
    T_info = NewType("T_info", object)

    @classmethod
    def solve_with(
        cls,
        solver: Solver,
        domain_factory: Optional[Callable[[], Domain]] = None,
        load_path: Optional[str] = None,
    ) -> Solver:
        """Solve the domain with a new or loaded solver and return it auto-cast to the level of the domain.

        By default, #Solver.check_domain() provides some boilerplate code and internally
        calls #Solver._check_domain_additional() (which returns True by default but can be overridden  to define
        specific checks in addition to the "domain requirements"). The boilerplate code automatically checks whether all
        domain requirements are met.

        # Parameters
        solver: The solver.
        domain_factory: A callable with no argument returning the domain to solve (factory is the domain class if None).
        load_path: The path to restore the solver state from (if None, the solving process will be launched instead).

        # Returns
        The new solver (auto-cast to the level of the domain).
        """
        if domain_factory is None:
            domain_factory = cls
        if load_path is not None:

            # TODO: avoid repeating this code somehow (identical in solver.solve(...))? Is factory necessary (vs cls)?
            def cast_domain_factory():
                domain = domain_factory()
                autocast_all(domain, domain, solver.T_domain)
                return domain

            solver.load(load_path, cast_domain_factory)
        else:
            solver.solve(domain_factory)
        autocast_all(solver, solver.T_domain, cls)
        return solver
Exemplo n.º 24
0
"""
Rank class for representing taxonomic levels or ranks.

"""

from enum import Enum
from typing import List, Iterator, NewType, Dict, Set

from recentrifuge.config import Id

# Type annotations
# pylint: disable=invalid-name
# Ranks and Levels are devised to be one the inverse of the other
Ranks = NewType('Ranks', Dict[Id, 'Rank'])  # Rank of each Id
TaxLevels = NewType('TaxLevels', Dict['Rank', Set[Id]])  # TaxIds for rank
# pylint: enable=invalid-name


class classproperty(object):  # pylint: disable=invalid-name
    """Decorator to emulate a class property."""

    # pylint: disable=too-few-public-methods
    def __init__(self, fget):
        self.fget = fget

    def __get__(self, owner_self, owner_cls):
        return self.fget(owner_cls)


class UnsupportedTaxLevelError(Exception):
    """Raised if a unsupported tax level is found."""
Exemplo n.º 25
0
from typing import Optional, Union, Dict, List, NewType

import torch

from dh_segment_torch.config.registrable import Registrable
from dh_segment_torch.metrics.utils import (
    batch_multilabel_confusion_matrix,
    nanaverage,
)
from dh_segment_torch.utils.ops import cut_with_padding
from dh_segment_torch.utils.ops import detach_and_move_tensors

logger = Logger(__name__)

MetricType = NewType(
    "Metric", Union[float, List[float], Dict[str, float], Dict[str,
                                                               List[float]]])


class Metric(Registrable):
    def __init__(
        self,
        num_classes: Optional[int] = None,
        multilabel: bool = False,
        ignore_padding: bool = False,
        margin: int = 0,
        device: Optional[str] = "cpu",
    ):
        super().__init__()
        self.num_classes = num_classes
        self.multilabel = multilabel
Exemplo n.º 26
0
from typing import NewType

Foo = NewType("Foo", str)
from typing import NewType

Baz = NewType("Baz", bool)
from typing import TypedDict, Optional

class ObjectOfBazX101YId8(TypedDict):
    ripslip: Optional[Baz]
from typing import List, NewType
"""array of strings is all...
"""
UnorderedSetOfFooz1UBFn8B = NewType("UnorderedSetOfFooz1UBFn8B", List[Foo])
from typing import NewType

Bar = NewType("Bar", int)
from typing import NewType, Tuple

BunchaNumbers = NewType("BunchaNumbers", Tuple[Bar])
from typing import NewType, Union

OneOfStuff = NewType("OneOfStuff", Union[UnorderedSetOfFooz1UBFn8B, BunchaNumbers])
from typing import NewType, Union
"""Generated! Represents an alias to any of the provided schemas
"""
AnyOfFooFooObjectOfBazX101YId8OneOfStuffBar = NewType("AnyOfFooFooObjectOfBazX101YId8OneOfStuffBar", Union[Foo, ObjectOfBazX101YId8, OneOfStuff, Bar])
Exemplo n.º 27
0
from pip._internal.exceptions import (
    ConfigurationError,
    ConfigurationFileCouldNotBeLoaded,
)
from pip._internal.utils import appdirs
from pip._internal.utils.compat import WINDOWS, expanduser
from pip._internal.utils.misc import ensure_dir, enum
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
from pip._vendor.six.moves import configparser

if MYPY_CHECK_RUNNING:
    from typing import (Any, Dict, Iterable, List, NewType, Optional, Tuple)

    RawConfigParser = configparser.RawConfigParser  # Shorthand
    Kind = NewType("Kind", str)

logger = logging.getLogger(__name__)


# NOTE: Maybe use the optionx attribute to normalize keynames.
def _normalize_name(name):
    # type: (str) -> str
    """Make a name consistent regardless of source (environment or file)
    """
    name = name.lower().replace('_', '-')
    if name.startswith('--'):
        name = name[2:]  # only prefer long opts
    return name

Exemplo n.º 28
0
from typing import NewType, Protocol


class Id1(Protocol):
    code: int


UserId1 = NewType('UserId1', <warning descr="NewType cannot be used with protocol classes">Id1</warning>)


class Id2:
    code: int


UserId2 = NewType('UserId2', Id2)
Exemplo n.º 29
0
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Generates KMN rules for all syllabics sequences with the
[T_LONG_DOT] and [T_W_DOT] keys.

This script requires Python 3.6+.
"""

import csv
from distutils.util import strtobool
from pprint import pprint
from typing import Dict, List, NamedTuple, NewType, Optional
from unicodedata import normalize

Syllabic = NewType("Syllabic", str)


class Index(NamedTuple):
    consonant: Optional[str]
    vowel: str
    has_w: bool
    is_long: bool

    @property
    def lacking_w_diacritic(self):
        return not self.has_w

    @property
    def lacking_long_diacritic(self):
        return not self.is_long
Exemplo n.º 30
0
Interface to CLSmith binaries
"""
from collections import namedtuple

import logging
import re
from phd.lib.labm8 import fs
from subprocess import PIPE, Popen
from tempfile import NamedTemporaryFile
from time import time
from typing import List, NewType, Tuple

from experimental import dsmith
from experimental.dsmith import Colors

runtime_t = NewType('runtime_t', float)
status_t = NewType('status_t', int)
return_t = namedtuple('return_t', ['runtime', 'status', 'stdout', 'stderr'])

# build paths
exec_path = dsmith.root_path("third_party", "clsmith", "build", "CLSmith")
cl_launcher_path = dsmith.root_path("third_party", "clsmith", "build",
                                    "cl_launcher")
include_path = dsmith.root_path("third_party", "clsmith", "runtime")

# sanity checks
assert fs.isexe(exec_path)
assert fs.isexe(cl_launcher_path)
assert fs.isfile(fs.path(include_path, "CLSmith.h"))