Forward an asynchronous sequence while a condition is met.

    The given function takes the item as an argument and returns a boolean
    corresponding to the condition to meet. The function can either be
    synchronous or asynchronous.
490813
async def takewhile(source, func):
    
    iscorofunc = asyncio.iscoroutinefunction(func)
    async with streamcontext(source) as streamer:
        async for item in streamer:
            result = func(item)
            if iscorofunc:
                result = await result
            if not result:
                return
            yield item
136679
function each(items, numParralel, fn, done) {
    if (done === undefined) {
      done = fn; fn = numParralel;
      numParralel = 3;
    }

    if (numParralel <= 0) numParralel = 1;

    let doing = 0;
    let numProcessing = 0;
    let numDone = 0;
    const numTotal = items.length;
    const results = [];
    return nextItem();

    function nextItem() {
      // We done-check first in case of emtpty array
      if (numDone >= numTotal) return done(null, results);

      // Batch (or call next item)
      while (doing < numTotal && numProcessing < numParralel) {
        callFn(fn, items[doing++], onDone);
        numProcessing++;
      }
      return;

      // All done
      function onDone(err, result) {
        if (err) return done(err);

        results.push(result);
        numProcessing--;
        numDone++;
        return nextItem();
      }
    }
  }
342877
def transaction(self, func, *watches, **kwargs):
        
        with self.pipeline(True, share_in_threads=kwargs.get('share_in_threads', False)) as pipe:
            while 1:
                try:
                    if watches:
                        pipe.watch(*watches)
                    func(pipe)
                    return pipe.execute()
                except WatchError:
                    continue
114085
async def transaction(self, func, *watches, **kwargs):
        
        shard_hint = kwargs.pop('shard_hint', None)
        value_from_callable = kwargs.pop('value_from_callable', False)
        watch_delay = kwargs.pop('watch_delay', None)
        async with await self.pipeline(True, shard_hint) as pipe:
            while True:
                try:
                    if watches:
                        await pipe.watch(*watches)
                    func_value = await func(pipe)
                    exec_value = await pipe.execute()
                    return func_value if value_from_callable else exec_value
                except WatchError:
                    if watch_delay is not None and watch_delay > 0:
                        await asyncio.sleep(
                            watch_delay,
                            loop=self.connection_pool.loop
                        )
                    continue
223283
function forwardEvent (event) {
    var n = Atok.events[event]
      , args = []

    while (n > 0) args.push('a' + n--)
    args = args.join()

    return 'atok.on("'
      + event
      + '", function forwardEvent (' + args + ') { self.emit_' + event + '(' + args + ') })'
  }
683648
def first_that(predicate, sequence, message=None):
    
    try:
        return next(ifilter(predicate, sequence))
    except StopIteration:
        raise KeyError(message or 'Not Found')
222950
def delay_or_fail(self, *args, **kwargs):
        
        return self.async_or_fail(args=args, kwargs=kwargs)
402199
function (item, itemIndex, then, complete, arrayWeTraverse) {
            $assert (item === data[itemIndex])
            $assert (itemIndex === currentIndex++)
            $assert (arrayWeTraverse === data)

            $assert (_.isFunction (then))
            $assert (_.isFunction (complete))

            then () }
35100
async def wait_for_send(self, event, *, until=None):
        '''
        
        '''
        while True:
            if until:
                r = until()
                if r:
                    return r
            waiter = self.scheduler.send(event)
            if waiter is None:
                break
            await waiter
792864
def _queue_task(self, args):
        '''  '''
        if self._cancel_called:
            raise AsperaTransferQueueError("Cancel already called")
        elif self._wait_called:
            raise AsperaTransferQueueError("Cant queue items during wait")
        elif self.waiting_coordinator_count() >= self._config.max_submission_queue_size:
            raise AsperaTransferQueueError("Max queued items reached")
        else:
            _coordinator = AsperaTransferCoordinator(args)
            _components = {'meta': TransferMeta(args, transfer_id=args.transfer_id),
                           'coordinator': _coordinator}

            _transfer_future = AsperaTransferFuture(**_components)
            _coordinator.add_subscribers(args.subscribers, future=_transfer_future)
            _coordinator.add_done_callback(self.remove_aspera_coordinator,
                                           transfer_coordinator=_coordinator)
            self.append_waiting_queue(_coordinator)

            if not self._processing_thread:
                self._processing_thread = threading.Thread(target=self._process_waiting_queue)
                self._processing_thread.daemon = True
                self._processing_thread.start()

            self._wakeup_processing_thread()

        return _transfer_future
597983
def coerce_to_synchronous(func):
    '''
    
    '''
    if inspect.iscoroutinefunction(func):
        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            loop = asyncio.get_event_loop()
            try:
                loop.run_until_complete(func(*args, **kwargs))
            finally:
                loop.close()
        return sync_wrapper
    return func
742706
async def wait(self) -> None:
        
        if self.triggered_token is not None:
            return

        futures = [asyncio.ensure_future(self._triggered.wait(), loop=self.loop)]
        for token in self._chain:
            futures.append(asyncio.ensure_future(token.wait(), loop=self.loop))

        def cancel_not_done(fut: 'asyncio.Future[None]') -> None:
            for future in futures:
                if not future.done():
                    future.cancel()

        async def _wait_for_first(futures: Sequence[Awaitable[Any]]) -> None:
            for future in asyncio.as_completed(futures):
                # We don't need to catch CancelledError here (and cancel not done futures)
                # because our callback (above) takes care of that.
                await cast(Awaitable[Any], future)
                return

        fut = asyncio.ensure_future(_wait_for_first(futures), loop=self.loop)
        fut.add_done_callback(cancel_not_done)
        await fut
782071
public static <T, R> Function<T, R> doIf(final Predicate<T> condition, final CheckedFunction<T, R> trueFunction,
                                             final CheckedFunction<T, R> falseFunction) {
        return t -> {
            try {
                if (condition.test(t)) {
                    return trueFunction.apply(t);
                }
                return falseFunction.apply(t);
            } catch (final Throwable e) {
                LOGGER.warn(e.getMessage(), e);
                try {
                    return falseFunction.apply(t);
                } catch (final Throwable ex) {
                    throw new IllegalArgumentException(ex.getMessage());
                }
            }
        };
    }
877386
def execute_with_delay(task_function, *args, **kwargs):
    
    delay = kwargs.pop('delay', 0)
    if get_setting('TEST_DISABLE_ASYNC_DELAY'):
        # Delay disabled, run synchronously
        logger.debug('Running function "%s" synchronously because '\
                     'TEST_DISABLE_ASYNC_DELAY is True'
                     % task_function.__name__)
        return task_function(*args, **kwargs)

    db.connections.close_all()
    task_function.apply_async(args=args, kwargs=kwargs, countdown=delay)
202719
def call_async(self, fn, *args, **kwargs):
        
        return self.default_call_chain.call_async(fn, *args, **kwargs)
248120
def connect(self, f, t):
        
        if t not in self._vertices:
            raise KeyError(t)
        self._forwards[f].add(t)
        self._backwards[t].add(f)
578425
def Synchronized(f):
  """"""

  @functools.wraps(f)
  def NewFunction(self, *args, **kw):
    with self.lock:
      return f(self, *args, **kw)

  return NewFunction