:meth:`.WThreadTask._polling_iteration` implementation
543362
def thread_stopped(self):
		
		if self.__current_task is not None:
			task = self.__task_chain[self.__current_task]
			task.stop()
			self.__current_task = None
516193
def _on_iteration(self, *args, **kwargs) -> None:
        

        # Update timing and the iteration number in the monitoring context.
        current_timestamp = get_hr_time()
        self._context.optimisation_time += current_timestamp - self._last_timestamp
        self._context.total_time = current_timestamp - self._start_timestamp
        self._context.optimiser_updated = False
        if not self._context.optimisation_finished:
            self._context.iteration_no += 1

        # Call all monitoring functions
        for func in self._monitor_tasks:
            func(self._context, *args, **kwargs)

        # Remember the time when the control is returned back to the optimiser, so that the next
        # optimisation step can be accurately timed.
        self._last_timestamp = get_hr_time()
1130389
def run(self):
        

        try:
            self.__options.callbacks.request_in_thread_before_start(self.__queue_item)
        except Exception as e:
            print(e)

        new_requests = []
        failed = False

        try:
            handler = Handler(self.__options, self.__queue_item)
            new_requests = handler.get_new_requests()

            try:
                self.__queue_item.response.raise_for_status()
            except Exception:
                if self.__queue_item.request.parent_raised_error:
                    failed = True
                else:
                    for new_request in new_requests:
                        new_request.parent_raised_error = True

        except Exception as e:
            failed = True

            error_message = "Setting status of '{}' to '{}' because of an HTTP error.".format(
                self.__queue_item.request.url,
                QueueItem.STATUS_ERRORED
            )

            DebugHelper.output(self.__options, error_message)
            DebugHelper.output(self.__options, e)

            try:
                self.__options.callbacks.request_on_error(self.__queue_item, str(e))
            except Exception as e:
                print(e)

        for new_request in new_requests:
            new_request.parent_url = self.__queue_item.request.url

        try:
            self.__options.callbacks.request_in_thread_after_finish(self.__queue_item)
        except Exception as e:
            print(e)

        with self.__callback_lock:
            self.__callback(self.__queue_item, new_requests, failed)
553436
def poll(self):
        

        pubsub = self.conn.pubsub()
        pubsub.subscribe(self.key)

        # Pubsub messages generator
        gen = pubsub.listen()

        last_heartbeat = time.time()
        self.heartbeat()

        last_cleanup = time.time()
        self.cleanup()

        try:
            while True:
                # Since Redis' listen method blocks, we use select to inspect the
                # underlying socket to see if there is activity.
                fileno = pubsub.connection._sock.fileno()
                timeout = max(0, POLL_INTERVAL - (time.time() - last_heartbeat))
                r, w, x = self._select([fileno], [], [], timeout)
                if fileno in r:
                    next(gen)
                    self.update()

                last_heartbeat = time.time()
                self.heartbeat()

                now = time.time()
                if now - last_cleanup > CLEANUP_INTERVAL:
                    last_cleanup = now
                    self.cleanup()
        finally:
            pubsub.close()
669566
def run( self ):
        

        self.handshake()

        try:
            self.loop()
        except socket.error, se:
            if self.finished:
                return True
            else:
                raise
406594
def _async_poll(self, poller, async_seconds, async_poll_interval):
        '''  '''

        results = poller.wait(async_seconds, async_poll_interval)

        # mark any hosts that are still listed as started as failed
        # since these likely got killed by async_wrapper
        for host in poller.hosts_to_poll:
            reason = { 'failed' : 1, 'rc' : None, 'msg' : 'timed out' }
            self.runner_callbacks.on_failed(host, reason)
            results['contacted'][host] = reason

        return results
234395
def main_loop_iteration(timeout=None):
    """"""
    prev_nr_read = nr_handle_read
    asyncore.loop(count=1, timeout=timeout, use_poll=True)
    return nr_handle_read - prev_nr_read
273233
def _multiprocessing_to_asyncio(in_queue, out_queue, loop):
    

    while True:
        value = in_queue.get()
        loop.call_soon_threadsafe(out_queue.put_nowait, value)
972589
def pause(self):
        
        self.status = 'paused'
        # The _loop method will react to 'paused' status and stop looping.
        if hasattr(
                self, '_sampling_thread') and self._sampling_thread.isAlive():
            print_('Waiting for current iteration to finish...')
            while self._sampling_thread.isAlive():
                sleep(.1)
1155579
def Poll(generator=None, condition=None, interval=None, timeout=None):
  """"""

  if not generator:
    raise ValueError("generator has to be a lambda")

  if not condition:
    raise ValueError("condition has to be a lambda")

  if interval is None:
    interval = DEFAULT_POLL_INTERVAL

  if timeout is None:
    timeout = DEFAULT_POLL_TIMEOUT

  started = time.time()
  while True:
    obj = generator()
    check_result = condition(obj)
    if check_result:
      return obj

    if timeout and (time.time() - started) > timeout:
      raise errors.PollTimeoutError(
          "Polling on %s timed out after %ds." % (obj, timeout))
    time.sleep(interval)
891140
def _create_new_thread_loop(self):
        
        self._thread_loop = ThreadLoop()
        if not self._thread_loop.is_ready():
            self._thread_loop.start()
        return self._thread_loop._io_loop
1342551
def iteration(self, node_status=True):
        
        self.clean_initial_status(self.available_statuses.values())

        actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)}

        # streaming
        if self.stream_execution:
            u, v = list(self.graph.edges())[0]
            u_status = self.status[u]
            v_status = self.status[v]

            if u_status == 1 and v_status == 0:
                p = np.random.random_sample()
                if p < self.params['model']['beta']:
                    actual_status[v] = 1

            if v_status == 1 and u_status == 0:
                p = np.random.random_sample()
                if p < self.params['model']['beta']:
                    actual_status[u] = 1

            delta, node_count, status_delta = self.status_delta(actual_status)
            self.status = actual_status
            self.actual_iteration += 1

            if node_status:
                return {"iteration": self.actual_iteration - 1, "status": delta.copy(),
                        "node_count": node_count.copy(), "status_delta": status_delta.copy()}
            else:
                return {"iteration": self.actual_iteration - 1, "status": {},
                        "node_count": node_count.copy(), "status_delta": status_delta.copy()}
        # snapshot
        else:

            if self.actual_iteration == 0:
                self.actual_iteration += 1
                delta, node_count, status_delta = self.status_delta(actual_status)
                if node_status:
                    return {"iteration": 0, "status": actual_status.copy(),
                            "node_count": node_count.copy(), "status_delta": status_delta.copy()}
                else:
                    return {"iteration": 0, "status": {},
                            "node_count": node_count.copy(), "status_delta": status_delta.copy()}

            for u in self.graph.nodes():
                u_status = self.status[u]
                eventp = np.random.random_sample()
                neighbors = self.graph.neighbors(u)
                if isinstance(self.graph, nx.DiGraph):
                    neighbors = self.graph.predecessors(u)

                if u_status == 0:
                    infected_neighbors = len([v for v in neighbors if self.status[v] == 1])
                    if eventp < self.params['model']['beta'] * infected_neighbors:
                        actual_status[u] = 1

        delta, node_count, status_delta = self.status_delta(actual_status)
        self.status = actual_status
        self.actual_iteration += 1

        if node_status:
            return {"iteration": self.actual_iteration - 1, "status": delta.copy(),
                    "node_count": node_count.copy(), "status_delta": status_delta.copy()}
        else:
            return {"iteration": self.actual_iteration - 1, "status": {},
                    "node_count": node_count.copy(), "status_delta": status_delta.copy()}
490196
def poll(self, timeout):
        
        now = time.time()
        end_time = now + float(timeout)
        prev_timeout = self.stream.gettimeout()
        self.stream.settimeout(self._poll_period)
        incoming = None
        try:
            while (end_time - now) >= 0:
                try:
                    incoming = self.stream.recv(self._max_read)
                except socket.timeout:
                    pass
                if incoming:
                    return incoming
                now = time.time()
            raise ExpectTimeout()
        finally:
            self.stream.settimeout(prev_timeout)
996459
def polling_loop(connection)
      if polling?
        polling_msg = "Polling enabled. Checking every #{config.poll_interval} seconds."
      else
        polling_msg = "Polling disabled. Checking for messages once."
      end
      Mailman.logger.info(polling_msg)

      tries ||= 5
      loop do
        begin
          connection.connect
          connection.get_messages
        rescue SystemCallError, EOFError => e
          Mailman.logger.error e.message
          unless (tries -= 1).zero?
            Mailman.logger.error "Retrying..."
            begin
              connection.disconnect
            rescue # don't crash in the crash handler
            end
            retry
          end
        ensure
          connection.started? && connection.disconnect
        end

        break unless polling?
        sleep config.poll_interval
      end
    end
341092
def _poll(self):
        
        while True:
            self.poll_count += 1
            self._poll_action()
            if self.poll_complete:
                break
            time.sleep(self.poll_interval_s)
            self._poll_update_interval()
7944
def _loop_once(self, timeout=None):
        
        _vv and IOLOG.debug('%r._loop_once(%r, %r)',
                            self, timeout, self.poller)
        #IOLOG.debug('readers =\n%s', pformat(self.poller.readers))
        #IOLOG.debug('writers =\n%s', pformat(self.poller.writers))
        for side, func in self.poller.poll(timeout):
            self._call(side.stream, func)
1257696
def run_sequential(self):
        
        try:
            result = self.empty_result(*self.context)

            for obj in self.iterable:
                r = self.compute(obj, *self.context)
                result = self.process_result(r, result)
                self.progress.update(1)

                # Short-circuited?
                if self.done:
                    break
        except Exception as e:
            raise e
        finally:
            self.progress.close()

        return result