コード例 #1
0
ファイル: gym_spaces.py プロジェクト: ivannz/rlplay
def patch_spaces_tuple_Tuple():
    # Sequence: `__getitem__`
    #   Reversible:  `__reversed__`*
    #   Collection:
    #     Sized: `__len__`
    #     Iterable: `__iter__`*
    #     Container: `__contains__`*
    # * [optional] Based on `__len__` and `__getitem__` (which should raise
    #   IndexError), Sequence provides generic slow-ish implementations of
    #   `__iter__`, `__contains__` and `__reversed__`.

    spaces_tuple = importlib.import_module('gym.spaces.tuple')

    # patch the missing methods into the class prototype
    spaces_tuple.Tuple.__len__ = __len__
    spaces_tuple.Tuple.__iter__ = __iter__

    # declare Sequence as a virtual base class of Tuple
    Sequence.register(spaces_tuple.Tuple)
コード例 #2
0
ファイル: _jcollection.py プロジェクト: KaiTyrusNelson/jpype
 def __jclass_init__(self):
     Sequence.register(self)
     MutableSequence.register(self)
コード例 #3
0
    def remove(self, value):
        """
        Remove the first occurrence of a value from the vector.

        >>> v1 = v(1, 2, 3, 2, 1)
        >>> v2 = v1.remove(1)
        >>> v2
        pvector([2, 3, 2, 1])
        >>> v2.remove(1)
        pvector([2, 3, 2])
        """


_EMPTY_PVECTOR = PythonPVector(0, SHIFT, [], [])
PVector.register(PythonPVector)
Sequence.register(PVector)
Hashable.register(PVector)


def python_pvector(iterable=()):
    """
    Create a new persistent vector containing the elements in iterable.

    >>> v1 = pvector([1, 2, 3])
    >>> v1
    pvector([1, 2, 3])
    """
    return _EMPTY_PVECTOR.extend(iterable)


try:
コード例 #4
0
    def __reversed__(self):
        # type: () -> Iterable
        return reversed(self.data)

    def __getitem__(self, index):
        # type: (Any) -> Any
        return self.data[index]

    @property
    def _evictcount(self):
        # type: () -> int
        return len(self)


Sequence.register(Messagebuffer)  # noqa: E305


@python_2_unicode_compatible
class BufferMap(OrderedDict, Evictable):
    """Map of buffers."""

    Buffer = Messagebuffer
    Empty = Empty

    maxsize = None
    total = 0
    bufmaxsize = None

    def __init__(self, maxsize, iterable=None, bufmaxsize=1000):
        # type: (int, Iterable, int) -> None
コード例 #5
0
    def __reversed__(self):
        # type: () -> Iterable
        return reversed(self.data)

    def __getitem__(self, index):
        # type: (Any) -> Any
        return self.data[index]

    @property
    def _evictcount(self):
        # type: () -> int
        return len(self)


Sequence.register(Messagebuffer)  # noqa: E305


@python_2_unicode_compatible
class BufferMap(OrderedDict, Evictable):
    """Map of buffers."""

    Buffer = Messagebuffer
    Empty = Empty

    maxsize = None
    total = 0
    bufmaxsize = None

    def __init__(self, maxsize, iterable=None, bufmaxsize=1000):
        # type: (int, Iterable, int) -> None
コード例 #6
0
            raise TypeError("'%s' object cannot be interpreted as an index" %
                            type(index).__name__)

        if index >= 0:
            return self.popleft(index).left

        shifted = len(self) + index
        if shifted < 0:
            raise IndexError(
                "pdeque index {0} out of range {1}".format(index, len(self)), )
        return self.popleft(shifted).left

    index = Sequence.index


Sequence.register(PDeque)
Hashable.register(PDeque)


def pdeque(iterable=(), maxlen=None):
    """
    Return deque containing the elements of iterable. If maxlen is specified then
    len(iterable) - maxlen elements are discarded from the left to if len(iterable) > maxlen.

    >>> pdeque([1, 2, 3])
    pdeque([1, 2, 3])
    >>> pdeque([1, 2, 3, 4], maxlen=2)
    pdeque([3, 4], maxlen=2)
    """
    t = tuple(iterable)
    if maxlen is not None:
コード例 #7
0
    def __reversed__(self):
        # type: () -> Iterable
        return reversed(self.data)

    def __getitem__(self, index):
        # type: (Any) -> Any
        return self.data[index]

    @property
    def _evictcount(self):
        # type: () -> int
        return len(self)


Sequence.register(Messagebuffer)


class BufferMap(OrderedDict, Evictable):
    """Map of buffers."""

    Buffer = Messagebuffer
    Empty = Empty

    maxsize = None
    total = 0
    bufmaxsize = None

    def __init__(self, maxsize, iterable=None, bufmaxsize=1000):
        # type: (int, Iterable, int) -> None
        super().__init__()
コード例 #8
0
else:
    from collections import Iterable, Sequence
# Register extension classes that look like a sequence, ie. have a
# length and adressable elements, as a Sequence. Same for Iterable.
for entry in ext.__dict__.values():
    # Only consider types (=classes), not object instances
    if not isinstance(entry, type): continue
    # The Iterable interface means the type contains retrievable items.
    # If the type fulfills this but is not already a known Iterable then
    # register it as such.
    if hasattr(entry, "__getitem__") and not issubclass(entry, Iterable):
        Iterable.register(entry)
    # A Sequence is an Iterable that also has a determinable length.
    if hasattr(entry, "__getitem__") and hasattr(entry, "__len__") \
        and not issubclass(entry, Sequence):
        Sequence.register(entry)


def bool_md5(self):
    return hashlib.md5(self.__getstate__()[1])


bool.md5 = bool_md5


@boost.python.inject_into(grid)
class _():
    def show_summary(self, f=None):
        if (f is None): f = sys.stdout
        print("origin:", self.origin(), file=f)
        print("last:", self.last(), file=f)
コード例 #9
0
ファイル: vector2.py プロジェクト: pathunstrom/ppb-vector
    def truncate(self: VectorOrSub, max_length: Realish) -> VectorOrSub:
        if self.length > max_length:
            return self.scale_to(max_length)
        return self

    def scale_to(self: VectorOrSub, length: Realish) -> VectorOrSub:
        """
        Scale the vector to the given length
        """
        try:
            scale = length / self.length
        except ZeroDivisionError:
            scale = 1
        return self.scale_by(scale)

    scale = scale_to

    def reflect(self: VectorOrSub, surface_normal: VectorLike) -> VectorOrSub:
        """
        Calculate the reflection of the vector against a given surface normal
        """
        surface_normal = Vector2.convert(surface_normal)
        if not isclose(surface_normal.length, 1):
            raise ValueError("Reflection requires a normalized vector.")

        return self - (2 * (self * surface_normal) * surface_normal)


Sequence.register(Vector2)
コード例 #10
0
ファイル: __init__.py プロジェクト: jianshu93/pyrodigal
from collections.abc import Sequence as _Sequence

from . import _pyrodigal
from ._pyrodigal import Gene, Genes, Pyrodigal

__all__ = ["Gene", "Genes", "Pyrodigal"]
__doc__ = _pyrodigal.__doc__

__author__ = "Martin Larralde <*****@*****.**>"
__license__ = "GPLv3"
__version__ = "0.3.2"

_Sequence.register(Genes)
コード例 #11
0
KeysView.register(EmptySet)
ItemsView.register(EmptySet)
ValuesView.register(EmptyCollection)
assert issubclass(EmptySet, KeysView)
assert issubclass(EmptySet, ItemsView)
assert issubclass(EmptySet, Set)
assert issubclass(EmptySet, MappingView)
assert issubclass(EmptyCollection, ValuesView)
assert issubclass(EmptyCollection, Collection)
assert issubclass(EmptyCollection, MappingView)



Mapping.register(EmptyMapping)
Set.register(EmptySet)
Sequence.register(EmptySequence)
assert issubclass(EmptyMapping, Mapping)
assert issubclass(EmptySet, Set)
assert issubclass(EmptySequence, Sequence)

if 0:
    Mapping.register(EmptyThree)
    Set.register(EmptyThree)
    Sequence.register(EmptyThree)
assert issubclass(EmptyThree, Mapping)
assert issubclass(EmptyThree, Set)
assert issubclass(EmptyThree, Sequence)



コード例 #12
0
    @classmethod
    def from_sequence_range(cls, seq, range_or_slice):
        return cls(seq, range_or_slice)

    def __len__(self):
        return len(self.__rng)

    def __iter__(self):
        return map(self.__seq.__getitem__, self.__rng)

    def __reversed__(self):
        return map(self.__seq.__getitem__, reversed(self.__rng))


'''
Sequence.register(int)
Sequence.register(range)
assert not isinstance(int, Sequence)
assert isinstance(range, Sequence) ??????? why fail????
'''


def t():
    ls = SeqSliceView([1, 2, 3, 4, 5, 6, 7], range(1, 6, 2))
    ls2 = SeqSliceView(ls, slice(-1, None, -1))
    assert repr(ls2) == 'SeqSliceView([1, 2, 3, 4, 5, 6, 7], range(5, -1, -2))'


if __name__ == "__main__":
    t()
コード例 #13
0
    """
    __slots__ = ('first', 'rest')

    def __new__(cls, first, rest):
        instance = super(PList, cls).__new__(cls)
        instance.first = first
        instance.rest = rest
        return instance

    def __bool__(self):
        return True

    __nonzero__ = __bool__


Sequence.register(PList)
Hashable.register(PList)


class _EmptyPList(_PListBase):
    __slots__ = ()

    def __bool__(self):
        return False

    __nonzero__ = __bool__

    @property
    def first(self):
        raise AttributeError("Empty PList has no first")