本文整理匯總了Python中typing.Iterable方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Iterable方法的具體用法?Python typing.Iterable怎麽用?Python typing.Iterable使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.Iterable方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def __init__(self, codes: Optional[Iterable[str]] = None):
"""Initialize the filter.
Args:
codes: An optional iterable of two-letter category codes for filtering.
Optional to set at initialization of the class, can be set through properties.
The codes property must be set prior to filtering.
Only codes that are valid categories are added, others are discarded.
Make sure you set appropriately as an iterable for single string values e.g.,
``codes=("bn",)``; otherwise, the codes property will set as empty.
"""
# managed by class properties, no direct setters
self._valid_categories = CATEGORIES # defined in transformers.py
self._codes: Set[str] = set()
# initialize through properties
self.codes = set(codes) if codes else set()
示例2: combine_mnemonics
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def combine_mnemonics(mnemonics: Iterable[str], passphrase: bytes = b"") -> bytes:
"""
Combine mnemonic shares to obtain the master secret which was previously split
using Shamir's secret sharing scheme.
This is the user-friendly method to recover a backed-up secret optionally protected
by a passphrase.
:param mnemonics: List of mnemonics.
:param passphrase: The passphrase used to encrypt the master secret.
:return: The master secret.
"""
if not mnemonics:
raise MnemonicError("The list of mnemonics is empty.")
identifier, iteration_exponent, encrypted_master_secret = recover_ems(mnemonics)
return cipher.decrypt(
encrypted_master_secret, passphrase, iteration_exponent, identifier,
)
示例3: _polymod
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def _polymod(values: Iterable[int]) -> int:
GEN = (
0xE0E040,
0x1C1C080,
0x3838100,
0x7070200,
0xE0E0009,
0x1C0C2412,
0x38086C24,
0x3090FC48,
0x21B1F890,
0x3F3F120,
)
chk = 1
for v in values:
b = chk >> 20
chk = (chk & 0xFFFFF) << 10 ^ v
for i in range(10):
chk ^= GEN[i] if ((b >> i) & 1) else 0
return chk
示例4: _build_predicate
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def _build_predicate(
self,
test: t.Callable,
operation: Operation,
args: t.Iterable
) -> Predicate:
"""
Generate a Predicate object based on a test function.
:param test: The test the Predicate executes.
:param operation: An `Operation` instance for the Predicate.
:return: A `Predicate` object
"""
if not self._path:
raise ValueError('Var has no path')
return Predicate(
check_path(test, self._path),
operation,
args,
self._name
)
示例5: check_path
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def check_path(
test: t.Callable[[t.Any, t.Any], bool],
path: t.Iterable[str]
) -> t.Callable[..., bool]:
def check_path_curried(value):
orig_value = value
for part in path:
try:
value = getattr(value, part)
except AttributeError:
try:
value = value[part]
except (KeyError, TypeError):
return False
return test(value, orig_value)
return check_path_curried
示例6: get_unhidden_ungenerated_python_files
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def get_unhidden_ungenerated_python_files(directory: str) -> Iterable[str]:
"""Iterates through relevant python files within the given directory.
Args:
directory: The top-level directory to explore.
Yields:
File paths.
"""
for dirpath, dirnames, filenames in os.walk(directory, topdown=True):
if os.path.split(dirpath)[-1].startswith('.'):
dirnames.clear()
continue
for filename in filenames:
if filename.endswith('.py') and not filename.endswith('_pb2.py'):
yield os.path.join(dirpath, filename)
示例7: topologically_sorted_checks_with_deps
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def topologically_sorted_checks_with_deps(checks: Iterable[check.Check]
) -> List[check.Check]:
result = []
seen = set() # type: Set[check.Check]
def handle(item: check.Check):
if item in seen:
return
seen.add(item)
# Dependencies first.
for dep in item.dependencies:
handle(dep)
result.append(item)
for e in checks:
handle(e)
return result
示例8: params
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def params(self) -> Iterable[sympy.Symbol]:
"""The parameters of the ansatz."""
for i in range(self.iterations):
for p in range(len(self.qubits)):
if (self.include_all_z or not
numpy.isclose(self.hamiltonian.one_body[p, p], 0)):
yield LetterWithSubscripts('U', p, i)
for p, q in itertools.combinations(range(len(self.qubits)), 2):
if (self.include_all_xxyy or not
numpy.isclose(self.hamiltonian.one_body[p, q].real, 0)):
yield LetterWithSubscripts('T', p, q, i)
if (self.include_all_yxxy or not
numpy.isclose(self.hamiltonian.one_body[p, q].imag, 0)):
yield LetterWithSubscripts('W', p, q, i)
if (self.include_all_cz or not
numpy.isclose(self.hamiltonian.two_body[p, q], 0)):
yield LetterWithSubscripts('V', p, q, i)
示例9: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def __init__(
self,
string: str,
defaults: Optional[dict] = None,
subdomain: Optional[str] = None,
methods: Optional[Iterable[str]] = None,
endpoint: Optional[str] = None,
strict_slashes: Optional[bool] = None,
merge_slashes: Optional[bool] = None,
host: Optional[str] = None,
websocket: bool = False,
provide_automatic_options: bool = False,
) -> None:
super().__init__( # type: ignore
string,
defaults=defaults,
subdomain=subdomain,
methods=methods,
endpoint=endpoint,
strict_slashes=strict_slashes,
merge_slashes=merge_slashes,
host=host,
websocket=websocket,
)
self.provide_automatic_options = provide_automatic_options
示例10: _convert_method_output_to_tensor
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def _convert_method_output_to_tensor(file_or_fd: Any,
fn: Callable,
convert_contiguous: bool = False) -> Iterable[Tuple[str, Tensor]]:
r"""Takes a method invokes it. The output is converted to a tensor.
Args:
file_or_fd (str/FileDescriptor): File name or file descriptor
fn (Callable): Function that has the signature (file name/descriptor) and converts it to
Iterable[Tuple[str, Tensor]].
convert_contiguous (bool, optional): Determines whether the array should be converted into a
contiguous layout. (Default: ``False``)
Returns:
Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is vec/mat
"""
for key, np_arr in fn(file_or_fd):
if convert_contiguous:
np_arr = np.ascontiguousarray(np_arr)
yield key, torch.from_numpy(np_arr)
示例11: read_vec_int_ark
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def read_vec_int_ark(file_or_fd: Any) -> Iterable[Tuple[str, Tensor]]:
r"""Create generator of (key,vector<int>) tuples, which reads from the ark file/stream.
Args:
file_or_fd (str/FileDescriptor): ark, gzipped ark, pipe or opened file descriptor
Returns:
Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is the vector read from file
Example
>>> # read ark to a 'dictionary'
>>> d = { u:d for u,d in torchaudio.kaldi_io.read_vec_int_ark(file) }
"""
# Requires convert_contiguous to be True because elements from int32 vector are
# sored in tuples: (sizeof(int32), value) so strides are (5,) instead of (4,) which will throw an error
# in from_numpy as it expects strides to be a multiple of 4 (int32).
return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_vec_int_ark, convert_contiguous=True)
示例12: _mcmc_move
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def _mcmc_move(params: Iterable[Parameter], dist: Distribution, stacked: StackedObject, shape: int):
"""
Performs an MCMC move to rejuvenate parameters.
:param params: The parameters to use for defining the distribution
:param dist: The distribution to use for sampling
:param stacked: The mask to apply for parameters
:param shape: The shape to sample
:return: Samples from a multivariate normal distribution
"""
rvs = dist.sample((shape,))
for p, msk, ps in zip(params, stacked.mask, stacked.prev_shape):
p.t_values = unflattify(rvs[:, msk], ps)
return True
示例13: update
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def update(self, parameters: Iterable[Parameter], filter_: BaseFilter, weights: torch.Tensor):
"""
Defines the function for updating the parameters.
:param parameters: The parameters of the model to update
:param filter_: The filter
:param weights: The weights to use for propagating.
:return: Self
"""
w = normalize(weights)
if self._record_stats:
self.record_stats(parameters, w)
self._update(parameters, filter_, w)
return self
示例14: codes
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def codes(self, value: Iterable[str]) -> None:
"""Set the codes to a new value (full replacement of the set).
Only codes that are valid categories are added, all others are discarded.
Args:
value: the set of 2-letter codes.
Returns:
None
"""
self._codes = {v for v in value if v in self.valid_codes}
示例15: get_command_options
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Iterable [as 別名]
def get_command_options(
self, include_base=True
): # type: (bool) -> Iterable[CommandOption]
command_options = list(self._command_options.values())
if include_base and self._base_format:
command_options += self._base_format.get_command_options()
return command_options