Python typing.AbstractSet() Examples

The following are 30 code examples of typing.AbstractSet(). 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: masterkey.py    From geofront with GNU Affero General Public License v3.0 7 votes vote down vote up
def __init__(self,
                 servers: AbstractSet[Remote],
                 key_store: MasterKeyStore,
                 interval: datetime.timedelta,
                 key_type: Type[PKey]=RSAKey,
                 bits: Optional[int]=None,
                 start: bool=True) -> None:
        super().__init__()
        self.servers = servers
        self.key_store = key_store
        self.interval = interval
        self.key_type = key_type
        self.bits = bits
        self.terminated = threading.Event()
        if self.start:
            self.start() 
Example #2
Source File: env_settings.py    From pydantic with MIT License 6 votes vote down vote up
def prepare_field(cls, field: ModelField) -> None:
            env_names: Union[List[str], AbstractSet[str]]
            env = field.field_info.extra.get('env')
            if env is None:
                if field.has_alias:
                    warnings.warn(
                        'aliases are no longer used by BaseSettings to define which environment variables to read. '
                        'Instead use the "env" field setting. '
                        'See https://pydantic-docs.helpmanual.io/usage/settings/#environment-variable-names',
                        FutureWarning,
                    )
                env_names = {cls.env_prefix + field.name}
            elif isinstance(env, str):
                env_names = {env}
            elif isinstance(env, (set, frozenset)):
                env_names = env
            elif sequence_like(env):
                env_names = list(env)
            else:
                raise TypeError(f'invalid field env: {env!r} ({display_as_type(env)}); should be string, list or set')

            if not cls.case_sensitive:
                env_names = env_names.__class__(n.lower() for n in env_names)
            field.field_info.extra['env_names'] = env_names 
Example #3
Source File: elevator_distributor.py    From randovania with GNU General Public License v3.0 6 votes vote down vote up
def create_elevator_database(world_list: WorldList,
                             areas_to_not_change: AbstractSet[int],
                             ) -> Tuple[Elevator, ...]:
    """
    Creates a tuple of Elevator objects, exclude those that belongs to one of the areas provided.
    :param world_list:
    :param areas_to_not_change: Set of asset_id of Areas whose teleporters are to be ignored
    :return:
    """
    return tuple(
        Elevator(node.teleporter_instance_id,
                 world.world_asset_id,
                 area.area_asset_id,
                 node.default_connection.world_asset_id,
                 node.default_connection.area_asset_id)

        for world, area, node in world_list.all_worlds_areas_nodes
        if isinstance(node, TeleporterNode) and node.editable and area.area_asset_id not in areas_to_not_change
    ) 
Example #4
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_all(self):
        from typing import __all__ as a
        # Just spot-check the first and last of every category.
        self.assertIn('AbstractSet', a)
        self.assertIn('ValuesView', a)
        self.assertIn('cast', a)
        self.assertIn('overload', a)
        if hasattr(contextlib, 'AbstractContextManager'):
            self.assertIn('ContextManager', a)
        # Check that io and re are not exported.
        self.assertNotIn('io', a)
        self.assertNotIn('re', a)
        # Spot-check that stdlib modules aren't exported.
        self.assertNotIn('os', a)
        self.assertNotIn('sys', a)
        # Check that Text is defined.
        self.assertIn('Text', a)
        # Check previously missing classes.
        self.assertIn('SupportsBytes', a)
        self.assertIn('SupportsComplex', a) 
Example #5
Source File: device.py    From Cirq with Apache License 2.0 6 votes vote down vote up
def qubit_set(self) -> Optional[AbstractSet['cirq.Qid']]:
        """Returns a set or frozenset of qubits on the device, if possible.

        Returns:
            If the device has a finite set of qubits, then a set or frozen set
            of all qubits on the device is returned.

            If the device has no well defined finite set of qubits (e.g.
            `cirq.UnconstrainedDevice` has this property), then `None` is
            returned.
        """

        # Compatibility hack to work with devices that were written before this
        # method was defined.
        for name in ['qubits', '_qubits']:
            if hasattr(self, name):
                val = getattr(self, name)
                if callable(val):
                    val = val()
                return frozenset(val)

        # Default to the qubits being unknown.
        return None 
Example #6
Source File: update_pinnings.py    From bioconda-utils with MIT License 6 votes vote down vote up
def skip_for_variants(meta: MetaData, variant_keys: AbstractSet[str]) -> bool:
    """Check if the recipe uses any given variant keys

    Args:
      meta: Variant MetaData object

    Returns:
      True if any variant key from variant_keys is used
    """
    # This is the same behavior as in
    # conda_build.metadata.Metadata.get_hash_contents but without leaving out
    # "build_string_excludes" (python, r_base, etc.).
    dependencies = set(meta.get_used_vars())
    trim_build_only_deps(meta, dependencies)

    return not dependencies.isdisjoint(variant_keys) 
Example #7
Source File: waveforms.py    From qupulse with MIT License 6 votes vote down vote up
def get_subset_for_channels(self, channels: AbstractSet[ChannelID]) -> 'Waveform':
        """Get a waveform that only describes the channels contained in `channels`.

        Args:
            channels: A channel set the return value should confine to.

        Raises:
            KeyError: If `channels` is not a subset of the waveform's defined channels.

        Returns:
            A waveform with waveform.defined_channels == `channels`
        """
        if not channels <= self.defined_channels:
            raise KeyError('Channels not defined on waveform: {}'.format(channels))
        if channels == self.defined_channels:
            return self
        return self.unsafe_get_subset_for_channels(channels=channels) 
Example #8
Source File: github.py    From the-knights-who-say-ni with Apache License 2.0 6 votes vote down vote up
def comment(self, problems: Mapping[ni_abc.Status, AbstractSet[str]]) -> Optional[str]:
        """Add an appropriate comment relating to the CLA status."""
        if not problems:
            return None

        comments_url = self.request['pull_request']['comments_url']
        problem_messages: Dict[str, str] = defaultdict(str)
        for status, usernames in problems.items():
            problem_messages[status.name] = self._problem_message_template(
                status
            ).format(
                ', '.join(f"@{username}" for username in usernames)
            )

        message = NO_CLA_TEMPLATE.format_map(problem_messages)

        await self._gh.post(comments_url, data={'body': message})
        return message 
Example #9
Source File: github.py    From the-knights-who-say-ni with Apache License 2.0 6 votes vote down vote up
def update(self, problems: Mapping[ni_abc.Status, AbstractSet[str]]) -> None:
        if self.event == PullRequestEvent.opened:
            await self.set_label(problems)
            await self.comment(problems)
        elif self.event == PullRequestEvent.unlabeled:
            # The assumption is that a PR will almost always go from no CLA to
            # being cleared, so don't bug the user with what will probably
            # amount to a repeated message about lacking a CLA.
            await self.set_label(problems)
        elif self.event == PullRequestEvent.synchronize:
            current_label = await self.current_label()
            if not problems:
                if current_label != CLA_OK:
                    await self.remove_label()
            elif current_label != NO_CLA:
                    await self.remove_label()
                    # Since there is a chance a new person was added to a PR
                    # which caused the change in status, a comment on how to
                    # resolve the CLA issue is probably called for.
                    await self.comment(problems)
        else:  # pragma: no cover
            # Should never be reached.
            msg = 'do not know how to update a PR for {}'.format(self.event)
            raise RuntimeError(msg) 
Example #10
Source File: parameters.py    From qupulse with MIT License 6 votes vote down vote up
def is_fulfilled(self, parameters: Mapping[str, Any], volatile: AbstractSet[str] = frozenset()) -> bool:
        """
        Args:
            parameters: These parameters are checked.
            volatile: For each of these parameters a warning is raised if they appear in a constraint

        Raises:
            :class:`qupulse.parameter_scope.ParameterNotProvidedException`: if a parameter is missing

        Warnings:
            ConstrainedParameterIsVolatileWarning: if a constrained parameter is volatile
        """
        affected_parameters = self.affected_parameters
        if not affected_parameters.issubset(parameters.keys()):
            raise ParameterNotProvidedException((affected_parameters-parameters.keys()).pop())

        for parameter in volatile & affected_parameters:
            warnings.warn(ConstrainedParameterIsVolatileWarning(parameter_name=parameter, constraint=self))

        return numpy.all(self._expression.evaluate_in_scope(parameters)) 
Example #11
Source File: parameter_scope.py    From qupulse with MIT License 5 votes vote down vote up
def from_mapping(cls, mapping: Mapping[str, Number], volatile: AbstractSet[str] = frozenset()) -> 'DictScope':
        return cls(FrozenDict(mapping), volatile) 
Example #12
Source File: waveforms.py    From qupulse with MIT License 5 votes vote down vote up
def unsafe_get_subset_for_channels(self, channels: AbstractSet[ChannelID]) -> 'Waveform':
        """Unsafe version of :func:`~qupulse.pulses.instructions.get_measurement_windows`.""" 
Example #13
Source File: waveforms.py    From qupulse with MIT License 5 votes vote down vote up
def unsafe_get_subset_for_channels(self, channels: AbstractSet[ChannelID]) -> 'Waveform':
        return self 
Example #14
Source File: no_commit_to_branch.py    From pre-commit-hooks with MIT License 5 votes vote down vote up
def is_on_branch(
        protected: AbstractSet[str],
        patterns: AbstractSet[str] = frozenset(),
) -> bool:
    try:
        ref_name = cmd_output('git', 'symbolic-ref', 'HEAD')
    except CalledProcessError:
        return False
    chunks = ref_name.strip().split('/')
    branch_name = '/'.join(chunks[2:])
    return branch_name in protected or any(
        re.match(p, branch_name) for p in patterns
    ) 
Example #15
Source File: waveforms.py    From qupulse with MIT License 5 votes vote down vote up
def unsafe_get_subset_for_channels(self, channels: AbstractSet[ChannelID]) -> Waveform:
        return self 
Example #16
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_trusted_users(self):
        usernames = ['miss-islington', 'bedevere-bot']
        problems: Mapping[ni_abc.Status, AbstractSet[str]] = {}
        server = util.FakeServerHost()
        server.trusted_usernames = ''
        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(usernames))
        self.assertEqual(contrib.problems, problems) 
Example #17
Source File: waveforms.py    From qupulse with MIT License 5 votes vote down vote up
def unsafe_get_subset_for_channels(self, channels: AbstractSet[ChannelID]) -> 'Waveform':
        return SequenceWaveform(
            sub_waveform.unsafe_get_subset_for_channels(channels & sub_waveform.defined_channels)
            for sub_waveform in self._sequenced_waveforms if sub_waveform.defined_channels & channels) 
Example #18
Source File: waveforms.py    From qupulse with MIT License 5 votes vote down vote up
def unsafe_get_subset_for_channels(self, channels: AbstractSet[ChannelID]) -> 'RepetitionWaveform':
        return RepetitionWaveform(body=self._body.unsafe_get_subset_for_channels(channels),
                                  repetition_count=self._repetition_count) 
Example #19
Source File: parameter_scope.py    From qupulse with MIT License 5 votes vote down vote up
def __init__(self, values: FrozenMapping[str, Number], volatile: AbstractSet[str] = frozenset()):
        super().__init__()
        assert getattr(values, '__hash__', None) is not None

        self._values = values
        self._as_dict = values
        self._volatile_parameters = FrozenDict({v: Expression(v) for v in volatile})
        self.keys = self._values.keys
        self.items = self._values.items
        self.values = self._values.values 
Example #20
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_abstractset(self):
        self.assertIsInstance(set(), typing.AbstractSet)
        self.assertNotIsInstance(42, typing.AbstractSet) 
Example #21
Source File: link_documents.py    From fava with MIT License 5 votes vote down vote up
def add_to_set(set_: Optional[AbstractSet[str]], new: str) -> Set[str]:
    """Add an entry to a set (or create it if doesn't exist)."""
    return set(set_).union([new]) if set_ else set([new]) 
Example #22
Source File: operators.py    From lale with Apache License 2.0 5 votes vote down vote up
def get_available_transformers(tags: AbstractSet[str] = None) -> List[PlannedOperator]:
    return get_available_operators('transformer', tags) 
Example #23
Source File: operators.py    From lale with Apache License 2.0 5 votes vote down vote up
def get_available_estimators(tags: AbstractSet[str] = None) -> List[PlannedOperator]:
    return get_available_operators('estimator', tags) 
Example #24
Source File: operators.py    From lale with Apache License 2.0 5 votes vote down vote up
def get_available_operators(tag: str, more_tags: AbstractSet[str] = None) -> List[PlannedOperator]:
    singleton = set([tag])
    tags = singleton if (more_tags is None) else singleton.union(more_tags)
    def filter(op):
        tags_dict = op.get_tags()
        if tags_dict is None:
            return False
        tags_set = {tag for prefix in tags_dict for tag in tags_dict[prefix]}
        return tags.issubset(tags_set)
    return [op for op in _all_available_operators if filter(op)] 
Example #25
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 #26
Source File: test_main.py    From the-knights-who-say-ni with Apache License 2.0 5 votes vote down vote up
def test_all_trusted_users(self):
        usernames = ['bedevere-bot', 'miss-islington']
        problems: Mapping[ni_abc.Status, AbstractSet[str]] = {}
        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 #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_comma_separated_trusted_users_with_spaces(self):
        usernames = ['brettcannon', 'miss-islington', 'bedevere-bot']

        problems: Mapping[ni_abc.Status, AbstractSet[str]] = {}
        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(['brettcannon'])) 
Example #28
Source File: test_main.py    From the-knights-who-say-ni with Apache License 2.0 5 votes vote down vote up
def test_comma_separated_trusted_users(self):
        usernames = ['brettcannon', 'miss-islington', 'bedevere-bot']
        problems: Mapping[ni_abc.Status, AbstractSet[str]] = {}
        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(['brettcannon'])) 
Example #29
Source File: test_main.py    From the-knights-who-say-ni with Apache License 2.0 5 votes vote down vote up
def test_not_comma_separated_trusted_users(self):
        usernames = ['miss-islington', 'bedevere-bot']
        problems: Mapping[ni_abc.Status, AbstractSet[str]] = {}
        server = util.FakeServerHost()
        server.trusted_usernames = 'bedevere-bot'
        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(['miss-islington'])) 
Example #30
Source File: test_main.py    From the-knights-who-say-ni with Apache License 2.0 5 votes vote down vote up
def test_response(self):
        # Success case.
        usernames = ['brettcannon']
        problems: Mapping[ni_abc.Status, AbstractSet[str]] = {}
        server = util.FakeServerHost()
        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(usernames))
        self.assertEqual(contrib.problems, problems)