text:
"""
Tests for lots of functionality provided by L{twisted.internet}.
"""

import os
import sys
import time

from twisted.trial import unittest
from twisted.internet import reactor, protocol, error, abstract, defer
from twisted.internet import interfaces, base

try:
    from twisted.internet import ssl
except ImportError:
    ssl = None
if ssl and not ssl.supported:
    ssl = None

from twisted.internet.defer import Deferred, maybeDeferred
from twisted.python import util, runtime

class ThreePhaseEventTests(unittest.TestCase):
    """
    Tests for the private implementation helpers for system event triggers.
    """
    def setUp(self):
        """
        Create a trigger, an argument, and an event to be used by tests.
        """
        self.trigger = lambda x: None
        self.arg = object()
        self.event = base._ThreePhaseEvent()

    def test_addInvalidPhase(self):
        """
        L{_ThreePhaseEvent.addTrigger} should raise L{KeyError} when called
        with an invalid phase.
        """
        self.assertRaises(
            KeyError,
            self.event.addTrigger, 'xxx', self.trigger, self.arg)

    def test_addBeforeTrigger(self):
        """
        L{_ThreePhaseEvent.addTrigger} should accept C{'before'} as a phase, a
        callable, and some arguments and add the callable with the arguments to
        the before list.
        """
        self.event.addTrigger('before', self.trigger, self.arg)
        self.assertEqual(
            self.event.before,
            [(self.trigger, (self.arg,), {})])

    def test_addDuringTrigger(self):
        """
        L{_ThreePhaseEvent.addTrigger} should accept C{'during'} as a phase, a
        callable, and some arguments and add the callable with the arguments to
        the during list.
        """
        self.event.addTrigger('during', self.trigger, self.arg)
        self.assertEqual(
            self.event.during,
            [(self.trigger, (self.arg,), {})])

    def test_addAfterTrigger(self):
        """
        L{_ThreePhaseEvent.addTrigger} should accept C{'after'} as a phase, a
        callable, and some arguments and add the callable with the arguments to
        the after list.
        """
        self.event.addTrigger('after', self.trigger, self.arg)
        self.assertEqual(
            self.event.after,
            [(self.trigger, (self.arg,), {})])

    def test_removeTrigger(self):
        """
        L{_ThreePhaseEvent.removeTrigger} should accept an opaque object
        previously returned by L{_ThreePhaseEvent.addTrigger} and remove the
        associated trigger.
        """
        handle = self.event.addTrigger('before', self.trigger, self.arg)
        self.event.removeTrigger(handle)
        self.assertEqual(self.event.before, [])

    def test_removeNonexistentTrigger(self):
        """
        L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} when given
        an object not previously returned by L{_ThreePhaseEvent.addTrigger}.
        """
        self.assertRaises(ValueError, self.event.removeTrigger, object())

    def test_removeRemovedTrigger(self):
        """
        L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} the second
        time it is called with an object returned by
        L{_ThreePhaseEvent.addTrigger}.
        """
        handle = self.event.addTrigger('before', self.trigger, self.arg)
        self.event.removeTrigger(handle)
        self.assertRaises(ValueError, self.event.removeTrigger, handle)

    def test_removeAlmostValidTrigger(self):
        """
        L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} if it is
        given a trigger handle which resembles a valid trigger handle aside
        from its phase being incorrect.
        """
        self.assertRaises(
            KeyError,
            self.event.removeTrigger, ('xxx', self.trigger, (self.arg,), {}))

    def test_fireEvent(self):
        """
        L{_ThreePhaseEvent.fireEvent} should call I{before}, I{during}, and
        I{after} phase triggers in that order.
        """
        events = []
        self.event.addTrigger('after', events.append, ('first', 'after'))
        self.event.addTrigger('during', events.append, ('first', 'during'))
        self.event.addTrigger('before', events.append, ('first', 'before'))
        self.event.addTrigger('before', events.append, ('second', 'before'))
        self.event.addTrigger('during', events.append, ('second', 'during'))
        self.event.addTrigger('after', events.append, ('second', 'after'))

        self.assertEqual(events, [])
        self.event.fireEvent()
        self.assertEqual(events,
                         [('first', 'before'), ('second', 'before'),
                          ('first', 'during'), ('second', 'during'),
                          ('first', 'after'), ('second', 'after')])

    def test_asynchronousBefore(self):
        """
        L{_ThreePhaseEvent.fireEvent} should wait for any L{Deferred} returned
        by a I{before} phase trigger before proceeding to I{during} events.
        """
        events = []
        beforeResult = Deferred()
        self.event.addTrigger('before', lambda: beforeResult)
        self.event.addTrigger('during', events.append, 'during')
        self.event.addTrigger('after', events.append, 'after')

        self.assertEqual(events, [])
        self.event.fireEvent()
        self.assertEqual(events, [])
        beforeResult.callback(None)
        self.assertEqual(events, ['during', 'after'])

    def test_beforeTriggerException(self):
        """
        If a before-phase trigger raises a synchronous exception, it should be
        logged and the remaining triggers should be run.
        """
        events = []

        class DummyException(Exception):
            pass

        def raisingTrigger():
            raise DummyException()

        self.event.addTrigger('before', raisingTrigger)
        self.event.addTrigger('before', events.append, 'before')
        self.event.addTrigger('during', events.append, 'during')
        self.event.fireEvent()
        self.assertEqual(events, ['before', 'during'])
        errors = self.flushLoggedErrors(DummyException)
        self.assertEqual(len(errors), 1)

    def test_duringTriggerException(self):
        """
        If a during-phase trigger raises a synchronous exception, it should be
        logged and the remaining triggers should be run.
        """
        events = []

        class DummyException(Exception):
            pass

        def raisingTrigger():
            raise DummyException()

        self.event.addTrigger('during', raisingTrigger)
        self.event.addTrigger('during', events.append, 'during')
        self.event.addTrigger('after', events.append, 'after')
        self.event.fireEvent()
        self.assertEqual(events, ['during', 'after'])
        errors = self.flushLoggedErrors(DummyException)
        self.assertEqual(len(errors), 1)

    def test_synchronousRemoveAlreadyExecutedBefore(self):
        """
        If a before-phase trigger tries to remove another before-phase trigger
        which has already run, a warning should be emitted.
        """
        events = []

        def removeTrigger():
            self.event.removeTrigger(beforeHandle)

        beforeHandle = self.event.addTrigger('before', events.append, ('first', 'before'))
        self.event.addTrigger('before', removeTrigger)
        self.event.addTrigger('before', events.append, ('second', 'before'))
        self.assertWarns(
            DeprecationWarning,
            "Removing already-fired system event triggers will raise an "
            "exception in a future version of Twisted.",
            __file__,
            self.event.fireEvent)
        self.assertEqual(events, [('first', 'before'), ('second', 'before')])

    def test_synchronousRemovePendingBefore(self):
        """
        If a before-phase trigger removes another before-phase trigger which
        has not yet run, the removed trigger should not be run.
        """
        events = []
        self.event.addTrigger(
            'before', lambda: self.event.removeTrigger(beforeHandle))
        beforeHandle = self.event.addTrigger(
            'before', events.append, ('first', 'before'))
        self.event.addTrigger('before', events.append, ('second', 'before'))
        self.event.fireEvent()
        self.assertEqual(events, [('second', 'before')])

    def test_synchronousBeforeRemovesDuring(self):
        """
        If a before-phase trigger removes a during-phase trigger, the
        during-phase trigger should not be run.
        """
        events = []
        self.event.addTrigger(
            'before', lambda: self.event.removeTrigger(duringHandle))
        duringHandle = self.event.addTrigger('during', events.append, 'during')
        self.event.addTrigger('after', events.append, 'after')
        self.event.fireEvent()
        self.assertEqual(events, ['after'])

    def test_asynchronousBeforeRemovesDuring(self):
        """
        If a before-phase trigger returns a L{Deferred} and later removes a
        during-phase trigger before the L{Deferred} fires, the during-phase
        trigger should not be run.
        """
        events = []
        beforeResult = Deferred()
        self.event.addTrigger('before', lambda: beforeResult)
        duringHandle = self.event.addTrigger('during', events.append, 'during')
        self.event.addTrigger('after', events.append, 'after')
        self.event.fireEvent()
        self.event.removeTrigger(duringHandle)
        beforeResult.callback(None)
        self.assertEqual(events, ['after'])

    def test_synchronousBeforeRemovesConspicuouslySimilarDuring(self):
        """
        If a before-phase trigger removes a during-phase trigger which is
        identical to an already-executed before-phase trigger aside from their
        phases, no warning should be emitted and the during-phase trigger
        should not be run.
        """
        events = []
        def trigger():
            events.append('trigger')
        self.event.addTrigger('before', trigger)
        self.event.addTrigger(
            'before', lambda: self.event.removeTrigger(duringTrigger))
        duringTrigger = self.event.addTrigger('during', trigger)
        self.event.fireEvent()
        self.assertEqual(events, ['trigger'])

    def test_synchronousRemovePendingDuring(self):
        """
        If a during-phase trigger removes another during-phase trigger which
        has not yet run, the removed trigger should not be run.
        """
        events = []
        self.event.addTrigger(
            'during', lambda: self.event.removeTrigger(duringHandle))
        duringHandle = self.event.addTrigger(
            'during', events.append, ('first', 'during'))
        self.event.addTrigger(
            'during', events.append, ('second', 'during'))
        self.event.fireEvent()
        self.assertEqual(events, [('second', 'during')])

    def test_triggersRunOnce(self):
        """
        A trigger should only be called on the first call to
        L{_ThreePhaseEvent.fireEvent}.
        """
        events = []
        self.event.addTrigger('before', events.append, 'before')
        self.event.addTrigger('during', events.append, 'during')
        self.event.addTrigger('after', events.append, 'after')
        self.event.fireEvent()
        self.event.fireEvent()
        self.assertEqual(events, ['before', 'during', 'after'])

    def test_finishedBeforeTriggersCleared(self):
        """
        The temporary list L{_ThreePhaseEvent.finishedBefore} should be emptied
        and the state reset to C{'BASE'} before the first during-phase trigger
        executes.
        """
        events = []
        def duringTrigger():
            events.append('during')
            self.assertEqual(self.event.finishedBefore, [])
            self.assertEqual(self.event.state, 'BASE')
        self.event.addTrigger('before', events.append, 'before')
        self.event.addTrigger('during', duringTrigger)
        self.event.fireEvent()
        self.assertEqual(events, ['before', 'during'])

class SystemEventTestCase(unittest.TestCase):
    """
    Tests for the reactor's implementation of the C{fireSystemEvent},
    C{addSystemEventTrigger}, and C{removeSystemEventTrigger} methods of the
    L{IReactorCore} interface.

    @ivar triggers: A list of the handles to triggers which have been added to
        the reactor.
    """
    def setUp(self):
        """
        Create an empty list in which to store trigger handles.
        """
        self.triggers = []

    def tearDown(self):
        """
        Remove all remaining triggers from the reactor.
        """
        while self.triggers:
            trigger = self.triggers.pop()
            try:
                reactor.removeSystemEventTrigger(trigger)
            except (ValueError, KeyError):
                pass

    def addTrigger(self, event, phase, func):
        """
        Add a trigger to the reactor and remember it in C{self.triggers}.
        """
        t = reactor.addSystemEventTrigger(event, phase, func)
        self.triggers.append(t)
        return t

    def removeTrigger(self, trigger):
        """
        Remove a trigger by its handle from the reactor and from
        C{self.triggers}.
        """
        reactor.removeSystemEventTrigger(trigger)
        self.triggers.remove(trigger)

    def _addSystemEventTriggerTest(self, phase):
        eventType = 'test'
        events = []
        def trigger():
            events.append(None)
        self.addTrigger(phase, eventType, trigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, [None])

    def test_beforePhase(self):
        """
        L{IReactorCore.addSystemEventTrigger} should accept the C{'before'}
        phase and not call the given object until the right event is fired.
        """
        self._addSystemEventTriggerTest('before')

    def test_duringPhase(self):
        """
        L{IReactorCore.addSystemEventTrigger} should accept the C{'during'}
        phase and not call the given object until the right event is fired.
        """
        self._addSystemEventTriggerTest('during')

    def test_afterPhase(self):
        """
        L{IReactorCore.addSystemEventTrigger} should accept the C{'after'}
        phase and not call the given object until the right event is fired.
        """
        self._addSystemEventTriggerTest('after')

    def test_unknownPhase(self):
        """
        L{IReactorCore.addSystemEventTrigger} should reject phases other than
        C{'before'}, C{'during'}, or C{'after'}.
        """
        eventType = 'test'
        self.assertRaises(
            KeyError, self.addTrigger, 'xxx', eventType, lambda: None)

    def test_beforePreceedsDuring(self):
        """
        L{IReactorCore.addSystemEventTrigger} should call triggers added to the
        C{'before'} phase before it calls triggers added to the C{'during'}
        phase.
        """
        eventType = 'test'
        events = []
        def beforeTrigger():
            events.append('before')
        def duringTrigger():
            events.append('during')
        self.addTrigger('before', eventType, beforeTrigger)
        self.addTrigger('during', eventType, duringTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['before', 'during'])

    def test_duringPreceedsAfter(self):
        """
        L{IReactorCore.addSystemEventTrigger} should call triggers added to the
        C{'during'} phase before it calls triggers added to the C{'after'}
        phase.
        """
        eventType = 'test'
        events = []
        def duringTrigger():
            events.append('during')
        def afterTrigger():
            events.append('after')
        self.addTrigger('during', eventType, duringTrigger)
        self.addTrigger('after', eventType, afterTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['during', 'after'])

    def test_beforeReturnsDeferred(self):
        """
        If a trigger added to the C{'before'} phase of an event returns a
        L{Deferred}, the C{'during'} phase should be delayed until it is called
        back.
        """
        triggerDeferred = Deferred()
        eventType = 'test'
        events = []
        def beforeTrigger():
            return triggerDeferred
        def duringTrigger():
            events.append('during')
        self.addTrigger('before', eventType, beforeTrigger)
        self.addTrigger('during', eventType, duringTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, [])
        triggerDeferred.callback(None)
        self.assertEqual(events, ['during'])

    def test_multipleBeforeReturnDeferred(self):
        """
        If more than one trigger added to the C{'before'} phase of an event
        return L{Deferred}s, the C{'during'} phase should be delayed until they
        are all called back.
        """
        firstDeferred = Deferred()
        secondDeferred = Deferred()
        eventType = 'test'
        events = []
        def firstBeforeTrigger():
            return firstDeferred
        def secondBeforeTrigger():
            return secondDeferred
        def duringTrigger():
            events.append('during')
        self.addTrigger('before', eventType, firstBeforeTrigger)
        self.addTrigger('before', eventType, secondBeforeTrigger)
        self.addTrigger('during', eventType, duringTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, [])
        firstDeferred.callback(None)
        self.assertEqual(events, [])
        secondDeferred.callback(None)
        self.assertEqual(events, ['during'])

    def test_subsequentBeforeTriggerFiresPriorBeforeDeferred(self):
        """
        If a trigger added to the C{'before'} phase of an event calls back a
        L{Deferred} returned by an earlier trigger in the C{'before'} phase of
        the same event, the remaining C{'before'} triggers for that event
        should be run and any further L{Deferred}s waited on before proceeding
        to the C{'during'} events.
        """
        eventType = 'test'
        events = []
        firstDeferred = Deferred()
        secondDeferred = Deferred()
        def firstBeforeTrigger():
            return firstDeferred
        def secondBeforeTrigger():
            firstDeferred.callback(None)
        def thirdBeforeTrigger():
            events.append('before')
            return secondDeferred
        def duringTrigger():
            events.append('during')
        self.addTrigger('before', eventType, firstBeforeTrigger)
        self.addTrigger('before', eventType, secondBeforeTrigger)
        self.addTrigger('before', eventType, thirdBeforeTrigger)
        self.addTrigger('during', eventType, duringTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['before'])
        secondDeferred.callback(None)
        self.assertEqual(events, ['before', 'during'])

    def test_removeSystemEventTrigger(self):
        """
        A trigger removed with L{IReactorCore.removeSystemEventTrigger} should
        not be called when the event fires.
        """
        eventType = 'test'
        events = []
        def firstBeforeTrigger():
            events.append('first')
        def secondBeforeTrigger():
            events.append('second')
        self.addTrigger('before', eventType, firstBeforeTrigger)
        self.removeTrigger(
            self.addTrigger('before', eventType, secondBeforeTrigger))
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['first'])

    def test_removeNonExistentSystemEventTrigger(self):
        """
        Passing an object to L{IReactorCore.removeSystemEventTrigger} which was
        not returned by a previous call to
        L{IReactorCore.addSystemEventTrigger} or which has already been passed
        to C{removeSystemEventTrigger} should result in L{TypeError},
        L{KeyError}, or L{ValueError} being raised.
        """
        b = self.addTrigger('during', 'test', lambda: None)
        self.removeTrigger(b)
        self.assertRaises(
            TypeError, reactor.removeSystemEventTrigger, None)
        self.assertRaises(
            ValueError, reactor.removeSystemEventTrigger, b)
        self.assertRaises(
            KeyError,
            reactor.removeSystemEventTrigger,
            (b[0], ('xxx',) + b[1][1:]))

    def test_interactionBetweenDifferentEvents(self):
        """
        L{IReactorCore.fireSystemEvent} should behave the same way for a
        particular system event regardless of whether Deferreds are being
        waited on for a different system event.
        """
        events = []

        firstEvent = 'first-event'
        firstDeferred = Deferred()
        def beforeFirstEvent():
            events.append(('before', 'first'))
            return firstDeferred
        def afterFirstEvent():
            events.append(('after', 'first'))

        secondEvent = 'second-event'
        secondDeferred = Deferred()
        def beforeSecondEvent():
            events.append(('before', 'second'))
            return secondDeferred
        def afterSecondEvent():
            events.append(('after', 'second'))

        self.addTrigger('before', firstEvent, beforeFirstEvent)
        self.addTrigger('after', firstEvent, afterFirstEvent)
        self.addTrigger('before', secondEvent, beforeSecondEvent)
        self.addTrigger('after', secondEvent, afterSecondEvent)

        self.assertEqual(events, [])

        # After this, firstEvent should be stuck before 'during' waiting for
        # firstDeferred.
        reactor.fireSystemEvent(firstEvent)
        self.assertEqual(events, [('before', 'first')])

        # After this, secondEvent should be stuck before 'during' waiting for
        # secondDeferred.
        reactor.fireSystemEvent(secondEvent)
        self.assertEqual(events, [('before', 'first'), ('before', 'second')])

        # After this, firstEvent should have finished completely, but
        # secondEvent should be at the same place.
        firstDeferred.callback(None)
        self.assertEqual(events, [('before', 'first'), ('before', 'second'),
                                  ('after', 'first')])

        # After this, secondEvent should have finished completely.
        secondDeferred.callback(None)
        self.assertEqual(events, [('before', 'first'), ('before', 'second'),
                                  ('after', 'first'), ('after', 'second')])

class TimeTestCase(unittest.TestCase):
    """
    Tests for the IReactorTime part of the reactor.
    """

    def test_seconds(self):
        """
        L{twisted.internet.reactor.seconds} should return something
        like a number.

        1. This test specifically does not assert any relation to the
           "system time" as returned by L{time.time} or
           L{twisted.python.runtime.seconds}, because at some point we
           may find a better option for scheduling calls than
           wallclock-time.
        2. This test *also* does not assert anything about the type of
           the result, because operations may not return ints or
           floats: For example, datetime-datetime == timedelta(0).
        """
        now = reactor.seconds()
        self.assertEqual(now-now+now, now)

    def test_callLaterUsesReactorSecondsInDelayedCall(self):
        """
        L{reactor.callLater} should use the reactor's seconds factory
        to produce the time at which the DelayedCall will be called.
        """
        oseconds = reactor.seconds
        reactor.seconds = lambda: 100
        try:
            call = reactor.callLater(5, lambda: None)
            self.assertEqual(call.getTime(), 105)
        finally:
            reactor.seconds = oseconds

    def test_callLaterUsesReactorSecondsAsDelayedCallSecondsFactory(self):
        """
        L{reactor.callLater} should propagate its own seconds factory
        to the DelayedCall to use as its own seconds factory.
        """
        oseconds = reactor.seconds
        reactor.seconds = lambda: 100
        try:
            call = reactor.callLater(5, lambda: None)
            self.assertEqual(call.seconds(), 100)
        finally:
            reactor.seconds = oseconds

    def test_callLater(self):
        """
        Test that a DelayedCall really calls the function it is
        supposed to call.
        """
        d = Deferred()
        reactor.callLater(0, d.callback, None)
        d.addCallback(self.assertEqual, None)
        return d

    def test_cancelDelayedCall(self):
        """
        Test that when a DelayedCall is cancelled it does not run.
        """
        called = []
        def function():
            called.append(None)
        call = reactor.callLater(0, function)
        call.cancel()

        # Schedule a call in two "iterations" to check to make sure that the
        # above call never ran.
        d = Deferred()
        def check():
            try:
                self.assertEqual(called, [])
            except:
                d.errback()
            else:
                d.callback(None)
        reactor.callLater(0, reactor.callLater, 0, check)
        return d

    def test_cancelCancelledDelayedCall(self):
        """
        Test that cancelling a DelayedCall which has already been cancelled
        raises the appropriate exception.
        """
        call = reactor.callLater(0, lambda: None)
        call.cancel()
        self.assertRaises(error.AlreadyCancelled, call.cancel)

    def test_cancelCalledDelayedCallSynchronous(self):
        """
        Test that cancelling a DelayedCall in the DelayedCall's function as
        that function is being invoked by the DelayedCall raises the
        appropriate exception.
        """
        d = Deferred()
        def later():
            try:
                self.assertRaises(error.AlreadyCalled, call.cancel)
            except:
                d.errback()
            else:
                d.callback(None)
        call = reactor.callLater(0, later)
        return d

    def test_cancelCalledDelayedCallAsynchronous(self):
        """
        Test that cancelling a DelayedCall after it has run its function
        raises the appropriate exception.
        """
        d = Deferred()
        def check():
            try:
                self.assertRaises(error.AlreadyCalled, call.cancel)
            except:
                d.errback()
            else:
                d.callback(None)
        def later():
            reactor.callLater(0, check)
        call = reactor.callLater(0, later)
        return d

    def testCallLaterTime(self):
        d = reactor.callLater(10, lambda: None)
        try:
            self.failUnless(d.getTime() - (time.time() + 10) < 1)
        finally:
            d.cancel()

    def testCallLaterOrder(self):
        l = []
        l2 = []
        def f(x):
            l.append(x)
        def f2(x):
            l2.append(x)
        def done():
            self.assertEqual(l, range(20))
        def done2():
            self.assertEqual(l2, range(10))

        for n in range(10):
            reactor.callLater(0, f, n)
        for n in range(10):
            reactor.callLater(0, f, n+10)
            reactor.callLater(0.1, f2, n)

        reactor.callLater(0, done)
        reactor.callLater(0.1, done2)
        d = Deferred()
        reactor.callLater(0.2, d.callback, None)
        return d

    testCallLaterOrder.todo = "See bug 1396"
    testCallLaterOrder.skip = "Trial bug, todo doesn't work! See bug 1397"
    def testCallLaterOrder2(self):
        # This time destroy the clock resolution so that it fails reliably
        # even on systems that don't have a crappy clock resolution.

        def seconds():
            return int(time.time())

        base_original = base.seconds
        runtime_original = runtime.seconds
        base.seconds = seconds
        runtime.seconds = seconds

        def cleanup(x):
            runtime.seconds = runtime_original
            base.seconds = base_original
            return x
        return maybeDeferred(self.testCallLaterOrder).addBoth(cleanup)

    testCallLaterOrder2.todo = "See bug 1396"
    testCallLaterOrder2.skip = "Trial bug, todo doesn't work! See bug 1397"

    def testDelayedCallStringification(self):
        # Mostly just make sure str() isn't going to raise anything for
        # DelayedCalls within reason.
        dc = reactor.callLater(0, lambda x, y: None, 'x', y=10)
        str(dc)
        dc.reset(5)
        str(dc)
        dc.cancel()
        str(dc)

        dc = reactor.callLater(0, lambda: None, x=[({'hello': u'world'}, 10j), reactor], *range(10))
        str(dc)
        dc.cancel()
        str(dc)

        def calledBack(ignored):
            str(dc)
        d = Deferred().addCallback(calledBack)
        dc = reactor.callLater(0, d.callback, None)
        str(dc)
        return d

    def testDelayedCallSecondsOverride(self):
        """
        Test that the C{seconds} argument to DelayedCall gets used instead of
        the default timing function, if it is not None.
        """
        def seconds():
            return 10
        dc = base.DelayedCall(5, lambda: None, (), {}, lambda dc: None,
                              lambda dc: None, seconds)
        self.assertEqual(dc.getTime(), 5)
        dc.reset(3)
        self.assertEqual(dc.getTime(), 13)

class CallFromThreadTests(unittest.TestCase):
    def testWakeUp(self):
        # Make sure other threads can wake up the reactor
        d = Deferred()
        def wake():
            time.sleep(0.1)
            # callFromThread will call wakeUp for us
            reactor.callFromThread(d.callback, None)
        reactor.callInThread(wake)
        return d

    if interfaces.IReactorThreads(reactor, None) is None:
        testWakeUp.skip = "Nothing to wake up for without thread support"

    def _stopCallFromThreadCallback(self):
        self.stopped = True

    def _callFromThreadCallback(self, d):
        reactor.callFromThread(self._callFromThreadCallback2, d)
        reactor.callLater(0, self._stopCallFromThreadCallback)

    def _callFromThreadCallback2(self, d):
        try:
            self.assert_(self.stopped)
        except:
            # Send the error to the deferred
            d.errback()
        else:
            d.callback(None)

    def testCallFromThreadStops(self):
        """
        Ensure that callFromThread from inside a callFromThread
        callback doesn't sit in an infinite loop and lets other
        things happen too.
        """
        self.stopped = False
        d = defer.Deferred()
        reactor.callFromThread(self._callFromThreadCallback, d)
        return d

class DelayedTestCase(unittest.TestCase):
    def setUp(self):
        self.finished = 0
        self.counter = 0
        self.timers = {}
        self.deferred = defer.Deferred()

    def tearDown(self):
        for t in self.timers.values():
            t.cancel()

    def checkTimers(self):
        l1 = self.timers.values()
        l2 = list(reactor.getDelayedCalls())

        # There should be at least the calls we put in.  There may be other
        # calls that are none of our business and that we should ignore,
        # though.

        missing = []
        for dc in l1:
            if dc not in l2:
                missing.append(dc)
        if missing:
            self.finished = 1
        self.failIf(missing, "Should have been missing no calls, instead was missing " + repr(missing))

    def callback(self, tag):
        del self.timers[tag]
        self.checkTimers()

    def addCallback(self, tag):
        self.callback(tag)
        self.addTimer(15, self.callback)

    def done(self, tag):
        self.finished = 1
        self.callback(tag)
        self.deferred.callback(None)

    def addTimer(self, when, callback):
        self.timers[self.counter] = reactor.callLater(when * 0.01, callback,
                                                      self.counter)
        self.counter += 1
        self.checkTimers()

    def testGetDelayedCalls(self):
        if not hasattr(reactor, "getDelayedCalls"):
            return
        # This is not a race because we don't do anything which might call
        # the reactor until we have all the timers set up. If we did, this
        # test might fail on slow systems.
        self.checkTimers()
        self.addTimer(35, self.done)
        self.addTimer(20, self.callback)
        self.addTimer(30, self.callback)
        which = self.counter
        self.addTimer(29, self.callback)
        self.addTimer(25, self.addCallback)
        self.addTimer(26, self.callback)

        self.timers[which].cancel()
        del self.timers[which]
        self.checkTimers()

        self.deferred.addCallback(lambda x : self.checkTimers())
        return self.deferred

    def test_active(self):
        """
        L{IDelayedCall.active} returns False once the call has run.
        """
        dcall = reactor.callLater(0.01, self.deferred.callback, True)
        self.assertEqual(dcall.active(), True)

        def checkDeferredCall(success):
            self.assertEqual(dcall.active(), False)
            return success

        self.deferred.addCallback(checkDeferredCall)

        return self.deferred

resolve_helper = """
import %(reactor)s
%(reactor)s.install()
from twisted.internet import reactor

class Foo:
    def __init__(self):
        reactor.callWhenRunning(self.start)
        self.timer = reactor.callLater(3, self.failed)
    def start(self):
        reactor.resolve('localhost').addBoth(self.done)
    def done(self, res):
        print 'done', res
        reactor.stop()
    def failed(self):
        print 'failed'
        self.timer = None
        reactor.stop()
f = Foo()
reactor.run()
"""

class ChildResolveProtocol(protocol.ProcessProtocol):
    def __init__(self, onCompletion):
        self.onCompletion = onCompletion

    def connectionMade(self):
        self.output = []
        self.error = []

    def outReceived(self, out):
        self.output.append(out)

    def errReceived(self, err):
        self.error.append(err)

    def processEnded(self, reason):
        self.onCompletion.callback((reason, self.output, self.error))
        self.onCompletion = None

class Resolve(unittest.TestCase):
    def testChildResolve(self):
        # I've seen problems with reactor.run under gtk2reactor. Spawn a
        # child which just does reactor.resolve after the reactor has
        # started, fail if it does not complete in a timely fashion.
        helperPath = os.path.abspath(self.mktemp())
        helperFile = open(helperPath, 'w')

        # Eeueuuggg
        reactorName = reactor.__module__

        helperFile.write(resolve_helper % {'reactor': reactorName})
        helperFile.close()

        env = os.environ.copy()
        env['PYTHONPATH'] = os.pathsep.join(sys.path)

        helperDeferred = Deferred()
        helperProto = ChildResolveProtocol(helperDeferred)

        reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)

        def cbFinished((reason, output, error)):
            # If the output is "done 127.0.0.1\n" we don't really care what
            # else happened.
            output = ''.join(output)
            if output != 'done 127.0.0.1\n':
                self.fail((
                    "The child process failed to produce the desired results:\n"
                    "   Reason for termination was: %r\n"
                    "   Output stream was: %r\n"
                    "   Error stream was: %r\n") % (reason.getErrorMessage(), output, ''.join(error)))

        helperDeferred.addCallback(cbFinished)
        return helperDeferred

if not interfaces.IReactorProcess(reactor, None):
    Resolve.skip = "cannot run test: reactor doesn't support IReactorProcess"

class CallFromThreadTestCase(unittest.TestCase):
    """
    Task scheduling from threads tests.
    """
    if interfaces.IReactorThreads(reactor, None) is None:
        skip = "Nothing to test without thread support"

    def setUp(self):
        self.counter = 0
        self.deferred = Deferred()

    def schedule(self, *args, **kwargs):
        """
        Override in subclasses.
        """
        reactor.callFromThread(*args, **kwargs)

    def test_lotsOfThreadsAreScheduledCorrectly(self):
        """
        L{IReactorThreads.callFromThread} can be used to schedule a large
        number of calls in the reactor thread.
        """
        def addAndMaybeFinish():
            self.counter += 1
            if self.counter == 100:
                self.deferred.callback(True)

        for i in xrange(100):
            self.schedule(addAndMaybeFinish)

        return self.deferred

    def test_threadsAreRunInScheduledOrder(self):
        """
        Callbacks should be invoked in the order they were scheduled.
        """
        order = []

        def check(_):
            self.assertEqual(order, [1, 2, 3])

        self.deferred.addCallback(check)
        self.schedule(order.append, 1)
        self.schedule(order.append, 2)
        self.schedule(order.append, 3)
        self.schedule(reactor.callFromThread, self.deferred.callback, None)

        return self.deferred

    def test_scheduledThreadsNotRunUntilReactorRuns(self):
        """
        Scheduled tasks should not be run until the reactor starts running.
        """
        def incAndFinish():
            self.counter = 1
            self.deferred.callback(True)
        self.schedule(incAndFinish)

        # Callback shouldn't have fired yet.
        self.assertEqual(self.counter, 0)

        return self.deferred

class MyProtocol(protocol.Protocol):
    """
    Sample protocol.
    """

class MyFactory(protocol.Factory):
    """
    Sample factory.
    """

    protocol = MyProtocol

class ProtocolTestCase(unittest.TestCase):

    def testFactory(self):
        factory = MyFactory()
        protocol = factory.buildProtocol(None)
        self.assertEqual(protocol.factory, factory)
        self.assert_( isinstance(protocol, factory.protocol) )

class DummyProducer(object):
    """
    Very uninteresting producer implementation used by tests to ensure the
    right methods are called by the consumer with which it is registered.

    @type events: C{list} of C{str}
    @ivar events: The producer/consumer related events which have happened to
    this producer.  Strings in this list may be C{'resume'}, C{'stop'}, or
    C{'pause'}.  Elements are added as they occur.
    """

    def __init__(self):
        self.events = []

    def resumeProducing(self):
        self.events.append('resume')

    def stopProducing(self):
        self.events.append('stop')

    def pauseProducing(self):
        self.events.append('pause')

class SillyDescriptor(abstract.FileDescriptor):
    """
    A descriptor whose data buffer gets filled very fast.

    Useful for testing FileDescriptor's IConsumer interface, since
    the data buffer fills as soon as at least four characters are
    written to it, and gets emptied in a single doWrite() cycle.
    """
    bufferSize = 3
    connected = True

    def writeSomeData(self, data):
        """
        Always write all data.
        """
        return len(data)

    def startWriting(self):
        """
        Do nothing: bypass the reactor.
        """
    stopWriting = startWriting

class ReentrantProducer(DummyProducer):
    """
    Similar to L{DummyProducer}, but with a resumeProducing method which calls
    back into an L{IConsumer} method of the consumer against which it is
    registered.

    @ivar consumer: The consumer with which this producer has been or will
    be registered.

    @ivar methodName: The name of the method to call on the consumer inside
    C{resumeProducing}.

    @ivar methodArgs: The arguments to pass to the consumer method invoked in
    C{resumeProducing}.
    """
    def __init__(self, consumer, methodName, *methodArgs):
        super(ReentrantProducer, self).__init__()
        self.consumer = consumer
        self.methodName = methodName
        self.methodArgs = methodArgs

    def resumeProducing(self):
        super(ReentrantProducer, self).resumeProducing()
        getattr(self.consumer, self.methodName)(*self.methodArgs)

class TestProducer(unittest.TestCase):
    """
    Test abstract.FileDescriptor's consumer interface.
    """
    def test_doubleProducer(self):
        """
        Verify that registering a non-streaming producer invokes its
        resumeProducing() method and that you can only register one producer
        at a time.
        """
        fd = abstract.FileDescriptor()
        fd.connected = 1
        dp = DummyProducer()
        fd.registerProducer(dp, 0)
        self.assertEqual(dp.events, ['resume'])
        self.assertRaises(RuntimeError, fd.registerProducer, DummyProducer(), 0)

    def test_unconnectedFileDescriptor(self):
        """
        Verify that registering a producer when the connection has already
        been closed invokes its stopProducing() method.
        """
        fd = abstract.FileDescriptor()
        fd.disconnected = 1
        dp = DummyProducer()
        fd.registerProducer(dp, 0)
        self.assertEqual(dp.events, ['stop'])

    def _dontPausePullConsumerTest(self, methodName):
        descriptor = SillyDescriptor()
        producer = DummyProducer()
        descriptor.registerProducer(producer, streaming=False)
        self.assertEqual(producer.events, ['resume'])
        del producer.events[:]

        # Fill up the descriptor's write buffer so we can observe whether or
        # not it pauses its producer in that case.
        getattr(descriptor, methodName)('1234')

        self.assertEqual(producer.events, [])

    def test_dontPausePullConsumerOnWrite(self):
        """
        Verify that FileDescriptor does not call producer.pauseProducing() on a
        non-streaming pull producer in response to a L{IConsumer.write} call
        which results in a full write buffer. Issue #2286.
        """
        return self._dontPausePullConsumerTest('write')

    def test_dontPausePullConsumerOnWriteSequence(self):
        """
        Like L{test_dontPausePullConsumerOnWrite}, but for a call to
        C{writeSequence} rather than L{IConsumer.write}.

        C{writeSequence} is not part of L{IConsumer}, but
        L{abstract.FileDescriptor} has supported consumery behavior in response
        to calls to L{writeSequence} forever.
        """
        return self._dontPausePullConsumerTest('writeSequence')

    def _reentrantStreamingProducerTest(self, methodName):
        descriptor = SillyDescriptor()
        producer = ReentrantProducer(descriptor, methodName, 'spam')
        descriptor.registerProducer(producer, streaming=True)

        # Start things off by filling up the descriptor's buffer so it will
        # pause its producer.
        getattr(descriptor, methodName)('spam')

        # Sanity check - make sure that worked.
        self.assertEqual(producer.events, ['pause'])
        del producer.events[:]

        # After one call to doWrite, the buffer has been emptied so the
        # FileDescriptor should resume its producer.  That will result in an
        # immediate call to FileDescriptor.write which will again fill the
        # buffer and result in the producer being paused.
        descriptor.doWrite()
        self.assertEqual(producer.events, ['resume', 'pause'])
        del producer.events[:]

        # After a second call to doWrite, the exact same thing should have
        # happened.  Prior to the bugfix for which this test was written,
        # FileDescriptor would have incorrectly believed its producer was
        # already resumed (it was paused) and so not resume it again.
        descriptor.doWrite()
        self.assertEqual(producer.events, ['resume', 'pause'])

    def test_reentrantStreamingProducerUsingWrite(self):
        """
        Verify that FileDescriptor tracks producer's paused state correctly.
        Issue #811, fixed in revision r12857.
        """
        return self._reentrantStreamingProducerTest('write')

    def test_reentrantStreamingProducerUsingWriteSequence(self):
        """
        Like L{test_reentrantStreamingProducerUsingWrite}, but for calls to
        C{writeSequence}.

        C{writeSequence} is B{not} part of L{IConsumer}, however
        C{abstract.FileDescriptor} has supported consumery behavior in response
        to calls to C{writeSequence} forever.
        """
        return self._reentrantStreamingProducerTest('writeSequence')

class PortStringification(unittest.TestCase):
    if interfaces.IReactorTCP(reactor, None) is not None:
        def testTCP(self):
            p = reactor.listenTCP(0, protocol.ServerFactory())
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening()

    if interfaces.IReactorUDP(reactor, None) is not None:
        def testUDP(self):
            p = reactor.listenUDP(0, protocol.DatagramProtocol())
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening()

    if interfaces.IReactorSSL(reactor, None) is not None and ssl:
        def testSSL(self, ssl=ssl):
            pem = util.sibpath(__file__, 'server.pem')
            p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem))
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening()


text:
import srddl.exceptions as se

class _SignalHandler:
    def __init__(self, func, kwargs):
        self.func, self._kwargs = func, kwargs

    def __repr__(self):
        return 'SignalHandler {:#x} on {}'.format(id(self), self.func)

    def __call__(self, args):
        self.func(*args, **self._kwargs)

class Signal:
    def __init__(self, *args):
        self._signals = dict()
        for arg in args:
            self.create(arg)

    def create(self, signame):
        '''
        :param signame: Name to give to the signal, it will be its identifier.

        Creates a signal with the given signal name. This is mandatory because
        we will use strings for signal names and we don't want to subscribe
        to a signal that doesn't exist by mistake because of a typo.
        '''
        if signame in self._signals:
            raise se.SignalExistsError(signame)
        self._signals[signame] = dict()

    def subscribe(self, signame, func, **kwargs):
        '''
        :param signame: The name of the signal.
        :param func: The callback to call on signal trigger.
        :return: An id identifying the handler, used by unsubscribe.

        This function permits to subscribe to some signal. You must give a
        callback function that will be called on signal triggering.  You can
        add some keyword parameters that will also be given to the function, so
        that you can have "closures".
        '''
        if signame not in self._signals:
            raise se.SignalNotFoundError(signame, 'subscribing')
        for idx, handler in self._signals[signame].items():
            if handler.func is func:
                return idx
        sh = _SignalHandler(func, kwargs)
        self._signals[signame][id(sh)] = sh
        return id(sh)

    def unsubscribe(self, signame, idx):
        '''
        :param signame: The name identifying the signal.
        :param idx: The id returned by subscribe method.

        You can unsubscribe to a signal using this method. After this, the
        handler function won't be called again.
        '''
        if signame not in self._signals:
            raise se.SignalNotFoundError(signame, 'unsubscribing')
        if idx not in self._signals[signame]:
            raise se.SignalHandlerNotFoundError(signame, idx)
        del self._signals[signame][idx]

    def trigger(self, signame, *args):
        '''
        With this function you can trigger a signal.

        :param signame: The signal name to trigger.
        :param args: Arguments to give to the signal.
        '''
        if signame not in self._signals:
            raise se.SignalNotFoundError(signame, 'triggering')
        handlers = list(self._signals[signame].values())
        for handler in handlers:
            try:
                handler(args)
            except TypeError:
                raise se.SignalHandlerCallError(signame, handler)

    def signals(self):
        return list(self._signals.keys())

redpajama_set_name: RedPajamaGithub


text:
require "amakanize/filterable"

module Amakanize
  class BookPosition
    include ::Amakanize::Filterable

    class << self
      # @return [Array<Class>]
      def filter_classes
        @filter_classes ||= [
          ::Amakanize::Filters::HtmlUnescapeFilter,
          ::Amakanize::Filters::NormalizationFilter,
          ::Amakanize::Filters::ContinuousSpacesNormalizationFilter,
          ::Amakanize::Filters::HyphenMinusNormalizationFilter,
          ::Amakanize::Filters::DashBetweenAlphabetsNormalizationFilter,
          ::Amakanize::Filters::BracketsNormalizationFilter,
          ::Amakanize::Filters::SpacesBetweenExclamationsDeletionFilter,
          ::Amakanize::Filters::SpaceBetweenExclamationAndBracketDeletionFilter,
          ::Amakanize::Filters::BookPositionInBracketDetectionFilter,
          ::Amakanize::Filters::TrailingDoubleParenthesesSinglizationFilter,
          ::Amakanize::Filters::TrailingParenthesesDeletionFilter,
          ::Amakanize::Filters::TrailingDashDeletionFilter,
          ::Amakanize::Filters::TrailingSeriesNamePayloadDeletionFilter,
          ::Amakanize::Filters::BookPositionInWordsDetectionFilter,
          ::Amakanize::Filters::BookPositionAtEndDetectionFilter,
          ::Amakanize::Filters::BookPositionClearingFilter,
          ::Amakanize::Filters::VideoPositionNumberConversionFilter,
          ::Amakanize::Filters::BookPositionNumberCanonicalizationFilter,
        ]
      end
    end
  end
end


text:
package com.mobvoi.appstore.model;

public class SimWatchface {
    private Long id;

    private String similar;

    private String lastUpdateTime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getSimilar() {
        return similar;
    }

    public void setSimilar(String similar) {
        this.similar = similar == null ? null : similar.trim();
    }

    public String getLastUpdateTime() {
        return lastUpdateTime;
    }

    public void setLastUpdateTime(String lastUpdateTime) {
        this.lastUpdateTime = lastUpdateTime == null ? null : lastUpdateTime.trim();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/rlTop"
        style="@style/TopLayout" >

        <ImageView
            android:id="@+id/ivBack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:padding="10dp"
            android:src="@drawable/return_icon" />

        <TextView
            android:id="@+id/ivStep"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/forget_password"
            android:textColor="@android:color/white"
            android:textSize="18sp" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/llInputMenu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/rlTop"
        android:background="@color/white"
        android:orientation="vertical"
        android:visibility="gone" >

        <Button
            android:id="@+id/btnPhoneReset"
            android:layout_width="match_parent"
            android:layout_height="65dp"
            android:background="#FFFFFF"
            android:drawableRight="@drawable/arrow_right_gray"
            android:gravity="left|center_vertical"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:text="@string/reset_by_phone"
            android:textColor="@color/text_gray" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/gray" />

        <Button
            android:id="@+id/btnEmailReset"
            android:layout_width="match_parent"
            android:layout_height="65dp"
            android:background="#FFFFFF"
            android:drawableRight="@drawable/arrow_right_gray"
            android:gravity="left|center_vertical"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:text="@string/reset_by_email"
            android:textColor="@color/text_gray" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/gray" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/llInputPhone"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/rlTop"
        android:orientation="vertical"
        android:visibility="visible" >

        <EditText
            android:id="@+id/etName"
            style="@style/EditTextTheme"
            android:layout_marginTop="30dp"
            android:hint="@string/register_phone_num"
            android:paddingLeft="10dp"
            android:inputType="number" />

        <LinearLayout
            android:id="@+id/llCaptchaCode"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/etInputCaptchaCode_farget"
                style="@style/EditTextTheme"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="5"
                android:hint="@string/forget_password_verifycode"
                android:digits="@string/register_name_digits" />

            <ImageView
                android:id="@+id/ivGetCaptchaCode_farget"
                android:layout_width="0dp"
                android:layout_height="40dp"
                android:layout_weight="3"
                android:visibility="gone" />

            <ProgressBar
                android:id="@+id/CaptchaCode_loading"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <Button
                android:id="@+id/btnReGetCaptchaCode_farget"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="2"
                android:background="@drawable/button_blue_short"
                android:text="@string/forget_password_get_captchacode"
                android:textColor="@android:color/background_light"
                android:textSize="14sp" />
        </LinearLayout>

        <Button
            android:id="@+id/btnGetCode"
            style="@style/ButtonBlue"
            android:text="@string/forget_password_get_verifycode" />

        <LinearLayout
            android:id="@+id/llInputCode"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/etInputCode"
                style="@style/EditTextTheme"
                android:layout_weight="1"
                android:hint="@string/forget_password_verifycode"
                android:paddingLeft="10dp"
                android:inputType="number" />

            <Button
                android:id="@+id/btnReGetCode"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_blue_short"
                android:text="@string/forget_password_get_verifycode2"
                android:textColor="@android:color/background_light"
                android:textSize="14sp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/llInputPsw"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/login_input_box"
            android:gravity="center_vertical"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/etInputPsw"
                style="@style/EditTextTheme"
                android:layout_weight="1"
                android:background="@android:color/transparent"
                android:digits="@string/register_name_digits"
                android:hint="@string/setting_password"
                android:inputType="textPassword" />

            <ToggleButton
                android:id="@+id/tbPswFlag"
                android:layout_width="50dp"
                android:layout_height="24dp"
                android:background="@drawable/toggle_selector"
                android:textOff=""
                android:textOn="" />
        </LinearLayout>

        <Button
            android:id="@+id/btnSure"
            style="@style/ButtonBlue"
            android:text="@string/confirm" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rlInputEmail"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/rlTop"
        android:visibility="gone" >

        <Button
            android:id="@+id/btnSureEmail"
            style="@style/ButtonBlue"
            android:layout_centerInParent="true"
            android:layout_marginTop="30dp"
            android:text="@string/confirm" />

        <EditText
            android:id="@+id/etInputEmail"
            style="@style/EditTextTheme"
            android:layout_above="@id/btnSureEmail"
            android:layout_margin="10dp"
            android:background="@drawable/login_input_box"
            android:hint="@string/register_email"
            android:inputType="text"
            android:paddingLeft="10dp" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/rlDialog"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/rlTop"
        android:background="@color/transparent_half"
        android:visibility="gone" >

        <TextView
            android:id="@+id/tvDialog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:background="@color/white"
            android:padding="20dp"
            android:text="已发送至您的邮箱,\n请登录邮箱查收!" />
    </RelativeLayout>

</RelativeLayout>


text:
using namespace std;

mt19937 create_rand_engine() {
	random_device rnd;
	vector<std::uint_least32_t> v(10);// ‰Šú‰»—pƒxƒNƒ^
	generate(v.begin(), v.end(), ref(rnd));// ƒxƒNƒ^'̏‰Šú‰»
	seed_seq seed(v.begin(), v.end());
	return mt19937(seed);// —"ƒGƒ"ƒWƒ"
}

namespace detail {
	template<typename T> auto diff(T n1, T n2) -> typename std::make_unsigned<T>::type {
		static_assert(std::is_integral<T>::value, "T is not integral.");
		if (n1 < n2) std::swap(n1, n2);
		return static_cast<typename std::make_unsigned<T>::type>(n1 - n2);
	}
}

template<typename type> vector<type> make_nonrepeat_rand_array_select_with_hash(const size_t size, type rand_min, type rand_max) {
	if (rand_min > rand_max) swap(rand_min, rand_max);
	auto max_min_diff = detail::diff(rand_max, rand_min) + 1;
	if (max_min_diff < size) throw runtime_error("Invalid argument");
	using hash_map = unordered_map<type, type>;

	vector<type> tmp;
	tmp.reserve(size);

	hash_map Map;

	auto engine = create_rand_engine();
	for (size_t cnt = 0; cnt < size; ++cnt) {
		type val = uniform_int_distribution<type>(rand_min, rand_max)(engine);
		auto itr = Map.find(val);

		type replaced_val;
		auto replaced_itr = Map.find(rand_max);
		if (replaced_itr != Map.end()) replaced_val = replaced_itr->second;
		else replaced_val = rand_max;

		if (itr == Map.end()) {
			tmp.push_back(val);
			if (val != rand_max)Map.insert(std::make_pair(val, replaced_val));
		}
		else {
			tmp.push_back(itr->second);
			itr->second = replaced_val;
		}

		//Map.erase(replaced_val);

		--rand_max;
	}

	return tmp;
}


text:
using System.Collections.Generic;

namespace DotSpatial.Controls
{
    /// <summary>
    /// This is a stack with a limit. If the limit is reached, for each item added at the end one item is removed at the beginning of the stack.
    /// </summary>
    /// <typeparam name="T">Type of the contained objects.</typeparam>
    internal class LimitedStack<T>
    {
        #region Fields
        private readonly List<T> _stack;
        #endregion

        #region  Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="LimitedStack{T}"/> class.
        /// </summary>
        /// <param name="limit">Number of items that should be maximally allowed in the stack.</param>
        public LimitedStack(int limit = 32)
        {
            Limit = limit;
            _stack = new List<T>(limit);
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the number of contained items.
        /// </summary>
        public int Count => _stack.Count;

        /// <summary>
        /// Gets the number of items that may maximally be contained in the stack.
        /// </summary>
        public int Limit { get; }

        #endregion

        #region Methods

        /// <summary>
        /// Peeks into the stack.
        /// </summary>
        /// <returns>The last item.</returns>
        public T Peek()
        {
            if (_stack.Count == 0) return default(T);
            return _stack[_stack.Count - 1];
        }

        /// <summary>
        /// Returns the last item, removing it from the stack.
        /// </summary>
        /// <returns>The last item.</returns>
        public T Pop()
        {
            var item = _stack[_stack.Count - 1];
            _stack.RemoveAt(_stack.Count - 1);
            return item;
        }

        /// <summary>
        /// Adds the given item to the end of the stack. If the limit is reached the first item gets removed.
        /// </summary>
        /// <param name="item">Item that gets added.</param>
        public void Push(T item)
        {
            if (_stack.Count == Limit) _stack.RemoveAt(0);
            _stack.Add(item);
        }

        #endregion
    }
}


text:
.icon-arrow--gallery { background-image: url('app/icons/arrow--gallery.png'); background-repeat: no-repeat; }

.icon-arrow-nopost { background-image: url('app/icons/arrow-nopost.png'); background-repeat: no-repeat; }

.icon-arrow-right { background-image: url('app/icons/arrow-right.png'); background-repeat: no-repeat; }

.icon-border-bottom-01 { background-image: url('app/icons/border-bottom-01.png'); background-repeat: no-repeat; }

.icon-border-bottom { background-image: url('app/icons/border-bottom.png'); background-repeat: no-repeat; }

.icon-border-top-2 { background-image: url('app/icons/border-top-2.png'); background-repeat: no-repeat; }

.icon-border-top { background-image: url('app/icons/border-top.png'); background-repeat: no-repeat; }

.icon-cocktail-illustration { background-image: url('app/icons/cocktail-illustration.png'); background-repeat: no-repeat; }

.icon-deco-bg-01 { background-image: url('app/icons/deco-bg-01.png'); background-repeat: no-repeat; }

.icon-deco-bg { background-image: url('app/icons/deco-bg.png'); background-repeat: no-repeat; }

.icon-deco { background-image: url('app/icons/deco.png'); background-repeat: no-repeat; }

.icon-divider { background-image: url('app/icons/divider.png'); background-repeat: no-repeat; }

.icon-gold-border-menu { background-image: url('app/icons/gold-border-menu.png'); background-repeat: no-repeat; }

.icon-gold-border { background-image: url('app/icons/gold-border.png'); background-repeat: no-repeat; }

.icon-logo-footer { background-image: url('app/icons/logo-footer.png'); background-repeat: no-repeat; }

.icon-logo-horizontal { background-image: url('app/icons/logo-horizontal.png'); background-repeat: no-repeat; }

.icon-logo { background-image: url('app/icons/logo.png'); background-repeat: no-repeat; }

.icon-menu-bg-icons { background-image: url('app/icons/menu-bg-icons.png'); background-repeat: no-repeat; }

.icon-nav { background-image: url('app/icons/nav.png'); background-repeat: no-repeat; }

.icon-plane-white { background-image: url('app/icons/plane-white.png'); background-repeat: no-repeat; }

.icon-plane { background-image: url('app/icons/plane.png'); background-repeat: no-repeat; }

.icon-skel-guy { background-image: url('app/icons/skel-guy.png'); background-repeat: no-repeat; }

.icon-social-fb { background-image: url('app/icons/social-fb.png'); background-repeat: no-repeat; }

.icon-social-in { background-image: url('app/icons/social-in.png'); background-repeat: no-repeat; }

.icon-social-tw { background-image: url('app/icons/social-tw.png'); background-repeat: no-repeat; }


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Moose2012.CommandBased.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 * @author Team1065
 */
public class Autonomous1 extends CommandGroup {

    public Autonomous1(){
        addParallel(new HoofUp());
        addSequential(new StopAndWait(2));
        addParallel(new ConveyorDown());
        addParallel(new HoofDown());
        addSequential(new StopAndWait(2));
        addSequential(new DrivetoDistance(-17));
    }
}


text:
var annotate = function() {
  var args = Array.prototype.slice.call(arguments);
  var fn = args.pop();

  fn.$inject = args;

  return fn;
};

// Current limitations:
// - can't put into "function arg" comments
// function /* (no parenthesis like this) */ (){}
// function abc( /* xx (no parenthesis like this) */ a, b) {}
//
// Just put the comment before function or inside:
// /* (((this is fine))) */ function(a, b) {}
// function abc(a) { /* (((this is fine))) */}

var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG = /\/\*([^\*]*)\*\//m;

var parse = function(fn) {
  if (typeof fn !== 'function') {
    throw new Error('Can not annotate "' + fn + '". Expected a function!');
  }

  var match = fn.toString().match(FN_ARGS);
  return match[1] && match[1].split(',').map(function(arg) {
    match = arg.match(FN_ARG);
    return match ? match[1].trim() : arg.trim();
  }) || [];
};

exports.annotate = annotate;
exports.parse = parse;


text:
<?php

namespace Google\Service\ServiceNetworking;

class ServicenetworkingEmpty extends \Google\Model
{
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ServicenetworkingEmpty::class, 'Google_Service_ServiceNetworking_ServicenetworkingEmpty');


text:
import sccsv
import securitycenter
import json
import os
from ConfigParser import ConfigParser

conf = ConfigParser()
conf.read('csv_gen.conf')

sccsv.debug.DEBUG = conf.getboolean('Settings', 'debug')

sc = SecurityCenter4(conf.get('Settings', 'address')
                    port=conf.getint('Settings', 'port'))

sc.login(conf.get('Settings', 'username'),
        conf.get('Settings', 'password'))

def build_and_email(section):
    # The first thing that we need to do is get all of the email configuration
    # stuff loaded up.  This will involve some minor parsing and in some cases
    # we will need to check to see if there is a local variable set to override
    # the global one that is set in the Settings stanza.
    email_to = conf.get(section, 'email_to').split(',')
    email_from = conf.get('Settings', 'email_from')
    email_host = conf.get('Settings', 'smtp_host')
    if conf.has_option(section, 'email_msg'):
        email_msg = conf.get(section, 'email_msg')
    else:
        email_msg = conf.get('Settings', 'email_msg')
    if conf.has_option(section, 'email_subject'):
        email_subject = conf.get(section, 'email_subject')
    else:
        email_subject = conf.get('Settings', 'email_subject')

    # We are going to derrive the filename from the stanza...
    filename = '%s.csv' % section.replace('CSVFILE: ', '')

    # Now that we have everything in place, it's time to call the worker
    sccsv.generator.gen_csv(sc, filename)

    # Now that we have the CSV file generated, check to see if we want to
    # send out an email and act accordingly.  If we do generate an email, then
    # we will delete the CSV file when done, otherwise just leave it.
    if conf.getboolean(section, 'gen_email'):
        sccsv.mail.send(email_from, email_to, email_subject, email_msg,
                        filename, host=email_host)
        os.remove(filename)

if __name__ == '__main__':
    for section in conf.sections():
        if 'CSVFILE: ' in section:
            build_and_email(section)


text:
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

class Sensor(models.Model):
    name = models.CharField(max_length=20, unique=True)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    user = models.ForeignKey(User, default='')
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("detail", kwargs={"id": self.id})


text:
from setuptools import setup, find_packages
import sys, os

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()

PROJECT = u'ssmrandom'
VERSION = '0.3'
URL = 'https://github.com/leifj/ssmrandom'
AUTHOR = u'Leif Johansson'
AUTHOR_EMAIL = u'leifj@sunet.se'
DESC = "Entropy distribution using SSM (source-specific multicast)"

def read_file(file_name):
    file_path = os.path.join(
        os.path.dirname(__file__),
        file_name
        )
    return open(file_path).read()

setup(
    name=PROJECT,
    version=VERSION,
    description=DESC,
    long_description=README + '\n\n' + NEWS,
    author=AUTHOR,
    author_email=AUTHOR_EMAIL,
    url=URL,
    license='BSD',
    namespace_packages=[],
    packages=find_packages('src'),
    package_dir = {'': 'src'},
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'python-daemon',
        'lockfile'
    ],
    entry_points = {
        'console_scripts':
            ['ssmrandom=ssmrandom:main']
    },
    classifiers=[
    	# see http://pypi.python.org/pypi?:action=list_classifiers
        # -*- Classifiers -*-
        'License :: OSI Approved',
        'License :: OSI Approved :: BSD License',
        "Programming Language :: Python",
    ],
)


text:
```

```

[![Build Status](https://travis-ci.org/JohnLangford/vowpal_wabbit.png)](https://travis-ci.org/JohnLangford/vowpal_wabbit)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/github/JohnLangford/vowpal_wabbit?branch=master&svg=true)](https://ci.appveyor.com/project/JohnLangford/vowpal-wabbit)
[![Coverage Status](https://coveralls.io/repos/JohnLangford/vowpal_wabbit/badge.svg)](https://coveralls.io/r/JohnLangford/vowpal_wabbit)

This is the *vowpal wabbit* fast online learning code.  For Windows, look at README.windows.txt

## Prerequisite software

These prerequisites are usually pre-installed on many platforms. However, you may need to consult your favorite package
manager (*yum*, *apt*, *MacPorts*, *brew*, ...) to install missing software.

- [Boost](http://www.boost.org) library, with the `Boost::Program_Options` library option enabled.
- lsb-release  (RedHat/CentOS: redhat-lsb-core, Debian: lsb-release, Ubuntu: you're all set, OSX: not required)
- GNU *autotools*: *autoconf*, *automake*, *libtool*, *autoheader*, et. al. This is not a strict prereq. On many systems (notably Ubuntu with `libboost-program-options-dev` installed), the provided `Makefile` works fine.
- (optional) [git](http://git-scm.com) if you want to check out the latest version of *vowpal wabbit*,
  work on the code, or even contribute code to the main project.

## Getting the code

You can download the latest version from [here](https://github.com/JohnLangford/vowpal_wabbit/wiki/Download).
The very latest version is always available via 'github' by invoking one of the following:

```
## For the traditional ssh-based Git interaction:
$ git clone git://github.com/JohnLangford/vowpal_wabbit.git

## For HTTP-based Git interaction
$ git clone https://github.com/JohnLangford/vowpal_wabbit.git
```

## Compiling

You should be able to build the *vowpal wabbit* on most systems with:
```
$ make
$ make test    # (optional)
```

If that fails, try:
```
$ ./autogen.sh
$ make
$ make test    # (optional)
$ make install
```

Note that `./autogen.sh` requires *automake* (see the prerequisites, above.)

`./autogen.sh`'s command line arguments are passed directly to `configure` as
if they were `configure` arguments and flags.

Note that `./autogen.sh` will overwrite the supplied `Makefile`, so
keeping a copy of `Makefile` may be a good idea before running `autogen.sh`.

Be sure to read the wiki: https://github.com/JohnLangford/vowpal_wabbit/wiki
for the tutorial, command line options, etc.

The 'cluster' directory has it's own documentation for cluster
parallel use, and the examples at the end of test/Runtests give some
example flags.

## C++ Optimization

The default C++ compiler optimization flags are very aggressive. If you should run into a problem, consider creating and running `configure` with the `--enable-debug` option, e.g.:

```
$ ./configure --enable-debug
```

or passing your own compiler flags via the `OPTIM_FLAGS` make variable:

```
$ make OPTIM_FLAGS="-O0 -g"
```

## Ubuntu/Debian specific info

On Ubuntu/Debian/Mint and similar the following sequence should work
for building the latest from github:

```
# -- Get libboost program-options and zlib:
apt-get install libboost-program-options-dev zlib1g-dev

# -- Get the python libboost bindings (python subdir) - optional:
apt-get install libboost-python-dev

# -- Get the vw source:
git clone git://github.com/JohnLangford/vowpal_wabbit.git

# -- Build:
cd vowpal_wabbit
make
make test       # (optional)
make install
```

### Ubuntu advanced build options (clang and static)

If you prefer building with `clang` instead of `gcc` (much faster build
and slighly faster executable), install `clang` and change the `make`
step slightly:

```
apt-get install clang

make CXX=clang++
```

A statically linked `vw` executable that is not sensitive to boost
version upgrades and can be safely copied between different Linux
versions (e.g. even from Ubuntu to Red-Hat) can be built and tested with:

```
make CXX='clang++ -static' clean vw test     # ignore warnings
```

## Mac OS X-specific info

OSX requires _glibtools_, which is available via the [brew](http://brew.sh) or
[MacPorts](https://www.macports.org) package managers.

### Complete brew install of 8.0
```
brew install vowpal-wabbit
```
[The homebrew formula for VW is located on github](https://github.com/Homebrew/homebrew-core/blob/master/Formula/vowpal-wabbit.rb).

### Manual install ov Vowpal Wabbit
#### OSX Dependencies (if using Brew):
```
brew install libtool
brew install autoconf
brew install automake
brew install boost
brew install boost-python
```

#### OSX Dependencies (if using MacPorts):
```
## Install glibtool and other GNU autotool friends:
$ port install libtool autoconf automake

## Build Boost for Mac OS X 10.8 and below
$ port install boost +no_single +no_static +openmpi +python27 configure.cxx_stdlib=libc++ configure.cxx=clang++

## Build Boost for Mac OS X 10.9 and above
$ port install boost +no_single +no_static +openmpi +python27
```

#### OSX Manual compile:
*Mac OS X 10.8 and below*: ``configure.cxx_stdlib=libc++`` and ``configure.cxx=clang++`` ensure that ``clang++`` uses
the correct C++11 functionality while building Boost. Ordinarily, ``clang++`` relies on the older GNU ``g++`` 4.2 series
header files and ``stdc++`` library; ``libc++`` is the ``clang`` replacement that provides newer C++11 functionality. If
these flags aren't present, you will likely encounter compilation errors when compiling _vowpalwabbit/cbify.cc_. These
error messages generally contain complaints about ``std::to_string`` and ``std::unique_ptr`` types missing.

To compile:
```
$ sh autogen.sh --enable-libc++
$ make
$ make test    # (optional)
```

## Code Documentation

To browse the code more easily, do

`make doc`

and then point your browser to `doc/html/index.html`.


text:
#include <wangle/channel/Handler.h>
#include <wangle/channel/Pipeline.h>
#include <wangle/channel/StaticPipeline.h>
#include <wangle/channel/AsyncSocketHandler.h>
#include <wangle/channel/OutputBufferingHandler.h>
#include <wangle/channel/test/MockHandler.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <boost/thread/barrier.hpp>

using namespace folly;
using namespace wangle;
using namespace testing;

typedef StrictMock<MockHandlerAdapter<int, int>> IntHandler;
class IntHandler2 : public StrictMock<MockHandlerAdapter<int, int>> {};

ACTION(FireRead) {
  arg0->fireRead(arg1);
}

ACTION(FireReadEOF) {
  arg0->fireReadEOF();
}

ACTION(FireReadException) {
  arg0->fireReadException(arg1);
}

ACTION(FireWrite) {
  arg0->fireWrite(arg1);
}

ACTION(FireClose) {
  arg0->fireClose();
}

// Test move only types, among other things
TEST(PipelineTest, RealHandlersCompile) {
  EventBase eb;
  auto socket = AsyncSocket::newSocket(&eb);
  // static
  {
    auto pipeline = StaticPipeline<IOBufQueue&, std::unique_ptr<IOBuf>,
      AsyncSocketHandler,
      OutputBufferingHandler>::create(
        AsyncSocketHandler(socket),
        OutputBufferingHandler());
    EXPECT_TRUE(pipeline->getHandler<AsyncSocketHandler>());
    EXPECT_TRUE(pipeline->getHandler<OutputBufferingHandler>());
  }
  // dynamic
  {
    auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
    (*pipeline)
      .addBack(AsyncSocketHandler(socket))
      .addBack(OutputBufferingHandler())
      .finalize();
    EXPECT_TRUE(pipeline->getHandler<AsyncSocketHandler>());
    EXPECT_TRUE(pipeline->getHandler<OutputBufferingHandler>());
  }
}

// Test that handlers correctly fire the next handler when directed
TEST(PipelineTest, FireActions) {
  IntHandler handler1;
  IntHandler2 handler2;

  {
    InSequence sequence;
    EXPECT_CALL(handler2, attachPipeline(_));
    EXPECT_CALL(handler1, attachPipeline(_));
  }

  auto pipeline = StaticPipeline<int, int, IntHandler, IntHandler2>::create(
      &handler1, &handler2);

  EXPECT_CALL(handler1, read_(_, _)).WillOnce(FireRead());
  EXPECT_CALL(handler2, read_(_, _)).Times(1);
  pipeline->read(1);

  EXPECT_CALL(handler1, readEOF(_)).WillOnce(FireReadEOF());
  EXPECT_CALL(handler2, readEOF(_)).Times(1);
  pipeline->readEOF();

  EXPECT_CALL(handler1, readException(_, _)).WillOnce(FireReadException());
  EXPECT_CALL(handler2, readException(_, _)).Times(1);
  pipeline->readException(make_exception_wrapper<std::runtime_error>("blah"));

  EXPECT_CALL(handler2, write_(_, _)).WillOnce(FireWrite());
  EXPECT_CALL(handler1, write_(_, _)).Times(1);
  EXPECT_NO_THROW(pipeline->write(1).value());

  EXPECT_CALL(handler2, close_(_)).WillOnce(FireClose());
  EXPECT_CALL(handler1, close_(_)).Times(1);
  EXPECT_NO_THROW(pipeline->close().value());

  {
    InSequence sequence;
    EXPECT_CALL(handler1, detachPipeline(_));
    EXPECT_CALL(handler2, detachPipeline(_));
  }
}

// Test that nothing bad happens when actions reach the end of the pipeline
// (a warning will be logged, however)
TEST(PipelineTest, ReachEndOfPipeline) {
  IntHandler handler;
  EXPECT_CALL(handler, attachPipeline(_));
  auto pipeline = StaticPipeline<int, int, IntHandler>::create(&handler);

  EXPECT_CALL(handler, read_(_, _)).WillOnce(FireRead());
  pipeline->read(1);

  EXPECT_CALL(handler, readEOF(_)).WillOnce(FireReadEOF());
  pipeline->readEOF();

  EXPECT_CALL(handler, readException(_, _)).WillOnce(FireReadException());
  pipeline->readException(make_exception_wrapper<std::runtime_error>("blah"));

  EXPECT_CALL(handler, write_(_, _)).WillOnce(FireWrite());
  EXPECT_NO_THROW(pipeline->write(1).value());

  EXPECT_CALL(handler, close_(_)).WillOnce(FireClose());
  EXPECT_NO_THROW(pipeline->close().value());

  EXPECT_CALL(handler, detachPipeline(_));
}

// Test having the last read handler turn around and write
TEST(PipelineTest, TurnAround) {
  IntHandler handler1;
  IntHandler2 handler2;

  {
    InSequence sequence;
    EXPECT_CALL(handler2, attachPipeline(_));
    EXPECT_CALL(handler1, attachPipeline(_));
  }

  auto pipeline = StaticPipeline<int, int, IntHandler, IntHandler2>::create(
      &handler1, &handler2);

  EXPECT_CALL(handler1, read_(_, _)).WillOnce(FireRead());
  EXPECT_CALL(handler2, read_(_, _)).WillOnce(FireWrite());
  EXPECT_CALL(handler1, write_(_, _)).Times(1);
  pipeline->read(1);

  {
    InSequence sequence;
    EXPECT_CALL(handler1, detachPipeline(_));
    EXPECT_CALL(handler2, detachPipeline(_));
  }
}

TEST(PipelineTest, DynamicFireActions) {
  IntHandler handler1, handler2, handler3;
  EXPECT_CALL(handler2, attachPipeline(_));
  auto pipeline = StaticPipeline<int, int, IntHandler>::create(&handler2);

  {
    InSequence sequence;
    EXPECT_CALL(handler3, attachPipeline(_));
    EXPECT_CALL(handler1, attachPipeline(_));
  }

  (*pipeline)
    .addFront(&handler1)
    .addBack(&handler3)
    .finalize();

  EXPECT_TRUE(pipeline->getHandler<IntHandler>(0));
  EXPECT_TRUE(pipeline->getHandler<IntHandler>(1));
  EXPECT_TRUE(pipeline->getHandler<IntHandler>(2));

  EXPECT_CALL(handler1, read_(_, _)).WillOnce(FireRead());
  EXPECT_CALL(handler2, read_(_, _)).WillOnce(FireRead());
  EXPECT_CALL(handler3, read_(_, _)).Times(1);
  pipeline->read(1);

  EXPECT_CALL(handler3, write_(_, _)).WillOnce(FireWrite());
  EXPECT_CALL(handler2, write_(_, _)).WillOnce(FireWrite());
  EXPECT_CALL(handler1, write_(_, _)).Times(1);
  EXPECT_NO_THROW(pipeline->write(1).value());

  {
    InSequence sequence;
    EXPECT_CALL(handler1, detachPipeline(_));
    EXPECT_CALL(handler2, detachPipeline(_));
    EXPECT_CALL(handler3, detachPipeline(_));
  }
}

TEST(PipelineTest, DynamicAttachDetachOrder) {
  IntHandler handler1, handler2;
  auto pipeline = Pipeline<int, int>::create();
  {
    InSequence sequence;
    EXPECT_CALL(handler2, attachPipeline(_));
    EXPECT_CALL(handler1, attachPipeline(_));
  }
  (*pipeline)
    .addBack(&handler1)
    .addBack(&handler2)
    .finalize();
  {
    InSequence sequence;
    EXPECT_CALL(handler1, detachPipeline(_));
    EXPECT_CALL(handler2, detachPipeline(_));
  }
}

TEST(PipelineTest, GetContext) {
  IntHandler handler;
  EXPECT_CALL(handler, attachPipeline(_));
  auto pipeline = StaticPipeline<int, int, IntHandler>::create(&handler);
  EXPECT_TRUE(handler.getContext());
  EXPECT_CALL(handler, detachPipeline(_));
}

TEST(PipelineTest, HandlerInMultiplePipelines) {
  IntHandler handler;
  EXPECT_CALL(handler, attachPipeline(_)).Times(2);
  auto pipeline1 = StaticPipeline<int, int, IntHandler>::create(&handler);
  auto pipeline2 = StaticPipeline<int, int, IntHandler>::create(&handler);
  EXPECT_FALSE(handler.getContext());
  EXPECT_CALL(handler, detachPipeline(_)).Times(2);
}

TEST(PipelineTest, HandlerInPipelineTwice) {
  auto handler = std::make_shared<IntHandler>();
  EXPECT_CALL(*handler, attachPipeline(_)).Times(2);
  auto pipeline = Pipeline<int, int>::create();
  pipeline->addBack(handler);
  pipeline->addBack(handler);
  pipeline->finalize();
  EXPECT_FALSE(handler->getContext());
  EXPECT_CALL(*handler, detachPipeline(_)).Times(2);
}

TEST(PipelineTest, NoDetachOnOwner) {
  IntHandler handler;
  EXPECT_CALL(handler, attachPipeline(_));
  auto pipeline = StaticPipeline<int, int, IntHandler>::create(&handler);
  pipeline->setOwner(&handler);
}

template <class Rin, class Rout = Rin, class Win = Rout, class Wout = Rin>
class ConcreteHandler : public Handler<Rin, Rout, Win, Wout> {
  typedef typename Handler<Rin, Rout, Win, Wout>::Context Context;
 public:
  void read(Context* ctx, Rin msg) override {}
  Future<Unit> write(Context* ctx, Win msg) override { return makeFuture(); }
};

typedef HandlerAdapter<std::string, std::string> StringHandler;
typedef ConcreteHandler<int, std::string> IntToStringHandler;
typedef ConcreteHandler<std::string, int> StringToIntHandler;

TEST(Pipeline, MissingInboundOrOutbound) {
  auto pipeline = Pipeline<int, int>::create();
  (*pipeline)
    .addBack(HandlerAdapter<std::string, std::string>{})
    .finalize();
  EXPECT_THROW(pipeline->read(0), std::invalid_argument);
  EXPECT_THROW(pipeline->readEOF(), std::invalid_argument);
  EXPECT_THROW(
      pipeline->readException(exception_wrapper(std::runtime_error("blah"))),
      std::invalid_argument);
  EXPECT_THROW(pipeline->write(0), std::invalid_argument);
  EXPECT_THROW(pipeline->close(), std::invalid_argument);
}

TEST(Pipeline, DynamicConstruction) {
  {
    auto pipeline = Pipeline<std::string, std::string>::create();
    pipeline->addBack(StringHandler());
    pipeline->addBack(StringHandler());

    // Exercise both addFront and addBack. Final pipeline is
    // StI <-> ItS <-> StS <-> StS <-> StI <-> ItS
    EXPECT_NO_THROW(
      (*pipeline)
        .addFront(IntToStringHandler{})
        .addFront(StringToIntHandler{})
        .addBack(StringToIntHandler{})
        .addBack(IntToStringHandler{})
        .finalize());
  }
}

TEST(Pipeline, RemovePointer) {
  IntHandler handler1, handler2;
  EXPECT_CALL(handler1, attachPipeline(_));
  EXPECT_CALL(handler2, attachPipeline(_));
  auto pipeline = Pipeline<int, int>::create();
  (*pipeline)
    .addBack(&handler1)
    .addBack(&handler2)
    .finalize();

  EXPECT_CALL(handler1, detachPipeline(_));
  (*pipeline)
    .remove(&handler1)
    .finalize();

  EXPECT_CALL(handler2, read_(_, _));
  pipeline->read(1);

  EXPECT_CALL(handler2, detachPipeline(_));
}

TEST(Pipeline, RemoveFront) {
  IntHandler handler1, handler2;
  EXPECT_CALL(handler1, attachPipeline(_));
  EXPECT_CALL(handler2, attachPipeline(_));
  auto pipeline = Pipeline<int, int>::create();
  (*pipeline)
    .addBack(&handler1)
    .addBack(&handler2)
    .finalize();

  EXPECT_CALL(handler1, detachPipeline(_));
  (*pipeline)
    .removeFront()
    .finalize();

  EXPECT_CALL(handler2, read_(_, _));
  pipeline->read(1);

  EXPECT_CALL(handler2, detachPipeline(_));
}

TEST(Pipeline, RemoveBack) {
  IntHandler handler1, handler2;
  EXPECT_CALL(handler1, attachPipeline(_));
  EXPECT_CALL(handler2, attachPipeline(_));
  auto pipeline = Pipeline<int, int>::create();
  (*pipeline)
    .addBack(&handler1)
    .addBack(&handler2)
    .finalize();

  EXPECT_CALL(handler2, detachPipeline(_));
  (*pipeline)
    .removeBack()
    .finalize();

  EXPECT_CALL(handler1, read_(_, _));
  pipeline->read(1);

  EXPECT_CALL(handler1, detachPipeline(_));
}

TEST(Pipeline, RemoveType) {
  IntHandler handler1;
  IntHandler2 handler2;
  EXPECT_CALL(handler1, attachPipeline(_));
  EXPECT_CALL(handler2, attachPipeline(_));
  auto pipeline = Pipeline<int, int>::create();
  (*pipeline)
    .addBack(&handler1)
    .addBack(&handler2)
    .finalize();

  EXPECT_CALL(handler1, detachPipeline(_));
  (*pipeline)
    .remove<IntHandler>()
    .finalize();

  EXPECT_CALL(handler2, read_(_, _));
  pipeline->read(1);

  EXPECT_CALL(handler2, detachPipeline(_));
}

// Pipeline lifetime used to be managed by DelayedDestruction, which is not
// thread safe. This test would fail. Mandatory shared_ptr ownership fixes the
// issue.
TEST(Pipeline, Concurrent) {
  NiceMock<MockHandlerAdapter<int, int>> handler1, handler2;
  auto pipeline = Pipeline<int, int>::create();
  (*pipeline)
    .addBack(&handler1)
    .addBack(&handler2)
    .finalize();
  boost::barrier b{2};
  auto spam = [&]{
    for  (int i = 0; i < 100000; i++) {
      b.wait();
      pipeline->read(i);
    }
  };
  std::thread t(spam);
  spam();
  t.join();
}


text:
var request = require('request'),
    async = require('async');

module.exports = function () {
    var self = this,
        getRequestHeaders = function () { // build request header
            if (typeof process.env.BUILDBUDDY_ACCESS_TOKEN !== 'undefined') {
                self.configuration.access_token = process.env.BUILDBUDDY_ACCESS_TOKEN;
            }
            return {
                'ACCESS-TOKEN': self.configuration.access_token,
                'Authorization': 'Bearer ' + self.configuration.access_token,
                'accept-encoding': 'application/json'
            };
        },
        makeUrl = function (app_id, build_id, branch, baseUrl) { //assemble url with designated branch id
            if (build_id) { // to query one build provide a build_id
                baseUrl += '/' + build_id;
            } else if (app_id) { // to get lastest build provide app_id but no build_id
                baseUrl += "/" + app_id + "/build/latest?branch=" + branch;
            }

            return baseUrl;
        },
        makeRequest = function (url, callback) { //make http request to BuildBuddy API
            request({
                    headers: getRequestHeaders(),
                    url: url,
                    json: true
                },
                function (error, response, body) {
                    if (error) {
                      callback(error);
                      return;
                    }

                    if (response.statusCode === 500) {
                      callback(new Error(response.statusMessage));
                      return;
                    }

                    callback(error, body);
                });
        },
        parseDate = function (dateAsString) {
            return new Date(dateAsString);
        },
        forEachResult = function (body, callback) {

            callback(body);

        },
        isNullOrWhiteSpace = function (string) {
            if (!string) {
                return true;
            }

            return string === null || string.match(/^ *$/) !== null;
        },
        getStatus = function (statusText) {
            switch (statusText) {
                case "success":
                    return "Green";
                case "failed":
                    return "Red";
                case "running":
                    return "Blue";
                case "stopped":
                    return "Red";
                case "queued":
                    return "Blue";
                case "canceled":
                    return "#FFA500";
                default:
                    return "Gray";
            }
        },
        parseLink = function (appId, buildId) { // point to the build
            return 'https://dashboard.buddybuild.com/apps/' + appId + '/build/' + buildId;
        },
        simplifyBuild = function (res) {
            return {
                id: res._id,
                platform: self.configuration.project_name,
                project: self.configuration.project_name + ': ' + res.commit_info.branch,
                number: 'Build: ' + res.build_number,
                isRunning: res.BuildFinished,
                startedAt: parseDate(res.started_at),
                finishedAt: parseDate(res.finished_at),
                requestedFor: res.commit_info.author,
                statusText: res.build_status,
                status: getStatus(res.build_status),
                reason: res.commit_info.message,
                finished: res.finished,
                hasErrors: !isNullOrWhiteSpace(res.Errors),
                hasWarnings: !isNullOrWhiteSpace(res.Warnings),
                branch: res.commit_info.branch,
                url: parseLink(res.app_id, res._id)
            };
        },
        queryBuilds = function (callback) { // query the build
            makeRequest(makeUrl(self.configuration.app_id, self.configuration.build_id, self.configuration.branch, self.configuration.url), function (error, body) {
                if (error) {
                  callback(error);
                  return;
                }

                var builds = [];

                forEachResult(body, function (res) {
                    builds.push(simplifyBuild(res));
                });

                callback(error, builds);
            });
        };

    self.configure = function (config) {
        self.configuration = config;
    };

    self.check = function (callback) {
        queryBuilds(callback);
    };

    self.makeURL = function (app_id, build_id, branch, url) {
        return makeUrl(app_id, build_id, branch, url);
    };

    self.getHeaders = function (access_token) {
        self.configuration.access_token = access_token;
        return getRequestHeaders();
    };

    self.getStatus = function (statusText) {
        "use strict";
        return getStatus(statusText);
    };
};


text:
package io.github.jklingsporn.vertx.jooq.generate;

import io.vertx.core.json.JsonArray;
import org.jooq.*;
import org.jooq.Record;
import org.jooq.impl.DSL;
import org.junit.BeforeClass;

import java.util.function.Function;

/**
 * @author jensklingsporn
 */
public abstract class AbstractPostgresInsertReturningTest {

    @BeforeClass
    public static void beforeClass() throws Exception {
        PostgresConfigurationProvider.getInstance().setupDatabase();
    }

    protected <R extends UpdatableRecord<R>, T> Function<Object, T> keyMapper(Table<R> table, Configuration configuration){
        return o -> {
            JsonArray j = (JsonArray) o;
            int pkLength = table.getPrimaryKey().getFieldsArray().length;
            if(pkLength == 1){
                return (T)j.getValue(0);
            }
            Object[] values = new Object[j.size()];
            for(int i=0;i<j.size();i++){
                values[i] = j.getValue(i);
            }
            TableField<R, Object>[] fields = (TableField<R, Object>[]) table.getPrimaryKey().getFieldsArray();
            Record result = DSL.using(configuration)
                    .newRecord(fields);

            for (int i = 0; i < values.length; i++)
                result.set(fields[i], fields[i].getDataType().convert(values[i]));

            return (T) result;
        };
    }

}


text:
from taiga.base.api import validators

from . import models

class FeedbackEntryValidator(validators.ModelValidator):
    class Meta:
        model = models.FeedbackEntry


text:
package org.lnu.is.converter.mark.scale.exchange;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.lnu.is.converter.mark.scale.exchange.MarkScaleExchangeResourceConverter;
import org.lnu.is.domain.mark.scale.MarkScale;
import org.lnu.is.domain.mark.scale.exchange.MarkScaleExchange;
import org.lnu.is.domain.mark.scale.value.MarkScaleValue;
import org.lnu.is.resource.mark.scale.exchange.MarkScaleExchangeResource;

public class MarkScaleExchangeResourceConverterTest {

	private MarkScaleExchangeResourceConverter unit = new MarkScaleExchangeResourceConverter();

	@Test
	public void testConvert() throws Exception {
		// Given
		Double markMin = 0.0;
		Double markMax = 10.0;
		Double markExchange = 5.0;

		Long markscaleId = 1L;
		MarkScale markscale = new MarkScale();
		markscale.setId(markscaleId);

		Long markscaleValueId = 1L;
		MarkScaleValue markscaleValue = new MarkScaleValue();
		markscaleValue.setId(markscaleValueId);

		Long markscaleExchangeId = 2L;
		MarkScale markscaleExchange = new MarkScale();
		markscaleExchange.setId(markscaleExchangeId);

		Long markscaleExchangeValueId = 2L;
		MarkScaleValue markscaleExchangeValue = new MarkScaleValue();
		markscaleExchangeValue.setId(markscaleExchangeValueId);

		MarkScaleExchangeResource source = new MarkScaleExchangeResource();
		source.setMarkMin(markMin);
		source.setMarkMax(markMax);
		source.setMarkExchange(markExchange);
		source.setMarkScaleId(markscaleId);
		source.setMarkScaleValueId(markscaleValueId);
		source.setMarkScaleExchangeId(markscaleExchangeId);
		source.setMarkScaleExchangeValueId(markscaleExchangeValueId);

		MarkScaleExchange expected = new MarkScaleExchange();
		expected.setMarkMin(markMin);
		expected.setMarkMax(markMax);
		expected.setMarkExchange(markExchange);
		expected.setMarkScale(markscale);
		expected.setMarkScaleValue(markscaleValue);
		expected.setMarkScaleExchange(markscaleExchange);
		expected.setMarkScaleExchangeValue(markscaleExchangeValue);

		// When
		MarkScaleExchange actual = unit.convert(source);

		// Then
		assertEquals(expected, actual);
	}

	@Test
	public void testConvertWithNoRelations() throws Exception {
		// Given
		Double markMin = 0.0;
		Double markMax = 10.0;
		Double markExchange = 5.0;

		MarkScaleExchangeResource source = new MarkScaleExchangeResource();
		source.setMarkMin(markMin);
		source.setMarkMax(markMax);
		source.setMarkExchange(markExchange);

		MarkScaleExchange expected = new MarkScaleExchange();
		expected.setMarkMin(markMin);
		expected.setMarkMax(markMax);
		expected.setMarkExchange(markExchange);

		// When
		MarkScaleExchange actual = unit.convert(source);

		// Then
		assertEquals(expected, actual);
	}
}