Python _collections.deque() Examples

The following are 20 code examples for showing how to use _collections.deque(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module _collections , or try the search function .

Example 1
Project: Fluid-Designer   Author: Microvellum   File: threading.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, lock=None):
        if lock is None:
            lock = RLock()
        self._lock = lock
        # Export the lock's acquire() and release() methods
        self.acquire = lock.acquire
        self.release = lock.release
        # If the lock defines _release_save() and/or _acquire_restore(),
        # these override the default implementations (which just call
        # release() and acquire() on the lock).  Ditto for _is_owned().
        try:
            self._release_save = lock._release_save
        except AttributeError:
            pass
        try:
            self._acquire_restore = lock._acquire_restore
        except AttributeError:
            pass
        try:
            self._is_owned = lock._is_owned
        except AttributeError:
            pass
        self._waiters = _deque() 
Example 2
Project: Fluid-Designer   Author: Microvellum   File: threading.py    License: GNU General Public License v3.0 6 votes vote down vote up
def notify(self, n=1):
        """Wake up one or more threads waiting on this condition, if any.

        If the calling thread has not acquired the lock when this method is
        called, a RuntimeError is raised.

        This method wakes up at most n of the threads waiting for the condition
        variable; it is a no-op if no threads are waiting.

        """
        if not self._is_owned():
            raise RuntimeError("cannot notify on un-acquired lock")
        all_waiters = self._waiters
        waiters_to_notify = _deque(_islice(all_waiters, n))
        if not waiters_to_notify:
            return
        for waiter in waiters_to_notify:
            waiter.release()
            try:
                all_waiters.remove(waiter)
            except ValueError:
                pass 
Example 3
Project: Imogen   Author: CedricGuillemet   File: threading.py    License: MIT License 6 votes vote down vote up
def __init__(self, lock=None):
        if lock is None:
            lock = RLock()
        self._lock = lock
        # Export the lock's acquire() and release() methods
        self.acquire = lock.acquire
        self.release = lock.release
        # If the lock defines _release_save() and/or _acquire_restore(),
        # these override the default implementations (which just call
        # release() and acquire() on the lock).  Ditto for _is_owned().
        try:
            self._release_save = lock._release_save
        except AttributeError:
            pass
        try:
            self._acquire_restore = lock._acquire_restore
        except AttributeError:
            pass
        try:
            self._is_owned = lock._is_owned
        except AttributeError:
            pass
        self._waiters = _deque() 
Example 4
Project: Imogen   Author: CedricGuillemet   File: threading.py    License: MIT License 6 votes vote down vote up
def notify(self, n=1):
        """Wake up one or more threads waiting on this condition, if any.

        If the calling thread has not acquired the lock when this method is
        called, a RuntimeError is raised.

        This method wakes up at most n of the threads waiting for the condition
        variable; it is a no-op if no threads are waiting.

        """
        if not self._is_owned():
            raise RuntimeError("cannot notify on un-acquired lock")
        all_waiters = self._waiters
        waiters_to_notify = _deque(_islice(all_waiters, n))
        if not waiters_to_notify:
            return
        for waiter in waiters_to_notify:
            waiter.release()
            try:
                all_waiters.remove(waiter)
            except ValueError:
                pass 
Example 5
Project: ironpython3   Author: IronLanguages   File: threading.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, lock=None):
        if lock is None:
            lock = RLock()
        self._lock = lock
        # Export the lock's acquire() and release() methods
        self.acquire = lock.acquire
        self.release = lock.release
        # If the lock defines _release_save() and/or _acquire_restore(),
        # these override the default implementations (which just call
        # release() and acquire() on the lock).  Ditto for _is_owned().
        try:
            self._release_save = lock._release_save
        except AttributeError:
            pass
        try:
            self._acquire_restore = lock._acquire_restore
        except AttributeError:
            pass
        try:
            self._is_owned = lock._is_owned
        except AttributeError:
            pass
        self._waiters = _deque() 
Example 6
Project: ironpython3   Author: IronLanguages   File: threading.py    License: Apache License 2.0 6 votes vote down vote up
def notify(self, n=1):
        """Wake up one or more threads waiting on this condition, if any.

        If the calling thread has not acquired the lock when this method is
        called, a RuntimeError is raised.

        This method wakes up at most n of the threads waiting for the condition
        variable; it is a no-op if no threads are waiting.

        """
        if not self._is_owned():
            raise RuntimeError("cannot notify on un-acquired lock")
        all_waiters = self._waiters
        waiters_to_notify = _deque(_islice(all_waiters, n))
        if not waiters_to_notify:
            return
        for waiter in waiters_to_notify:
            waiter.release()
            try:
                all_waiters.remove(waiter)
            except ValueError:
                pass 
Example 7
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: threading.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, lock=None):
        if lock is None:
            lock = RLock()
        self._lock = lock
        # Export the lock's acquire() and release() methods
        self.acquire = lock.acquire
        self.release = lock.release
        # If the lock defines _release_save() and/or _acquire_restore(),
        # these override the default implementations (which just call
        # release() and acquire() on the lock).  Ditto for _is_owned().
        try:
            self._release_save = lock._release_save
        except AttributeError:
            pass
        try:
            self._acquire_restore = lock._acquire_restore
        except AttributeError:
            pass
        try:
            self._is_owned = lock._is_owned
        except AttributeError:
            pass
        self._waiters = _deque() 
Example 8
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: threading.py    License: GNU General Public License v3.0 6 votes vote down vote up
def notify(self, n=1):
        """Wake up one or more threads waiting on this condition, if any.

        If the calling thread has not acquired the lock when this method is
        called, a RuntimeError is raised.

        This method wakes up at most n of the threads waiting for the condition
        variable; it is a no-op if no threads are waiting.

        """
        if not self._is_owned():
            raise RuntimeError("cannot notify on un-acquired lock")
        all_waiters = self._waiters
        waiters_to_notify = _deque(_islice(all_waiters, n))
        if not waiters_to_notify:
            return
        for waiter in waiters_to_notify:
            waiter.release()
            try:
                all_waiters.remove(waiter)
            except ValueError:
                pass 
Example 9
Project: VMAttack   Author: anatolikalysch   File: OptimizationViewer.py    License: MIT License 5 votes vote down vote up
def __init__(self, trace, title='Optimizations', **kwargs):
        # context should be a dictionary containing the backward traced result of each relevant register
        super(OptimizationViewer, self).__init__(title)
        self.orig_trace = trace
        self.trace = deepcopy(trace)
        self.undo_stack = deque([deepcopy(trace), deepcopy(trace), deepcopy(trace)], maxlen=3)
        self.opti_map = dict(zip(optimization_names, optimizations))
        self.order = []
        self.foldable_regs = []
        self.save = kwargs.get('save', None) 
Example 10
Project: VMAttack   Author: anatolikalysch   File: OptimizationViewer.py    License: MIT License 5 votes vote down vote up
def __init__(self, trace, title='Optimizations (legacy)', **kwargs):
        # context should be a dictionary containing the backward traced result of each relevant register
        super(OptimizationViewer, self).__init__(title)
        self.orig_trace = trace
        self.trace = deepcopy(trace)
        self.undo_stack = deque([deepcopy(trace), deepcopy(trace), deepcopy(trace)], maxlen=3)
        self.opti_map = dict(zip(optimization_names, optimizations))
        self.order = []
        self.foldable_regs = []
        self.save = kwargs.get('save', None) 
Example 11
Project: VMAttack   Author: anatolikalysch   File: ClusterViewer.py    License: MIT License 5 votes vote down vote up
def __init__(self, clustered_trace, bb_func, ctx_reg_size, title='Clustering Analysis Result (legacy)', save_func=None):
        # context should be a dictionary containing the backward traced result of each relevant register
        super(ClusterViewer, self).__init__(title)
        self.orig_trace = clustered_trace
        self.trace = deepcopy(self.orig_trace)
        self.bb_func = bb_func
        self.ctx_reg_size = ctx_reg_size
        self.save = save_func
        self.undo_stack = deque([deepcopy(self.trace)], maxlen=3) 
Example 12
Project: VMAttack   Author: anatolikalysch   File: ClusterViewer.py    License: MIT License 5 votes vote down vote up
def Restore(self):
        self.undo_stack = deque([deepcopy(self.trace)], maxlen=3)
        self.trace = deepcopy(self.orig_trace)
        self.PopulateModel() 
Example 13
Project: VMAttack   Author: anatolikalysch   File: ClusterViewer.py    License: MIT License 5 votes vote down vote up
def __init__(self, clustered_trace, bb_func, ctx_reg_size, title='Clustering Analysis Result', save_func=None):
        # context should be a dictionary containing the backward traced result of each relevant register
        super(ClusterViewer, self).__init__(title)
        self.orig_trace = clustered_trace
        self.trace = deepcopy(self.orig_trace)
        self.bb_func = bb_func
        self.ctx_reg_size = ctx_reg_size
        self.save = save_func
        self.undo_stack = deque([deepcopy(self.trace)], maxlen=3) 
Example 14
Project: ironpython2   Author: IronLanguages   File: python26.py    License: Apache License 2.0 5 votes vote down vote up
def test_builtin_next():
    from _collections import deque
    values = [1,2,3,4]
    iterable_list = [list, tuple, set, deque]
    
    for iterable in iterable_list:
        i = iter(iterable(values))
        AreEqual(next(i), 1)
        AreEqual(next(i), 2)
        AreEqual(next(i), 3)
        AreEqual(next(i), 4)
        AssertError(StopIteration, next, i)
        
        i = iter(iterable(values))
        AreEqual(next(i, False), 1)
        AreEqual(next(i, False), 2)
        AreEqual(next(i, False), 3)
        AreEqual(next(i, False), 4)
        AreEqual(next(i, False), False)
        AreEqual(next(i, False), False)
    
    i = iter('abcdE')
    AreEqual(next(i), 'a')
    AreEqual(next(i), 'b')
    AreEqual(next(i), 'c')
    AreEqual(next(i), 'd')
    AreEqual(next(i), 'E')
    AssertError(StopIteration, next, i)
    
    i = iter('edcbA')
    AreEqual(next(i, False), 'e')
    AreEqual(next(i, False), 'd')
    AreEqual(next(i, False), 'c')
    AreEqual(next(i, False), 'b')
    AreEqual(next(i, False), 'A')
    AreEqual(next(i, False), False)
    AreEqual(next(i, False), False) 
Example 15
Project: ironpython2   Author: IronLanguages   File: test_isinstance.py    License: Apache License 2.0 5 votes vote down vote up
def test_unhashable_types(self):
        import System
        class OldUserClass:
            def foo(): pass
        import _weakref
        from _collections import deque
        
        self.assertRaises(TypeError, hash, slice(None))
        hashcode = System.Object.GetHashCode(slice(None))
        
        # weakproxy
        self.assertRaises(TypeError, hash, _weakref.proxy(OldUserClass()))
        hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass()))
        
        # weakcallableproxy
        self.assertRaises(TypeError, hash, _weakref.proxy(OldUserClass().foo))
        hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass().foo))
        
        self.assertRaises(TypeError, hash, deque())
        hashcode = System.Object.GetHashCode(deque())
        
        self.assertRaises(TypeError, hash, dict())
        hashcode = System.Object.GetHashCode(dict())
        
        self.assertRaises(TypeError, hash, list())
        hashcode = System.Object.GetHashCode(list())
        
        self.assertRaises(TypeError, hash, set())
        hashcode = System.Object.GetHashCode(set()) 
Example 16
Project: turkish-stemmer-python   Author: otuncelli   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _genericSuffixStripper(self, initialState, word, stems, machine):
        """
        Given the initial state of a state machine, it adds possible stems to a set of stems.

        Args:
        initialState (State): an initial state
        word (str): the word to stem
        stems (set): the set to populate
        machine (str): a string representing the name of the state machine. It is used for debugging reasons only.
        """
        transitions = deque()
        initialState.AddTransitions(word, transitions, False)

        while transitions:
            transition = transitions.popleft()
            wordToStem = transition.word
            stem = self.stemWord(wordToStem, transition.suffix)
            if stem != wordToStem:
                if transition.nextState.finalState:
                    for transitionToRemove in tuple(transitions):
                        if ((transitionToRemove.startState == transition.startState and 
                            transitionToRemove.nextState == transition.nextState) or 
                            transitionToRemove.marked):
                            transitions.remove(transitionToRemove)
                    stems.add(stem)
                    transition.nextState.AddTransitions(stem, transitions, False)
                else:
                    for similarTransition in transition.similarTransitions(transitions):
                        similarTransition.marked = True
                    transition.nextState.AddTransitions(stem, transitions, True) 
Example 17
Project: ironpython3   Author: IronLanguages   File: python26.py    License: Apache License 2.0 5 votes vote down vote up
def test_builtin_next():
    from _collections import deque
    values = [1,2,3,4]
    iterable_list = [list, tuple, set, deque]
    
    for iterable in iterable_list:
        i = iter(iterable(values))
        AreEqual(next(i), 1)
        AreEqual(next(i), 2)
        AreEqual(next(i), 3)
        AreEqual(next(i), 4)
        AssertError(StopIteration, next, i)
        
        i = iter(iterable(values))
        AreEqual(next(i, False), 1)
        AreEqual(next(i, False), 2)
        AreEqual(next(i, False), 3)
        AreEqual(next(i, False), 4)
        AreEqual(next(i, False), False)
        AreEqual(next(i, False), False)
    
    i = iter('abcdE')
    AreEqual(next(i), 'a')
    AreEqual(next(i), 'b')
    AreEqual(next(i), 'c')
    AreEqual(next(i), 'd')
    AreEqual(next(i), 'E')
    AssertError(StopIteration, next, i)
    
    i = iter('edcbA')
    AreEqual(next(i, False), 'e')
    AreEqual(next(i, False), 'd')
    AreEqual(next(i, False), 'c')
    AreEqual(next(i, False), 'b')
    AreEqual(next(i, False), 'A')
    AreEqual(next(i, False), False)
    AreEqual(next(i, False), False) 
Example 18
Project: ironpython3   Author: IronLanguages   File: test_isinstance.py    License: Apache License 2.0 5 votes vote down vote up
def test_unhashable_types(self):
        import System
        class OldUserClass:
            def foo(): pass
        import _weakref
        from _collections import deque

        self.assertRaises(TypeError, hash, slice(None))
        hashcode = System.Object.GetHashCode(slice(None))

        # weakproxy
        self.assertRaises(TypeError, hash, _weakref.proxy(OldUserClass()))
        hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass()))

        # weakcallableproxy
        self.assertRaises(TypeError, hash, _weakref.proxy(OldUserClass().foo))
        hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass().foo))

        self.assertRaises(TypeError, hash, deque())
        hashcode = System.Object.GetHashCode(deque())

        self.assertRaises(TypeError, hash, dict())
        hashcode = System.Object.GetHashCode(dict())

        self.assertRaises(TypeError, hash, list())
        hashcode = System.Object.GetHashCode(list())

        self.assertRaises(TypeError, hash, set())
        hashcode = System.Object.GetHashCode(set()) 
Example 19
Project: ironpython2   Author: IronLanguages   File: test_set.py    License: Apache License 2.0 4 votes vote down vote up
def test_deque(self):
        if is_cli:
            from _collections import deque
        else:
            from collections import deque
        x = deque([2,3,4,5,6])
        x.remove(2)
        self.assertEqual(x, deque([3,4,5,6]))
        x.remove(6)
        self.assertEqual(x, deque([3,4,5]))
        x.remove(4)
        self.assertEqual(x, deque([3,5]))

        # get a deque w/ head/tail backwards...
        x = deque([1,2,3,4,5,6,7,8])
        x.popleft()
        x.popleft()
        x.popleft()
        x.popleft()
        x.append(1)
        x.append(2)
        x.append(3)
        x.append(4)
        self.assertEqual(x, deque([5,6,7,8, 1, 2, 3, 4]))
        x.remove(5)
        self.assertEqual(x, deque([6,7,8, 1, 2, 3, 4]))
        x.remove(4)
        self.assertEqual(x, deque([6,7,8, 1, 2, 3]))
        x.remove(8)
        self.assertEqual(x, deque([6,7,1, 2, 3]))
        x.remove(2)
        self.assertEqual(x, deque([6,7,1, 3]))

        class BadCmp:
            def __eq__(self, other):
                raise RuntimeError

        d = deque([1,2, BadCmp()])
        self.assertRaises(RuntimeError, d.remove, 3)

        x = deque()
        class y(object):
            def __eq__(self, other):
                return True

        x.append(y())
        self.assertEqual(y() in x, True)

        x = deque({}, None)
        self.assertEqual(x, deque([]))

        self.assertRaisesPartialMessage(TypeError, "takes at most 2 arguments (3 given)", deque, 'abc', 2, 2) 
Example 20
Project: ironpython3   Author: IronLanguages   File: test_set.py    License: Apache License 2.0 4 votes vote down vote up
def test_deque(self):
        if is_cli:
            from _collections import deque
        else:
            from collections import deque
        x = deque([2,3,4,5,6])
        x.remove(2)
        self.assertEqual(x, deque([3,4,5,6]))
        x.remove(6)
        self.assertEqual(x, deque([3,4,5]))
        x.remove(4)
        self.assertEqual(x, deque([3,5]))

        # get a deque w/ head/tail backwards...
        x = deque([1,2,3,4,5,6,7,8])
        x.popleft()
        x.popleft()
        x.popleft()
        x.popleft()
        x.append(1)
        x.append(2)
        x.append(3)
        x.append(4)
        self.assertEqual(x, deque([5,6,7,8, 1, 2, 3, 4]))
        x.remove(5)
        self.assertEqual(x, deque([6,7,8, 1, 2, 3, 4]))
        x.remove(4)
        self.assertEqual(x, deque([6,7,8, 1, 2, 3]))
        x.remove(8)
        self.assertEqual(x, deque([6,7,1, 2, 3]))
        x.remove(2)
        self.assertEqual(x, deque([6,7,1, 3]))

        class BadCmp:
            def __eq__(self, other):
                raise RuntimeError

        d = deque([1,2, BadCmp()])
        self.assertRaises(RuntimeError, d.remove, 3)

        x = deque()
        class y(object):
            def __eq__(self, other):
                return True

        x.append(y())
        self.assertEqual(y() in x, True)

        x = deque({}, None)
        self.assertEqual(x, deque([]))

        self.assertRaisesPartialMessage(TypeError, "takes at most 2 arguments (3 given)", deque, 'abc', 2, 2)