Python typing.Mapping() Examples
The following are 30
code examples of typing.Mapping().
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: GooglePhotosDownload.py From gphotos-sync with MIT License | 8 votes |
def find_bad_items(self, batch: Mapping[str, DatabaseMedia]): """ a batch get failed. Now do all of its contents as individual gets so we can work out which ID(s) cause the failure """ for item_id, media_item in batch.items(): try: log.debug("BAD ID Retry on %s (%s)", item_id, media_item.relative_path) response = self._api.mediaItems.get.execute(mediaItemId=item_id) media_item_json = response.json() self.download_file(media_item, media_item_json) except RequestException as e: self.bad_ids.add_id( str(media_item.relative_path), media_item.id, media_item.url, e ) self.files_download_failed += 1 log.error( "FAILURE %d in get of %s BAD ID", self.files_download_failed, media_item.relative_path, )
Example #2
Source File: filtering.py From bot with MIT License | 7 votes |
def delete_offensive_msg(self, msg: Mapping[str, str]) -> None: """Delete an offensive message, and then delete it from the db.""" try: channel = self.bot.get_channel(msg['channel_id']) if channel: msg_obj = await channel.fetch_message(msg['id']) await msg_obj.delete() except NotFound: log.info( f"Tried to delete message {msg['id']}, but the message can't be found " f"(it has been probably already deleted)." ) except HTTPException as e: log.warning(f"Failed to delete message {msg['id']}: status {e.status}") await self.bot.api_client.delete(f'bot/offensive-messages/{msg["id"]}') log.info(f"Deleted the offensive message with id {msg['id']}.")
Example #3
Source File: matchups.py From Penny-Dreadful-Tools with GNU General Public License v3.0 | 6 votes |
def __init__(self, hero: Dict[str, Union[str, int]], enemy: Dict[str, Union[str, int]], season_id: Optional[int], archetypes: List[Archetype], people: List[Person], cards: List[Card], results: Mapping[str, Union[str, int, List[int], List[Deck]]]) -> None: super().__init__() self.results = results if results: self.results['num_decks'] = len(results['hero_deck_ids']) # type: ignore self.results['win_percent'] = str(round((results['wins'] / (results['wins'] + results['losses'])) * 100, 1)) if results.get('wins') else ''# type: ignore self.criteria = [ {'name': 'Decks Matching…', 'prefix': 'hero_', 'choices': hero}, {'name': '… versus …', 'prefix': 'enemy_', 'choices': enemy} ] # Set up options for dropdowns, marking the right ones as selected. for c in self.criteria: c['archetypes'] = [{'name': a.name, 'id': a.id, 'selected': str(c['choices'].get('archetype_id')) == str(a.id)} for a in archetypes] # type: ignore c['people'] = [{'mtgo_username': p.mtgo_username.lower(), 'id': p.id, 'selected': str(c['choices'].get('person_id')) == str(p.id)} for p in people] # type: ignore c['cards'] = [{'name': card.name, 'selected': c['choices'].get('card') == card.name} for card in cards] # type: ignore self.seasons = [{'season_id': s['num'] or '', 'name': s['name'], 'selected': str(season_id) == str(s['num'])} for s in self.all_seasons()] self.decks = results.get('hero_decks', []) # type: ignore self.show_decks = len(self.decks) > 0 self.matches = results.get('matches', []) self.show_matches = False self.search_season_id = season_id
Example #4
Source File: preprocess.py From CoupletAI with MIT License | 6 votes |
def create_dataset(seqs: List[List[str]], tags: List[List[str]], word_to_ix: Mapping[str, int], max_seq_len: int, pad_ix: int) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Convert List[str] -> torch.Tensor. Returns: seqs_tensor: shape=[num_seqs, max_seq_len]. seqs_mask: shape=[num_seqs, max_seq_len]. tags_tesnor: shape=[num_seqs, max_seq_len]. """ assert len(seqs) == len(tags) num_seqs = len(seqs) seqs_tensor = torch.ones(num_seqs, max_seq_len) * pad_ix seqs_mask = torch.zeros(num_seqs, max_seq_len) tags_tesnor = torch.ones(num_seqs, max_seq_len) * pad_ix for i in trange(num_seqs): seqs_mask[i, : len(seqs[i])] = 1 for j, word in enumerate(seqs[i]): seqs_tensor[i, j] = word_to_ix.get(word, word_to_ix['[UNK]']) for j, tag in enumerate(tags[i]): tags_tesnor[i, j] = word_to_ix.get(tag, word_to_ix['[UNK]']) return seqs_tensor.long(), seqs_mask, tags_tesnor.long()
Example #5
Source File: control.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def _case_insensitive_lookup(entries: Union[Sequence[str], Mapping[str, Any]], key: str, default: Any = UNDEFINED) -> Any: """ Makes a case insensitive lookup within a list or dictionary, providing the first matching entry that we come across. :param entries: list or dictionary to be searched :param key: entry or key value to look up :param default: value to be returned if the key doesn't exist :returns: case insensitive match or default if one was provided and key wasn't found :raises: **ValueError** if no such value exists """ if entries is not None: if isinstance(entries, dict): for k, v in list(entries.items()): if k.lower() == key.lower(): return v else: for entry in entries: if entry.lower() == key.lower(): return entry raise ValueError("key '%s' doesn't exist in dict: %s" % (key, entries))
Example #6
Source File: control.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def _confchanged_cache_invalidation(self, params: Mapping[str, Any]) -> None: """ Drops dependent portions of the cache when configuration changes. :param params: **dict** of 'config_key => value' pairs for configs that changed. The entries' values are currently unused. """ with self._cache_lock: if not self.is_caching_enabled(): return if any('hidden' in param.lower() for param in params.keys()): self._set_cache({'hidden_service_conf': None}) # reset any getinfo parameters that can be changed by a SETCONF self._set_cache(dict([(k.lower(), None) for k in CACHEABLE_GETINFO_PARAMS_UNTIL_SETCONF]), 'getinfo') self._set_cache(None, 'listeners') self._set_cache({'get_custom_options': None}) self._set_cache({'exit_policy': None}) # numerous options can change our policy
Example #7
Source File: control.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def _get_conf_dict_to_response(self, config_dict: Mapping[str, Sequence[str]], default: Any, multiple: bool) -> Dict[str, Union[str, Sequence[str]]]: """ Translates a dictionary of 'config key => [value1, value2...]' into the return value of :func:`~stem.control.Controller.get_conf_map`, taking into account what the caller requested. """ return_dict = {} for key, values in list(config_dict.items()): if values == []: # config option was unset if default != UNDEFINED: return_dict[key] = default else: return_dict[key] = [] if multiple else None else: return_dict[key] = values if multiple else values[0] return return_dict
Example #8
Source File: log.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def __init__(self, fmt: str, datefmt: str, log_colors: typing.Mapping[str, str]) -> None: """Constructor. Args: fmt: The format string to use. datefmt: The date format to use. log_colors: The colors to use for logging levels. """ super().__init__(fmt, datefmt) self._log_colors = log_colors # type: typing.Mapping[str, str] self._colordict = {} # type: typing.Mapping[str, str] # We could solve this nicer by using CSS, but for this simple case this # works. for color in COLORS: self._colordict[color] = '<font color="{}">'.format(color) self._colordict['reset'] = '</font>'
Example #9
Source File: version.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def _path_info() -> typing.Mapping[str, str]: """Get info about important path names. Return: A dictionary of descriptive to actual path names. """ info = { 'config': standarddir.config(), 'data': standarddir.data(), 'cache': standarddir.cache(), 'runtime': standarddir.runtime(), } if standarddir.config() != standarddir.config(auto=True): info['auto config'] = standarddir.config(auto=True) if standarddir.data() != standarddir.data(system=True): info['system data'] = standarddir.data(system=True) return info
Example #10
Source File: extrainfo_descriptor.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def content(cls: Type['stem.descriptor.extrainfo_descriptor.RelayExtraInfoDescriptor'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), sign: bool = False, signing_key: Optional['stem.descriptor.SigningKey'] = None) -> bytes: base_header = ( ('extra-info', '%s %s' % (_random_nickname(), _random_fingerprint())), ('published', _random_date()), ) if sign or signing_key: if attr and 'router-signature' in attr: raise ValueError('Cannot sign the descriptor if a router-signature has been provided') if signing_key is None: signing_key = create_signing_key() content = _descriptor_content(attr, exclude, base_header) + b'\nrouter-signature\n' return _append_router_signature(content, signing_key.private) else: return _descriptor_content(attr, exclude, base_header, ( ('router-signature', _random_crypto_blob('SIGNATURE')), ))
Example #11
Source File: __init__.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def create(cls, attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), validate: bool = True) -> 'stem.descriptor.Descriptor': """ Creates a descriptor with the given attributes. Mandatory fields are filled with dummy information unless data is supplied. This doesn't yet create a valid signature. .. versionadded:: 1.6.0 :param attr: keyword/value mappings to be included in the descriptor :param exclude: mandatory keywords to exclude from the descriptor, this results in an invalid descriptor :param validate: checks the validity of the descriptor's content if **True**, skips these checks otherwise :returns: :class:`~stem.descriptor.Descriptor` subclass :raises: * **ValueError** if the contents is malformed and validate is True * **ImportError** if cryptography is unavailable and sign is True * **NotImplementedError** if not implemented for this descriptor type """ return cls(cls.content(attr, exclude), validate = validate) # type: ignore
Example #12
Source File: networkstatus.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def content(cls: Type['stem.descriptor.networkstatus.DirectoryAuthority'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), is_vote: bool = False) -> bytes: attr = {} if attr is None else dict(attr) # include mandatory 'vote-digest' if a consensus if not is_vote and not ('vote-digest' in attr or (exclude and 'vote-digest' in exclude)): attr['vote-digest'] = _random_fingerprint() content = _descriptor_content(attr, exclude, ( ('dir-source', '%s %s no.place.com %s 9030 9090' % (_random_nickname(), _random_fingerprint(), _random_ipv4_address())), ('contact', 'Mike Perry <email>'), )) if is_vote: content += b'\n' + KeyCertificate.content() return content
Example #13
Source File: __init__.py From stem with GNU Lesser General Public License v3.0 | 6 votes |
def content(cls, attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = ()) -> bytes: """ Creates descriptor content with the given attributes. Mandatory fields are filled with dummy information unless data is supplied. This doesn't yet create a valid signature. .. versionadded:: 1.6.0 :param attr: keyword/value mappings to be included in the descriptor :param exclude: mandatory keywords to exclude from the descriptor, this results in an invalid descriptor :returns: **bytes** with the content of a descriptor :raises: * **ImportError** if cryptography is unavailable and sign is True * **NotImplementedError** if not implemented for this descriptor type """ raise NotImplementedError("The create and content methods haven't been implemented for %s" % cls.__name__)
Example #14
Source File: regen.py From geofront with GNU Affero General Public License v3.0 | 6 votes |
def get_regen_options(config: Mapping[str, object]) -> Tuple[Type[PKey], Optional[int]]: key_type = config.get('MASTER_KEY_TYPE', RSAKey) if not isinstance(key_type, type): raise RegenOptionError('MASTER_KEY_TYPE configuration must be a type, ' 'not ' + repr(key_type)) elif not issubclass(key_type, PKey): raise RegenOptionError( 'MASTER_KEY_TYPE configuration must be a subclass of ' '{0.__module__}.{0.__qualname__}, but {1.__module__}.' '{1.__qualname__} is not'.format(PKey, key_type) ) bits = config['MASTER_KEY_BITS'] if bits is not None and not isinstance(bits, int): raise RegenOptionError('MASTER_KEY_BITS configuration must be an ' 'integer, not ' + repr(bits)) return RSAKey, bits
Example #15
Source File: stash.py From geofront with GNU Affero General Public License v3.0 | 6 votes |
def request_list( self, identity: Identity ) -> Iterator[Sequence[Mapping[str, object]]]: team = self.team if not (isinstance(team, identity.team_type) and cast(str, identity.identifier).startswith(team.server_url)): return start = 0 while True: response = self.request( identity, 'GET', self.LIST_URL.format(self.team, start) ) assert response.code == 200 payload = json.load(io.TextIOWrapper(response, encoding='utf-8')) response.close() yield from payload['values'] if payload['isLastPage']: break start = payload['nextPageStart']
Example #16
Source File: config.py From quart with MIT License | 6 votes |
def from_mapping(self, mapping: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> None: """Load the configuration values from a mapping. This allows either a mapping to be directly passed or as keyword arguments, for example, .. code-block:: python config = {'FOO': 'bar'} app.config.from_mapping(config) app.config.form_mapping(FOO='bar') Arguments: mapping: Optionally a mapping object. kwargs: Optionally a collection of keyword arguments to form a mapping. """ mappings: Dict[str, Any] = {} if mapping is not None: mappings.update(mapping) mappings.update(kwargs) for key, value in mappings.items(): if key.isupper(): self[key] = value
Example #17
Source File: extrainfo_descriptor.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def content(cls: Type['stem.descriptor.extrainfo_descriptor.BridgeExtraInfoDescriptor'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = ()) -> bytes: return _descriptor_content(attr, exclude, ( ('extra-info', 'ec2bridgereaac65a3 %s' % _random_fingerprint()), ('published', _random_date()), ), ( ('router-digest', _random_fingerprint()), ))
Example #18
Source File: _transformation.py From tmppy with Apache License 2.0 | 5 votes |
def __init__(self, replacements: Mapping[str, str]): super().__init__() self.replacements = replacements
Example #19
Source File: tracing.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def __init__( self, environ, # type: typing.Mapping[str, str] prefix="HTTP_", # type: str ): # type: (...) -> None self.environ = environ self.prefix = prefix
Example #20
Source File: hidden_service.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def content(cls: Type['stem.descriptor.hidden_service.HiddenServiceDescriptorV2'], attr: Mapping[str, str] = None, exclude: Sequence[str] = ()) -> bytes: return _descriptor_content(attr, exclude, ( ('rendezvous-service-descriptor', 'y3olqqblqw2gbh6phimfuiroechjjafa'), ('version', '2'), ('permanent-key', _random_crypto_blob('RSA PUBLIC KEY')), ('secret-id-part', 'e24kgecavwsznj7gpbktqsiwgvngsf4e'), ('publication-time', _random_date()), ('protocol-versions', '2,3'), ('introduction-points', '\n-----BEGIN MESSAGE-----\n-----END MESSAGE-----'), ), ( ('signature', _random_crypto_blob('SIGNATURE')), ))
Example #21
Source File: server_descriptor.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def content(cls: Type['stem.descriptor.server_descriptor.BridgeDescriptor'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = ()) -> bytes: return _descriptor_content(attr, exclude, ( ('router', '%s %s 9001 0 0' % (_random_nickname(), _random_ipv4_address())), ('router-digest', '006FD96BA35E7785A6A3B8B75FE2E2435A13BDB4'), ('published', _random_date()), ('bandwidth', '409600 819200 5120'), ('reject', '*:*'), ))
Example #22
Source File: server_descriptor.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def create(cls: Type['stem.descriptor.server_descriptor.RelayDescriptor'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), validate: bool = True, sign: bool = False, signing_key: Optional['stem.descriptor.SigningKey'] = None, exit_policy: Optional['stem.exit_policy.ExitPolicy'] = None) -> 'stem.descriptor.server_descriptor.RelayDescriptor': return cls(cls.content(attr, exclude, sign, signing_key, exit_policy), validate = validate, skip_crypto_validation = not sign)
Example #23
Source File: server_descriptor.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def content(cls: Type['stem.descriptor.server_descriptor.RelayDescriptor'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), sign: bool = False, signing_key: Optional['stem.descriptor.SigningKey'] = None, exit_policy: Optional['stem.exit_policy.ExitPolicy'] = None) -> bytes: attr = dict(attr) if attr else {} if exit_policy is None: exit_policy = REJECT_ALL_POLICY base_header = [ ('router', '%s %s 9001 0 0' % (_random_nickname(), _random_ipv4_address())), ('published', _random_date()), ('bandwidth', '153600 256000 104590'), ] + [ tuple(line.split(' ', 1)) for line in str(exit_policy).splitlines() # type: ignore ] + [ ('onion-key', _random_crypto_blob('RSA PUBLIC KEY')), ('signing-key', _random_crypto_blob('RSA PUBLIC KEY')), ] if sign or signing_key: if attr and 'signing-key' in attr: raise ValueError('Cannot sign the descriptor if a signing-key has been provided') elif attr and 'router-signature' in attr: raise ValueError('Cannot sign the descriptor if a router-signature has been provided') if signing_key is None: signing_key = create_signing_key() if 'fingerprint' not in attr: fingerprint = hashlib.sha1(_bytes_for_block(stem.util.str_tools._to_unicode(signing_key.public_digest.strip()))).hexdigest().upper() attr['fingerprint'] = ' '.join(stem.util.str_tools._split_by_length(fingerprint, 4)) attr['signing-key'] = signing_key.public_digest content = _descriptor_content(attr, exclude, base_header) + b'\nrouter-signature\n' return _append_router_signature(content, signing_key.private) else: return _descriptor_content(attr, exclude, base_header, ( ('router-sig-ed25519', None), ('router-signature', _random_crypto_blob('SIGNATURE')), ))
Example #24
Source File: config.py From quart with MIT License | 5 votes |
def from_file( self, filename: str, load: Callable[[IO[Any]], Mapping], silent: bool = False ) -> None: """Load the configuration from a data file. This allows configuration to be loaded as so .. code-block:: python app.config.from_file('config.toml', toml.load) app.config.from_file('config.json', json.load) Arguments: filename: The filename which when appended to :attr:`root_path` gives the path to the file. load: Callable that takes a file descriptor and returns a mapping loaded from the file. silent: If True any errors will fail silently. """ file_path = self.root_path / filename try: with open(file_path) as file_: data = load(file_) except (FileNotFoundError, IsADirectoryError): if not silent: raise else: self.from_mapping(data)
Example #25
Source File: conf.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self, config_dict: Mapping[str, Any], interceptor: Callable[[str, Any], Any]) -> None: self.config_dict = config_dict self.interceptor = interceptor
Example #26
Source File: tracing.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def continue_from_environ( cls, environ, # type: typing.Mapping[str, str] **kwargs # type: Any ): # type: (...) -> Transaction if cls is Span: logger.warning( "Deprecated: use Transaction.continue_from_environ " "instead of Span.continue_from_environ." ) return Transaction.continue_from_headers(EnvironHeaders(environ), **kwargs)
Example #27
Source File: directory.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def _write(fallbacks: Dict[str, 'stem.directory.Fallback'], tor_commit: str, stem_commit: str, headers: Mapping[str, str], path: str = FALLBACK_CACHE_PATH) -> None: """ Persists fallback directories to a location in a way that can be read by from_cache(). :param fallbacks: mapping of fingerprints to their fallback directory :param tor_commit: tor commit the fallbacks came from :param stem_commit: stem commit the fallbacks came from :param headers: metadata about the file these came from :param path: location fallbacks will be persisted to """ conf = stem.util.conf.Config() conf.set('tor_commit', tor_commit) conf.set('stem_commit', stem_commit) for k, v in headers.items(): conf.set('header.%s' % k, v) for directory in sorted(fallbacks.values(), key = lambda x: x.fingerprint): fingerprint = directory.fingerprint conf.set('%s.address' % fingerprint, directory.address) conf.set('%s.or_port' % fingerprint, str(directory.or_port)) conf.set('%s.dir_port' % fingerprint, str(directory.dir_port)) conf.set('%s.nickname' % fingerprint, directory.nickname) conf.set('%s.has_extrainfo' % fingerprint, 'true' if directory.has_extrainfo else 'false') if directory.orport_v6: conf.set('%s.orport6_address' % fingerprint, str(directory.orport_v6[0])) conf.set('%s.orport6_port' % fingerprint, str(directory.orport_v6[1])) conf.save(path)
Example #28
Source File: directory.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self, address: Optional[str] = None, or_port: Optional[Union[int, str]] = None, dir_port: Optional[Union[int, str]] = None, fingerprint: Optional[str] = None, nickname: Optional[str] = None, has_extrainfo: bool = False, orport_v6: Optional[Tuple[str, int]] = None, header: Optional[Mapping[str, str]] = None) -> None: super(Fallback, self).__init__(address, or_port, dir_port, fingerprint, nickname, orport_v6) self.has_extrainfo = has_extrainfo self.header = collections.OrderedDict(header) if header else collections.OrderedDict()
Example #29
Source File: manual.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self, name: str, synopsis: str, description: str, commandline_options: Mapping[str, str], signals: Mapping[str, str], files: Mapping[str, str], config_options: Mapping[str, 'stem.manual.ConfigOption']) -> None: self.name = name self.synopsis = synopsis self.description = description self.commandline_options = collections.OrderedDict(commandline_options) self.signals = collections.OrderedDict(signals) self.files = collections.OrderedDict(files) self.config_options = collections.OrderedDict(config_options) self.man_commit = None self.stem_commit = None self.schema = None
Example #30
Source File: hidden_service.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def create(cls: Type['stem.descriptor.hidden_service.OuterLayer'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), validate: bool = True, sign: bool = False, inner_layer: Optional['stem.descriptor.hidden_service.InnerLayer'] = None, revision_counter: int = None, authorized_clients: Optional[Sequence['stem.descriptor.hidden_service.AuthorizedClient']] = None, subcredential: bytes = None, blinded_key: bytes = None) -> 'stem.descriptor.hidden_service.OuterLayer': return cls(cls.content(attr, exclude, validate, sign, inner_layer, revision_counter, authorized_clients, subcredential, blinded_key), validate = validate)