當前位置: 首頁>>代碼示例>>Python>>正文


Python typing.Sized方法代碼示例

本文整理匯總了Python中typing.Sized方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Sized方法的具體用法?Python typing.Sized怎麽用?Python typing.Sized使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在typing的用法示例。


在下文中一共展示了typing.Sized方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: zip_equal

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def zip_equal(*args: Union[Sized, Iterable]) -> Iterable[Tuple]:
    """
    zip over the given iterables, but enforce that all of them exhaust simultaneously.

    Examples
    --------
    >>> zip_equal([1, 2, 3], [4, 5, 6]) # ok
    >>> zip_equal([1, 2, 3], [4, 5, 6, 7]) # raises ValueError
    # ValueError is raised even if the lengths are not known
    >>> zip_equal([1, 2, 3], map(np.sqrt, [4, 5, 6])) # ok
    >>> zip_equal([1, 2, 3], map(np.sqrt, [4, 5, 6, 7])) # raises ValueError
    """
    if not args:
        return

    lengths = []
    all_lengths = []
    for arg in args:
        try:
            lengths.append(len(arg))
            all_lengths.append(len(arg))
        except TypeError:
            all_lengths.append('?')

    if lengths and not all(x == lengths[0] for x in lengths):
        from .checks import join
        raise ValueError(f'The arguments have different lengths: {join(all_lengths)}.')

    iterables = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iterables:
            with suppress(StopIteration):
                result.append(next(it))

        if len(result) != len(args):
            break
        yield tuple(result)

    if len(result) != 0:
        raise ValueError(f'The iterables did not exhaust simultaneously.') 
開發者ID:neuro-ml,項目名稱:deep_pipe,代碼行數:43,代碼來源:itertools.py

示例2: test_sized

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def test_sized(self):
        assert isinstance([], typing.Sized)
        assert not isinstance(42, typing.Sized) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:5,代碼來源:test_typing.py

示例3: predict_batch

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        if not self.use_block:
            return np.random.randint(0, high=int(self.n_actions), size=(len(observations),))
        self._i += 1
        return self.noise[: len(observations), self._i % self.samples] 
開發者ID:Guillemdb,項目名稱:FractalAI,代碼行數:14,代碼來源:model.py

示例4: serialize

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def serialize(self, instance: Sized):
        _check_type_and_size(instance, self.actual_type, len(self.items), SerializationError)
        return self.actual_type(serialize(o, t) for t, o in zip(self.items, instance)) 
開發者ID:zyfra,項目名稱:ebonite,代碼行數:5,代碼來源:dataset_type.py

示例5: contains

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def contains(self, x):
        if not isinstance(x, Sized):
            return False

        if not (self.min_seq_length <= len(x) <= self.max_seq_length):
            return False

        return all([self.space.contains(el) for el in x]) 
開發者ID:facebookresearch,項目名稱:habitat-api,代碼行數:10,代碼來源:spaces.py

示例6: are_none

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def are_none(sequences: Sequence[Sized]) -> bool:
    """
    Returns True if all sequences are None.
    """
    if not sequences:
        return True
    return all(s is None for s in sequences) 
開發者ID:awslabs,項目名稱:sockeye,代碼行數:9,代碼來源:data_io.py

示例7: are_token_parallel

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def are_token_parallel(sequences: Sequence[Sized]) -> bool:
    """
    Returns True if all sequences in the list have the same length.
    """
    if not sequences or len(sequences) == 1:
        return True
    return all(len(s) == len(sequences[0]) for s in sequences) 
開發者ID:awslabs,項目名稱:sockeye,代碼行數:9,代碼來源:data_io.py

示例8: test_sized

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def test_sized(self):
        self.assertIsInstance([], typing.Sized)
        self.assertNotIsInstance(42, typing.Sized) 
開發者ID:ShikyoKira,項目名稱:Project-New-Reign---Nemesis-Main,代碼行數:5,代碼來源:test_typing.py

示例9: _get_all_dimensions

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def _get_all_dimensions(batch: Sequence, level: int = 0, res: Optional[List[List[int]]] = None) -> List[List[int]]:
    """Return all presented element sizes of each dimension.

    Args:
        batch: Data array.
        level: Recursion level.
        res: List containing element sizes of each dimension.

    Return:
        List, i-th element of which is list containing all presented sized of batch's i-th dimension.

    Examples:
        >>> x = [[[1], [2, 3]], [[4], [5, 6, 7], [8, 9]]]
        >>> _get_all_dimensions(x)
        [[2], [2, 3], [1, 2, 1, 3, 2]]

    """
    if not level:
        res = [[len(batch)]]
    if len(batch) and isinstance(batch[0], Sized) and not isinstance(batch[0], str):
        level += 1
        if len(res) <= level:
            res.append([])
        for item in batch:
            res[level].append(len(item))
            _get_all_dimensions(item, level, res)
    return res 
開發者ID:deepmipt,項目名稱:DeepPavlov,代碼行數:29,代碼來源:utils.py

示例10: from_parameters

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def from_parameters(cls, parameters: Sequence[float]) -> Sized:
        """Construct Robot from Kinematic Chain parameters."""
        # FIXME: assumes MDH revolute robot
        kc = MDHKinematicChain.from_parameters(parameters)
        return cls(kinematic_chain=kc) 
開發者ID:nnadeau,項目名稱:pybotics,代碼行數:7,代碼來源:robot.py

示例11: predict_batch

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        if not self.use_block:
            return np.random.randint(0, high=int(self.n_actions), size=(len(observations),))
        self._i += 1
        return self.noise[:len(observations), self._i % self.samples] 
開發者ID:FragileTech,項目名稱:FractalAI,代碼行數:14,代碼來源:model.py

示例12: _count_values

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def _count_values(dictionary: Dict[str, Sized]) -> int:
        return sum(len(e) for e in dictionary.values()) 
開發者ID:fkie-cad,項目名稱:FACT_core,代碼行數:4,代碼來源:miscellaneous_routes.py

示例13: plot_assignments

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def plot_assignments(
    assignments: torch.Tensor,
    im: Optional[AxesImage] = None,
    figsize: Tuple[int, int] = (5, 5),
    classes: Optional[Sized] = None,
) -> AxesImage:
    # language=rst
    """
    Plot the two-dimensional neuron assignments.

    :param assignments: Vector of neuron label assignments.
    :param im: Used for re-drawing the assignments plot.
    :param figsize: Horizontal, vertical figure size in inches.
    :param classes: Iterable of labels for colorbar ticks corresponding to data labels.
    :return: Used for re-drawing the assigments plot.
    """
    locals_assignments = assignments.detach().clone().cpu().numpy()
    if not im:
        fig, ax = plt.subplots(figsize=figsize)
        ax.set_title("Categorical assignments")

        if classes is None:
            color = plt.get_cmap("RdBu", 11)
            im = ax.matshow(
                locals_assignments, cmap=color, vmin=-1.5, vmax=9.5
            )
        else:
            color = plt.get_cmap("RdBu", len(classes) + 1)
            im = ax.matshow(
                locals_assignments,
                cmap=color,
                vmin=-1.5,
                vmax=len(classes) - 0.5,
            )

        div = make_axes_locatable(ax)
        cax = div.append_axes("right", size="5%", pad=0.05)

        if classes is None:
            cbar = plt.colorbar(im, cax=cax, ticks=list(range(-1, 11)))
            cbar.ax.set_yticklabels(["none"] + list(range(10)))
        else:
            cbar = plt.colorbar(im, cax=cax, ticks=np.arange(-1, len(classes)))
            cbar.ax.set_yticklabels(["none"] + list(classes))

        ax.set_xticks(())
        ax.set_yticks(())
        fig.tight_layout()
    else:
        im.set_data(locals_assignments)

    return im 
開發者ID:BINDS-LAB-UMASS,項目名稱:bindsnet,代碼行數:54,代碼來源:plotting.py


注:本文中的typing.Sized方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。