Python typing.Union() Examples

The following are 30 code examples of typing.Union(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: file_utils.py    From cmrc2019 with Creative Commons Attribution Share Alike 4.0 International 9 votes vote down vote up
def filename_to_url(filename: str, cache_dir: Union[str, Path] = None) -> Tuple[str, str]:
    """
    Return the url and etag (which may be ``None``) stored for `filename`.
    Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
    """
    if cache_dir is None:
        cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
    if isinstance(cache_dir, Path):
        cache_dir = str(cache_dir)

    cache_path = os.path.join(cache_dir, filename)
    if not os.path.exists(cache_path):
        raise FileNotFoundError("file {} not found".format(cache_path))

    meta_path = cache_path + '.json'
    if not os.path.exists(meta_path):
        raise FileNotFoundError("file {} not found".format(meta_path))

    with open(meta_path) as meta_file:
        metadata = json.load(meta_file)
    url = metadata['url']
    etag = metadata['etag']

    return url, etag 
Example #2
Source File: auth.py    From hydrus with MIT License 8 votes vote down vote up
def check_authentication_response() -> Union[Response, None]:
    """
    Return the response as per the authentication requirements.
    """
    if get_authentication():
        if get_token():
            token = check_token(request, get_session())
            if not token:
                if request.authorization is None:
                    return failed_authentication(False)
                else:
                    return verify_user()
        elif request.authorization is None:
            return failed_authentication(False)
        else:
            return verify_user()
    else:
        return None 
Example #3
Source File: args_format_builder.py    From clikit with MIT License 8 votes vote down vote up
def get_argument(
        self, name, include_base=True
    ):  # type: (Union[str, int], bool) -> Argument
        if isinstance(name, int):
            arguments = list(self.get_arguments(include_base).values())

            if name >= len(arguments):
                raise NoSuchArgumentException(name)
        else:
            arguments = self.get_arguments(include_base)

            if name not in arguments:
                raise NoSuchArgumentException(name)

        return arguments[name] 
Example #4
Source File: event_dispatcher.py    From clikit with MIT License 7 votes vote down vote up
def get_listeners(
        self, event_name=None
    ):  # type: (str) -> Union[List[Callable], Dict[str, Callable]]
        if event_name is not None:
            if event_name not in self._listeners:
                return []

            if event_name not in self._sorted:
                self._sort_listeners(event_name)

            return self._sorted[event_name]

        for event_name, event_listeners in self._listeners.items():
            if event_name not in self._sorted:
                self._sort_listeners(event_name)

        return self._sorted 
Example #5
Source File: util.py    From cmus-osx with MIT License 7 votes vote down vote up
def throttle(interval: Union[float, int]):
    """Decorator ensures function that can only be called once every `s` seconds.
    """

    def decorate(fn: Callable) -> Callable:
        t = None

        def wrapped(*args, **kwargs):
            nonlocal t
            t_ = time()
            if t is None or t_ - t >= interval:
                result = fn(*args, **kwargs)
                t = time()
                return result

        return wrapped

    return decorate 
Example #6
Source File: state_preparation.py    From OpenFermion-Cirq with Apache License 2.0 7 votes vote down vote up
def _generic_gaussian_circuit(
        qubits: Sequence[cirq.Qid],
        quadratic_hamiltonian: QuadraticHamiltonian,
        occupied_orbitals: Optional[Sequence[int]],
        initial_state: Union[int, Sequence[int]]) -> cirq.OP_TREE:

    n_qubits = len(qubits)
    circuit_description, start_orbitals = gaussian_state_preparation_circuit(
            quadratic_hamiltonian, occupied_orbitals)

    if isinstance(initial_state, int):
        initially_occupied_orbitals = _occupied_orbitals(
                initial_state, n_qubits)
    else:
        initially_occupied_orbitals = initial_state  # type: ignore

    # Flip bits so that the correct starting orbitals are occupied
    yield (cirq.X(qubits[j]) for j in range(n_qubits)
           if (j in initially_occupied_orbitals) != (j in start_orbitals))

    yield _ops_from_givens_rotations_circuit_description(
            qubits, circuit_description) 
Example #7
Source File: zmirror.py    From zmirror with MIT License 6 votes vote down vote up
def try_get_cached_response(url, client_header=None):
    """
    尝试从本地缓存中取出响应
    :param url: real url with query string
    :type client_header: dict
    :rtype: Union[Response, None]
    """
    # Only use cache when client use GET
    if local_cache_enable and parse.method == 'GET' and cache.is_cached(url):
        if client_header is not None and 'if-modified-since' in client_header and \
                cache.is_unchanged(url, client_header.get('if-modified-since', None)):
            dbgprint('FileCacheHit-304', url)
            return generate_304_response()
        else:
            cached_info = cache.get_info(url)
            if cached_info.get('without_content', True):
                # 关于 without_content 的解释, 请看update_content_in_local_cache()函数
                return None
            # dbgprint('FileCacheHit-200')
            resp = cache.get_obj(url)
            assert isinstance(resp, Response)
            parse.set_extra_resp_header('x-zmirror-cache', 'FileHit')
            return resp
    else:
        return None 
Example #8
Source File: filters.py    From mutatest with MIT License 6 votes vote down vote up
def filter(  # type: ignore
        self,
        loc_idxs: Set[LocIndex],
        source_file: Union[str, Path],
        invert: bool = False,
        resolve_source: bool = True,
    ) -> Set[LocIndex]:
        """Filter based on coverage measured file.

        This adds the source_file argument to the filter abstract method because the coverage
        file holds multiple measured-files, and the ``LocIndex`` object does not have a source
        file attribute. The choice is that the coverage file can be set and read once for the
        class instance, and any valid measured file can be used in the filter.

        Args:
            loc_idxs: location index set of targets
            source_file: source file that is measured by the coverage file
            invert: flag for inverted filter using NOT
            resolve_source: flag for using resolved source_file vs. direct str, default True.
                This exists mostly for testing purposes to access mocked entries in the
                fake coverage files.

        Returns:
            Filtered set of location index set
        """
        measured_file = str(Path(source_file).resolve()) if resolve_source else str(source_file)

        covered_lines = self.coverage_data.lines(measured_file) or list()

        if invert:
            return {loc for loc in loc_idxs if loc.lineno not in covered_lines}
        return {loc for loc in loc_idxs if loc.lineno in covered_lines} 
Example #9
Source File: ini.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def load_ini_from_filepath(filepath: t.Union[str, 'pathlib.Path']) -> dict:
    config = ConfigParser()
    config.read(filepath)
    return {name: dict(section) for name, section in config.items()} 
Example #10
Source File: predicate.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def __init__(self, name: str = None, _path: t.Union[str, t.Iterable, None] = None):
        """
        :param name: (optional) A name for the Var instance. Variables
         in a formula may be equated using their names.
        :param _path: (optional) A technical argument, used for passing
         path tuple between Var constructors.
        """
        self._name = name
        if _path is None:
            self._path = ()
        elif is_iterable(_path):
            self._path = tuple(_path)
        elif isinstance(_path, str):
            self._path = tuple(_path.split('.')) 
Example #11
Source File: loaders.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def load_from_filepath(filepath: t.Union[str, Path]) -> t.Any:
    path = Path(filepath)
    loader = Loaders.guess_loader(path)
    return loader(path) 
Example #12
Source File: circuits.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def prepare_slater_determinant(qubits: List[cirq.Qid],
                               slater_determinant_matrix: np.ndarray,
                               clean_ryxxy: Optional[Union[bool, int]] = True):
    """
    High level interface to the real basis rotation circuit generator

    :param qubits: List of cirq.Qids denoting logical qubits
    :param slater_determinant_matrix: basis rotation matrix
    :param clean_ryxxy: Optional[True, 1, 2, 3, 4] for indicating an error
                        model of the Givens rotation.
    :return: generator for circuit
    """
    circuit_description = slater_determinant_preparation_circuit(slater_determinant_matrix)
    yield (cirq.X(qubits[j]) for j in range(slater_determinant_matrix.shape[0]))
    for parallel_ops in circuit_description:
        for op in parallel_ops:
            i, j, theta, phi = op
            if not np.isclose(phi, 0):  # testpragma: no cover
                raise ValueError("unitary must be real valued only")
            if clean_ryxxy is True or clean_ryxxy == 1:
                yield ryxxy(qubits[i], qubits[j], theta)
            elif clean_ryxxy == 2:
                yield ryxxy2(qubits[i], qubits[j], theta)
            elif clean_ryxxy == 3:
                yield ryxxy3(qubits[i], qubits[j], theta)
            elif clean_ryxxy == 4:
                yield ryxxy3(qubits[i], qubits[j], theta)
            else:
                raise ValueError("Invalide clean_ryxxy value") 
Example #13
Source File: state_preparation.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def _ops_from_givens_rotations_circuit_description(
        qubits: Sequence[cirq.Qid],
        circuit_description: Iterable[Iterable[
            Union[str, Tuple[int, int, float, float]]]]) -> cirq.OP_TREE:
    """Yield operations from a Givens rotations circuit obtained from
    OpenFermion.
    """
    for parallel_ops in circuit_description:
        for op in parallel_ops:
            if op == 'pht':
                yield cirq.X(qubits[-1])
            else:
                i, j, theta, phi = cast(Tuple[int, int, float, float], op)
                yield Ryxxy(theta).on(qubits[i], qubits[j])
                yield cirq.Z(qubits[j]) ** (phi / numpy.pi) 
Example #14
Source File: four_qubit_gates.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def _with_exponent(self,
                       exponent: Union[sympy.Symbol, float]
                       ) -> 'DoubleExcitationGate':
        return DoubleExcitationGate(exponent=exponent) 
Example #15
Source File: gradient_hf.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def rhf_func_generator(rhf_objective: RestrictedHartreeFockObjective,
                       initial_occ_vec: Optional[Union[None, np.ndarray]] = None,
                       get_opdm_func: Optional[bool] = False):
    """
    Generate the energy, gradient, and unitary functions

    :param rhf_objective: objective function object
    :param initial_occ_vec: (optional) vector for occupation numbers of the alpha-opdm
    :return: functions for unitary, energy, gradient (in that order)
    """
    if initial_occ_vec is None:
        initial_opdm = np.diag([1] * rhf_objective.nocc + [0] * rhf_objective.nvirt)
    else:
        initial_opdm = np.diag(initial_occ_vec)

    def energy(params):
        u = unitary(params)
        final_opdm_aa = u @ initial_opdm @ np.conjugate(u).T
        tenergy = rhf_objective.energy_from_opdm(final_opdm_aa)
        return tenergy

    def gradient(params):
        u = unitary(params)
        final_opdm_aa = u @ initial_opdm @ np.conjugate(u).T
        return rhf_objective.global_gradient_opdm(params, final_opdm_aa).real

    def unitary(params):
        kappa = rhf_params_to_matrix(params,
                                     len(rhf_objective.occ) + len(rhf_objective.virt),
                                     rhf_objective.occ, rhf_objective.virt)
        return sp.linalg.expm(kappa)

    def get_opdm(params):
        u = unitary(params)
        return u @ initial_opdm @ np.conjugate(u).T

    if get_opdm_func:
        return unitary, energy, gradient, get_opdm
    return unitary, energy, gradient 
Example #16
Source File: circuits.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def rhf_params_to_matrix(parameters: np.ndarray, num_qubits: int,
                         occ: Optional[Union[None, List[int]]]=None,
                         virt: Optional[Union[None, List[int]]]=None):
    """
    For restricted Hartree-Fock we have nocc * nvirt parameters.  These are provided
    as a list that is ordered by (virtuals) \times (occupied) where
    occupied is a set of indices corresponding to the occupied oribitals w.r.t the
    Lowdin basis and virtuals is a set of indices of the virutal orbitals w.r.t the
    Lowdin basis.  For example, for H4 we have 2 orbitals occupied and 2 virtuals

    occupied = [0, 1]  virtuals = [2, 3]

    parameters = [(v_{0}, o_{0}), (v_{0}, o_{1}), (v_{1}, o_{0}), (v_{1}, o_{1})]
               = [(2, 0), (2, 1), (3, 0), (3, 1)]

    You can think of the tuples of elements of the upper right triangle of the
    antihermitian matrix that specifies the c_{b, i} coefficients.

    coefficient matrix
    [[ c_{0, 0}, -c_{1, 0}, -c_{2, 0}, -c_{3, 0}],
     [ c_{1, 0},  c_{1, 1}, -c_{2, 1}, -c_{3, 1}],
     [ c_{2, 0},  c_{2, 1},  c_{2, 2}, -c_{3, 2}],
     [ c_{3, 0},  c_{3, 1},  c_{3, 2},  c_{3, 3}]]

    Since we are working with only non-redundant operators we know c_{i, i} = 0
    and any c_{i, j} where i and j are both in occupied or both in virtual = 0.
    """
    if occ is None:
        occ = range(num_qubits//2)
    if virt is None:
        virt = range(num_qubits // 2, num_qubits)

    # check that parameters are a real array
    if not np.allclose(parameters.imag, 0):
        raise ValueError("parameters input must be real valued")

    kappa = np.zeros((len(occ) + len(virt), len(occ) + len(virt)))
    for idx, (v, o) in enumerate(product(virt, occ)):
        kappa[v, o] = parameters[idx].real
        kappa[o, v] = -parameters[idx].real
    return kappa 
Example #17
Source File: letter_with_subscripts.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 letter: str,
                 *subscripts: Union[str, int]) -> None:
        self.letter = letter
        self.subscripts = subscripts
        super().__init__() 
Example #18
Source File: objective.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def value(self,
              circuit_output: Union[cirq.TrialResult,
                                    cirq.SimulationTrialResult,
                                    numpy.ndarray]
              ) -> float:
        """The evaluation function for a circuit output.

        A variational quantum algorithm will attempt to minimize this value over
        possible settings of the parameters.
        """ 
Example #19
Source File: state_preparation.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def _spin_symmetric_gaussian_circuit(
        qubits: Sequence[cirq.Qid],
        quadratic_hamiltonian: QuadraticHamiltonian,
        occupied_orbitals: Tuple[Sequence[int], Sequence[int]],
        initial_state: Union[int, Sequence[int]]) -> cirq.OP_TREE:

    n_qubits = len(qubits)

    if isinstance(initial_state, int):
        initially_occupied_orbitals = _occupied_orbitals(
                initial_state, n_qubits)
    else:
        initially_occupied_orbitals = initial_state  # type: ignore

    for spin_sector in range(2):
        circuit_description, start_orbitals = (
                gaussian_state_preparation_circuit(
                    quadratic_hamiltonian,
                    occupied_orbitals[spin_sector],
                    spin_sector=spin_sector)
        )

        def index_map(i):
            return i + spin_sector*(n_qubits // 2)
        spin_indices = [index_map(i) for i in range(n_qubits // 2)]
        spin_qubits = [qubits[i] for i in spin_indices]

        # Flip bits so that the correct starting orbitals are occupied
        yield (cirq.X(spin_qubits[j]) for j in range(n_qubits // 2)
               if (index_map(j) in initially_occupied_orbitals)
               != (index_map(j) in [index_map(k) for k in start_orbitals]))

        yield _ops_from_givens_rotations_circuit_description(
                spin_qubits, circuit_description) 
Example #20
Source File: predicate.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def all(self, cond: t.Union[Predicate, t.Iterable]) -> Predicate:
        """
        Checks if a condition is met by any element in a list,
        where a condition can also be a sequence (e.g. list).
        >>> var('f1').all(var('f2').exists())
        Matches::
            {'f1': [{'f2': 1}, {'f2': 1}]}
        >>> var('f1').all([1, 2, 3])
        # Match f1 that contains any element from [1, 2, 3]
        Matches::
            {'f1': [1, 2, 3, 4, 5]}

        :param cond: Either a Predicate that all elements have to match or
         a list which has to be contained in the tested element.
        """
        if callable(cond):
            def _cmp(value):
                return is_iterable(value) and all(cond(e) for e in value)

        else:
            def _cmp(value):
                return is_iterable(value) and all(e in value for e in cond)

        return self._build_predicate(
            lambda lhs, value: _cmp(lhs),
            Operation.ALL,
            (self._path, freeze(cond))
        )


# noinspection PyProtectedMember 
Example #21
Source File: predicate.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def any(self, cond: t.Union[Predicate, t.Iterable]) -> Predicate:
        """
        Checks if a condition is met by any element in a list,
        where a condition can also be a sequence (e.g. list).
        >>> var('f1').any(var('f2').exists())
        Matches::
            {'f1': [{'f2': 1}, {'f2': 0}]}
        >>> var('f1').any([1, 2, 3])
        # Match f1 that contains any element from [1, 2, 3]
        Matches::
            {'f1': [1, 2]}
            {'f1': [3, 4, 5]}

        :param cond: Either a Predicate that at least one element has to match
         or a list of which at least one element has to be contained
         in the tested element.
-        """
        if callable(cond):
            def _cmp(value):
                return is_iterable(value) and any(cond(e) for e in value)

        else:
            def _cmp(value):
                return is_iterable(value) and any(e in cond for e in value)

        return self._build_predicate(
            lambda lhs, value: _cmp(lhs),
            Operation.ANY,
            (self._path, freeze(cond))
        ) 
Example #22
Source File: entity.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def __get__(self, instance, owner) -> t.Union['Id', t.Tuple]:
        if not instance:
            return self
        return getattr(instance, self._ID_ATTR_NAME, None) 
Example #23
Source File: interactor.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def interactor_factory(
        error_handler: t.Callable = None,
        error_class: t.Union[t.Type[Exception], t.Sequence[t.Type[Exception]]] = ProcessError
):
    """
    Decorator factory that builds a decorator to enriches an application function
    with additional features:

    * input data will be validated using given validators
    * decorated function can use Inject descriptors in its signature
    * errors, described with `error_class`, raised during validation and interaction itself,
      will be turned into a result using `error_handler`
    """
    def interactor(*validators: Validator):
        """
        Closure which encloses arguments of error handling. Takes series of validators
        as the arguments.

        :param validators: callables that make some validation; it might be instances of
            schemas or plain functions that make some additional validation; they should
            take the same signature as the decorated function, ie. may use injected
            dependencies
        :returns: container closure that returns decorated interactor
        """
        def decorator(f: InteractorFunction):
            """
            The actual decorator of an interactor function. Enwraps decorated with decorators
            of validation, error handling and dependency injection.
            """
            decorated_f = validated_by(*validators)(f)
            decorated_f = error_catcher(
                error_class=error_class,
                error_constructor=error_handler
            )(decorated_f)
            decorated_f = inject(decorated_f)
            decorated_f = container_supplier(decorated_f)
            return decorated_f

        return decorator

    return interactor 
Example #24
Source File: base_class.py    From zmirror with MIT License 5 votes vote down vote up
def _dump(self, select='all'):
        """
        :type select: Union[int, str]
        :rtype: str
        """
        from pprint import pformat

        select = {
            "all": "all",
            1: "rv",
            2: "rv2",
            3: "rv3",
        }[select]
        dump = "\n------------- begin dump -------------"

        dump += "\n------------- zmirror parse -------------\n"
        dump += attributes(self.zmirror.parse)
        if self.zmirror.parse.remote_response is not None:
            dump += "\n------------- zmirror remote request -------------\n"
            dump += attributes(self.zmirror.parse.remote_response.request)
            dump += "\n------------- zmirror remote response -------------\n"
            dump += attributes(self.zmirror.parse.remote_response)

        for rv_name in ([select] if select != "all" else ["rv", "rv2", "rv3"]):
            if not hasattr(self, rv_name):
                continue

            rv = getattr(self, rv_name)  # type: Response

            if not isinstance(rv, Response):
                continue

            dump += "\n------------- {} -------------\n".format(rv_name)
            dump += attributes(rv)
            dump += "\n------------- {}.headers -------------\n".format(rv_name)
            dump += pformat(list(rv.headers.items()))

        dump += "\n------------- end dump -------------\n"

        return dump 
Example #25
Source File: threadlocal.py    From zmirror with MIT License 5 votes vote down vote up
def request_data_encoding(self, value):
        """:type value: Union[str, None]"""
        self.__setattr__("_request_data_encoding", value) 
Example #26
Source File: threadlocal.py    From zmirror with MIT License 5 votes vote down vote up
def request_data_encoding(self):
        """浏览器传入的data的编码
        :rtype: Union[str, None]"""
        return self.__getattribute__("_request_data_encoding") 
Example #27
Source File: threadlocal.py    From zmirror with MIT License 5 votes vote down vote up
def request_data(self, value):
        """:type value: Union[str, bytes, None]"""
        self.__setattr__("_request_data", value) 
Example #28
Source File: threadlocal.py    From zmirror with MIT License 5 votes vote down vote up
def request_data(self):
        """浏览器传入的data(已经经过重写)
        :rtype: Union[str, bytes, None]"""
        return self.__getattribute__("_request_data") 
Example #29
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def prepare_client_request_data():
    """
    解析出浏览者发送过来的data, 如果是文本, 则进行重写
    如果是文本, 则对文本内容进行重写后返回str
    如果是二进制则, 则原样返回, 不进行任何处理 (bytes)
    :rtype: Union[str, bytes, None]
    """
    data = request.get_data()  # type: bytes

    # 尝试解析浏览器传入的东西的编码
    encoding = encoding_detect(data)

    if encoding is not None:
        try:
            data = data.decode(encoding=encoding)  # type: str
        except:
            # 解码失败, data是二进制内容或无法理解的编码, 原样返回, 不进行重写
            encoding = None
            pass
        else:
            # data是文本内容, 则进行重写, 并返回str
            data = client_requests_text_rewrite(data)  # type: str

    # 下面这个if是debug用代码, 对正常运行无任何作用
    if developer_string_trace:  # coverage: exclude
        if isinstance(data, str):
            data = data.encode(encoding=encoding)
        if developer_string_trace.encode(encoding=encoding) in data:
            infoprint('StringTrace: appears after client_requests_bin_rewrite, code line no. ', current_line_number())

    return data, encoding 
Example #30
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def encoding_detect(byte_content):
    """
    试图解析并返回二进制串的编码, 如果失败, 则返回 None
    :param byte_content: 待解码的二进制串
    :type byte_content: bytes
    :return: 编码类型或None
    :rtype: Union[str, None]
    """

    if force_decode_remote_using_encode is not None:
        return force_decode_remote_using_encode
    if possible_charsets:
        for charset in possible_charsets:
            try:
                byte_content.decode(encoding=charset)
            except:
                pass
            else:
                return charset
    if cchardet_available:  # detect the encoding using cchardet (if we have)
        return c_chardet(byte_content)['encoding']

    return None