Python typing.FrozenSet() Examples

The following are 30 code examples of typing.FrozenSet(). 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: link_based_source.py    From beancount-import with GNU General Public License v2.0 6 votes vote down vote up
def get_entries_with_link(
            self,
            all_entries: Entries,
            valid_links: Union[Set[str], FrozenSet[str]],
            results: SourceResults,
    ) -> Dict[str, List[Transaction]]:
        link_prefix = self.link_prefix
        seen_entries = dict()  # type: Dict[str, Entries]
        for entry in all_entries:
            if not isinstance(entry, Transaction): continue
            for link in entry.links:
                if not link.startswith(link_prefix): continue
                txn_id = link[len(link_prefix):]
                seen_entries.setdefault(txn_id, []).append(entry)
        for txn_id, entries in seen_entries.items():
            expected_count = 1 if txn_id in valid_links else 0
            if len(entries) == expected_count: continue
            results.add_invalid_reference(
                InvalidSourceReference(
                    num_extras=len(entries) - expected_count,
                    transaction_posting_pairs=[(t, None) for t in entries]))
        return seen_entries 
Example #2
Source File: owlsim2.py    From ontobio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def search_by_attribute_set(
        url: str,
        profile: FrozenSet[str],
        limit: Optional[int] = 100,
        namespace_filter: Optional[str]=None) -> Dict:
    """
    Given a list of phenotypes, returns a ranked list of individuals
    individuals can be filtered by namespace, eg MONDO, MGI, HGNC
    :returns Dict with the structure: {
        'unresolved' : [...]
        'query_IRIs' : [...]
        'results': {...}
    }
    :raises JSONDecodeError: If the response body does not contain valid json.
    """
    owlsim_url = url + 'searchByAttributeSet'

    params = {
        'a': profile,
        'limit': limit,
        'target': namespace_filter
    }
    return requests.post(owlsim_url, data=params, timeout=TIMEOUT).json() 
Example #3
Source File: matching.py    From beancount-import with GNU General Public License v2.0 6 votes vote down vote up
def get_unknown_to_opposite_unknown_extensions(
        transaction_constraint: IsTransactionMergeablePredicate,
        posting_db: PostingDatabase,
        excluded_transaction_ids: FrozenSet[int],
        mp: MatchablePosting) -> Iterable[SingleStepMergedTransaction]:
    """Finds extensions that remove both `mp` and an unknown posting of opposite
    weight in the matching transaction.
    """
    for matching_transaction, other_mp in _get_valid_posting_matches(
            transaction_constraint,
            mp.posting,
            negate=True,
            posting_db=posting_db,
            excluded_transaction_ids=excluded_transaction_ids):
        if not is_removal_candidate(other_mp): continue
        yield SingleStepMergedTransaction(
            combine_transactions_using_match_set(
                (transaction_constraint.transaction, matching_transaction),
                match_set=PostingMatchSet(matches=[], removals=(mp, other_mp)),
                is_cleared=posting_db.is_cleared), matching_transaction) 
Example #4
Source File: matching.py    From beancount-import with GNU General Public License v2.0 6 votes vote down vote up
def _get_valid_posting_matches(
        transaction_constraint: IsTransactionMergeablePredicate,
        posting: Posting, negate: bool, posting_db: PostingDatabase,
        excluded_transaction_ids: FrozenSet[int]
) -> Iterable[Tuple[Transaction, MatchablePosting]]:
    """Returns the matching transaction, posting pairs.

    Transactions already present in `excluded_transaction_ids` are excluded, as
    are transactions that do not satisfy `transaction_constraint`.
    """
    matches = posting_db.get_posting_matches(
        transaction_constraint.transaction, posting, negate=negate)
    for matching_transaction, mp in matches:
        if id(matching_transaction) in excluded_transaction_ids:
            continue
        if not transaction_constraint(matching_transaction): continue
        yield matching_transaction, mp 
Example #5
Source File: stylesheet.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, obj: QObject,
                 stylesheet: Optional[str], update: bool) -> None:
        super().__init__()
        self._obj = obj
        self._update = update

        # We only need to hang around if we are asked to update.
        if update:
            self.setParent(self._obj)
        if stylesheet is None:
            self._stylesheet = obj.STYLESHEET  # type: str
        else:
            self._stylesheet = stylesheet

        if update:
            self._options = jinja.template_config_variables(
                self._stylesheet)  # type: Optional[FrozenSet[str]]
        else:
            self._options = None 
Example #6
Source File: manager.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def server_status_required(allowed_status: FrozenSet[ManagerStatus]):

    def decorator(handler):

        @functools.wraps(handler)
        async def wrapped(request, *args, **kwargs):
            status = await request.app['config_server'].get_manager_status()
            if status not in allowed_status:
                if status == ManagerStatus.FROZEN:
                    raise ServerFrozen
                msg = f'Server is not in the required status: {allowed_status}'
                raise ServiceUnavailable(msg)
            return (await handler(request, *args, **kwargs))

        return wrapped

    return decorator 
Example #7
Source File: matching.py    From beancount-import with GNU General Public License v2.0 6 votes vote down vote up
def filter_dominated_match_sets(
        match_sets: List[PostingMatchSet]) -> List[PostingMatchSet]:
    """Computes a filtered list of PostingMatchSet objects with dominated match sets
    removed.

    A PostingMatchSet `a` dominates another PostingMatchSet `b` if `a` contains
    all of the matches in `b`.
    """
    match_sets.sort(key=lambda x: -len(x.matches))
    filtered_results = []
    filtered_posting_match_frozensets = [
    ]  # type: List[FrozenSet[Tuple[int,int]]]
    for match_set in match_sets:
        if any(
                all((id(a), id(b)) in existing for a, b in match_set.matches)
                for existing in filtered_posting_match_frozensets):
            continue
        filtered_posting_match_frozensets.append(
            _get_posting_match_frozenset(match_set.matches))
        filtered_results.append(match_set)
    return filtered_results


# [[neg_a, neg_b], [pos_a, pos_b]] 
Example #8
Source File: owlsim2.py    From ontobio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compare_attribute_sets(
        url: str,
        profile_a: FrozenSet[str],
        profile_b: FrozenSet[str]) -> Dict:
    """
    Given two phenotype profiles, returns their similarity
    :returns Dict with the structure: {
        'unresolved' : [...]
        'query_IRIs' : [...]
        'target_IRIs': [...]
        'results': {...}
    }
    """
    owlsim_url = url + 'compareAttributeSets'

    params = {
        'a': profile_a,
        'b': profile_b,
    }

    return requests.post(owlsim_url, data=params, timeout=TIMEOUT).json() 
Example #9
Source File: envoy_tools.py    From paasta with Apache License 2.0 6 votes vote down vote up
def get_casper_endpoints(clusters_info: Dict[str, Any]) -> FrozenSet[Tuple[str, int]]:
    """Filters out and returns casper endpoints from Envoy clusters."""
    casper_endpoints: Set[Tuple[str, int]] = set()
    for cluster_status in clusters_info["cluster_statuses"]:
        if "host_statuses" in cluster_status:
            if cluster_status["name"].startswith("spectre.") and cluster_status[
                "name"
            ].endswith(".egress_cluster"):
                for host_status in cluster_status["host_statuses"]:
                    casper_endpoints.add(
                        (
                            host_status["address"]["socket_address"]["address"],
                            host_status["address"]["socket_address"]["port_value"],
                        )
                    )
    return frozenset(casper_endpoints) 
Example #10
Source File: owlsim2.py    From ontobio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_attribute_information_profile(
        url: str,
        profile: Optional[FrozenSet[str]]=None,
        categories: Optional[FrozenSet[str]]=None) -> Dict:
    """
    Get the information content for a list of phenotypes
    and the annotation sufficiency simple and
    and categorical scores if categories are provied

    Ref: https://zenodo.org/record/834091#.W8ZnCxhlCV4
    Note that the simple score varies slightly from the pub in that
    it uses max_max_ic instead of mean_max_ic

    If no arguments are passed this function returns the
    system (loaded cohort) stats
    :raises JSONDecodeError: If the response body does not contain valid json.
    """
    owlsim_url = url + 'getAttributeInformationProfile'

    params = {
        'a': profile,
        'r': categories
    }
    return requests.post(owlsim_url, data=params, timeout=TIMEOUT).json() 
Example #11
Source File: ambassador.py    From ambassador with Apache License 2.0 6 votes vote down vote up
def kinds(self) -> FrozenSet[KubernetesGVK]:
        kinds = [
            'AuthService',
            'ConsulResolver',
            'Host',
            'KubernetesEndpointResolver',
            'KubernetesServiceResolver',
            'LogService',
            'Mapping',
            'Module',
            'RateLimitService',
            'TCPMapping',
            'TLSContext',
            'TracingService',
        ]

        return frozenset([
            KubernetesGVK.for_ambassador(kind, version=version) for (kind, version) in itertools.product(kinds, ['v1', 'v2'])
        ]) 
Example #12
Source File: top_k_uniques_stats_generator.py    From data-validation with Apache License 2.0 6 votes vote down vote up
def _make_dataset_feature_stats_proto_with_topk_for_single_feature(
    feature_path_to_value_count_list: Tuple[Tuple[types.SliceKey,
                                                  FeaturePathTuple],
                                            List[FeatureValueCount]],
    categorical_features: FrozenSet[types.FeaturePath], is_weighted_stats: bool,
    num_top_values: int, frequency_threshold: Union[int, float],
    num_rank_histogram_buckets: int
) -> Tuple[types.SliceKey, statistics_pb2.DatasetFeatureStatistics]:
  """Makes a DatasetFeatureStatistics proto with top-k stats for a feature."""
  (slice_key, feature_path_tuple), value_count_list = (
      feature_path_to_value_count_list)
  feature_path = types.FeaturePath(feature_path_tuple)
  result = statistics_pb2.DatasetFeatureStatistics()
  result.features.add().CopyFrom(
      make_feature_stats_proto_with_topk_stats(
          feature_path, value_count_list, feature_path in categorical_features,
          is_weighted_stats, num_top_values, frequency_threshold,
          num_rank_histogram_buckets))
  return slice_key, result 
Example #13
Source File: whitelist.py    From wikipron with Apache License 2.0 6 votes vote down vote up
def _filter_write(
    input_tsv_path: str, phones: FrozenSet[str], output_tsv_path: str
) -> None:
    """Creates TSV filtered by whitelist."""
    with open(input_tsv_path, "r") as source, open(
        output_tsv_path, "w"
    ) as sink:
        for line in source:
            line = line.rstrip()
            (word, pron, *_) = line.split("\t", 2)
            these_phones = frozenset(pron.split())
            bad_phones = these_phones - phones
            if bad_phones:
                for phone in bad_phones:
                    logging.warning("Bad phone:\t%s\t(%s)", phone, word)
            else:
                print(line, file=sink) 
Example #14
Source File: pixel_map.py    From python-sc2 with MIT License 5 votes vote down vote up
def flood_fill_all(self, pred: Callable[[int], bool]) -> Set[FrozenSet[Point2]]:
        groups: Set[FrozenSet[Point2]] = set()

        for x in range(self.width):
            for y in range(self.height):
                if any((x, y) in g for g in groups):
                    continue

                if pred(self[x, y]):
                    groups.add(frozenset(self.flood_fill(Point2((x, y)), pred)))

        return groups 
Example #15
Source File: k8sprocessor.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def kinds(self) -> FrozenSet[KubernetesGVK]:
        return frozenset(iter(self.mapping)) 
Example #16
Source File: utilities.py    From Ithemal with MIT License 5 votes vote down vote up
def get_register_class(reg):
    # type: Union[str, int] -> Optional[FrozenSet[str]]

    if isinstance(reg, int):
        reg = _global_sym_dict.get(reg)

    for cls in _REGISTER_CLASSES:
        if reg in cls:
            return cls

    return None 
Example #17
Source File: message.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def content_set_bool(self) -> FrozenSet[bool]:
        """Get the 'content_set_bool' content from the message."""
        assert self.is_set("content_set_bool"), "'content_set_bool' content is not set."
        return cast(FrozenSet[bool], self.get("content_set_bool")) 
Example #18
Source File: message.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def content_set_int(self) -> FrozenSet[int]:
        """Get the 'content_set_int' content from the message."""
        assert self.is_set("content_set_int"), "'content_set_int' content is not set."
        return cast(FrozenSet[int], self.get("content_set_int")) 
Example #19
Source File: message.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def content_set_float(self) -> FrozenSet[float]:
        """Get the 'content_set_float' content from the message."""
        assert self.is_set(
            "content_set_float"
        ), "'content_set_float' content is not set."
        return cast(FrozenSet[float], self.get("content_set_float")) 
Example #20
Source File: message.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def content_set_str(self) -> FrozenSet[str]:
        """Get the 'content_set_str' content from the message."""
        assert self.is_set("content_set_str"), "'content_set_str' content is not set."
        return cast(FrozenSet[str], self.get("content_set_str")) 
Example #21
Source File: message.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def content_o_union(
        self,
    ) -> Optional[
        Union[
            str,
            Dict[str, int],
            FrozenSet[int],
            FrozenSet[bytes],
            Tuple[bool, ...],
            Dict[str, float],
        ]
    ]:
        """Get the 'content_o_union' content from the message."""
        return cast(
            Optional[
                Union[
                    str,
                    Dict[str, int],
                    FrozenSet[int],
                    FrozenSet[bytes],
                    Tuple[bool, ...],
                    Dict[str, float],
                ]
            ],
            self.get("content_o_union"),
        ) 
Example #22
Source File: conftest.py    From wikidata with GNU General Public License v3.0 5 votes vote down vote up
def pytest_assertrepr_compare(op: str, left, right) -> Optional[Sequence[str]]:
    # set of entities
    if op == '==' and isinstance(left, (set, frozenset)) and \
       isinstance(right, (set, frozenset)) and \
       all(isinstance(v, Entity) for v in left) and \
       all(isinstance(v, Entity) for v in right):
        def repr_ids(ids: AbstractSet[EntityId]) -> str:
            sorted_ids = sorted(
                ids,
                key=lambda i: (
                    i[0],
                    # Since EntityIds usually consist of one letter followed
                    # by digits, order them numerically.  If it's not in
                    # that format they should be sorted in the other bucket.
                    (0, int(i[1:])) if i[1:].isdigit() else (1, i[1:])
                )
            )
            return '{' + ', '.join(sorted_ids) + '}'
        left = cast(Union[Set[Entity], FrozenSet[Entity]], left)
        right = cast(Union[Set[Entity], FrozenSet[Entity]], right)
        left_ids = {e.id for e in left}
        right_ids = {e.id for e in right}
        return [
            '{} == {}'.format(repr_ids(left_ids), repr_ids(right_ids)),
            'Extra entities in the left set:',
            repr_ids(left_ids - right_ids),
            'Extra entities in the right set:',
            repr_ids(right_ids - left_ids),
        ]
    return None 
Example #23
Source File: k8sprocessor.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def kinds(self) -> FrozenSet[KubernetesGVK]:
        return self.delegate.kinds() 
Example #24
Source File: ion_device.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def qubit_set(self) -> FrozenSet['cirq.LineQubit']:
        return self.qubits 
Example #25
Source File: k8sprocessor.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def kinds(self) -> FrozenSet[KubernetesGVK]:
        # Override kinds to describe the types of resources this processor wants
        # to process.
        return frozenset() 
Example #26
Source File: knative.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def kinds(self) -> FrozenSet[KubernetesGVK]:
        kinds = [
            'Ingress',
            'ClusterIngress',
        ]

        return frozenset([KubernetesGVK.for_knative_networking(kind) for kind in kinds]) 
Example #27
Source File: test_main.py    From the-knights-who-say-ni with Apache License 2.0 5 votes vote down vote up
def test_no_usernames(self):
        usernames: FrozenSet[str] = frozenset()
        problems = {ni_abc.Status.not_signed: {'miss-islington'}}
        server = util.FakeServerHost()
        server.trusted_usernames = 'bedevere-bot, miss-islington'
        cla = FakeCLAHost(problems)
        contrib = FakeContribHost(usernames)
        request = util.FakeRequest()
        with mock.patch('ni.__main__.ContribHost', contrib):
            responder = __main__.handler(util.FakeSession, server, cla)
            response = self.run_awaitable(responder(request))
        self.assertEqual(response.status, 200)
        self.assertEqual(cla.usernames, frozenset())
        self.assertEqual(contrib.problems, problems) 
Example #28
Source File: runner.py    From kitty with GNU General Public License v3.0 5 votes vote down vote up
def all_kitten_names() -> FrozenSet[str]:
    n = []
    import glob
    base = os.path.dirname(os.path.abspath(__file__))
    for x in glob.glob(os.path.join(base, '*', '__init__.py')):
        q = os.path.basename(os.path.dirname(x))
        if q != 'tui':
            n.append(q)
    return frozenset(n) 
Example #29
Source File: SettingFunction.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getUsedSettingKeys(self) -> FrozenSet[str]:
        """Retrieve a set of the keys (strings) of all the settings used in this function.

        :return: A set of the keys (strings) of all the settings used in this functions.
        """

        return self._used_keys 
Example #30
Source File: SettingFunction.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, expression: str) -> None:
        """Constructor.

        :param expression: The Python code this function should evaluate.
        """
        super().__init__()

        self._code = expression

        #  Keys of all settings that are referenced to in this function.
        self._used_keys = frozenset()  # type: FrozenSet[str]
        self._used_values = frozenset()  # type: FrozenSet[str]

        self._compiled = None  # type: Optional[CodeType] #Actually an Optional['code'] object, but Python doesn't properly expose this 'code' object via any library.
        self._valid = False  # type: bool

        try:
            tree = ast.parse(self._code, "eval")

            result = _SettingExpressionVisitor().visit(tree)
            self._used_keys = frozenset(result.keys)
            self._used_values = frozenset(result.values)

            self._compiled = compile(self._code, repr(self), "eval")
            self._valid = True
        except (SyntaxError, TypeError) as e:
            Logger.log("e", "Parse error in function ({1}) for setting: {0}".format(str(e), self._code))
        except IllegalMethodError as e:
            Logger.log("e", "Use of illegal method {0} in function ({1}) for setting".format(str(e), self._code))
        except Exception as e:
            Logger.log("e", "Exception in function ({0}) for setting: {1}".format(str(e), self._code))