Check that the realtime streams are being produced
321162
def _verify_realtime_streams(self, hw):
        
        print("--> Testing realtime data (takes 2 seconds)")
        time.sleep(2.1)
        reports = [x for x in hw.iter_reports()]
        reports_seen = {key: 0 for key in self._realtime_streams}

        for report in reports:
            stream_value = report.visible_readings[0].stream
            if reports_seen.get(stream_value) is not None:
                reports_seen[stream_value] += 1

        for stream in reports_seen.keys():
            if reports_seen[stream] < 2:
                raise ArgumentError("Realtime Stream not pushing any reports", stream=hex(stream), \
                    reports_seen=reports_seen[stream])
1359666
def start_watching(self):
        
        if not self.is_sync:
            return

        self._stop = False
        while not self._stop:
            self.reactor.doIteration(0)
844238
boolean isAsync() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "isAsync");
        boolean isAsync = !asyncConsumers.isEmpty() && getState() == STARTED;
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "isAsync", isAsync);
        return isAsync;
    }
790254
def available_streams():
    """"""
    sds = kp.db.StreamDS()
    print("Available streams: ")
    print(', '.join(sorted(sds.streams)))
1002747
function hasPipeDataListeners (stream) {
  var listeners = stream.listeners('data')

  for (var i = 0; i < listeners.length; i++) {
    if (listeners[i].name === 'ondata') {
      return true
    }
  }

  return false
}
824263
def alert_stream(self, reset_event, kill_event):
        """"""
        _LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id)
        start_event = False
        parse_string = ""
        fail_count = 0

        url = '%s/ISAPI/Event/notification/alertStream' % self.root_url

        # pylint: disable=too-many-nested-blocks
        while True:

            try:
                stream = self.hik_request.get(url, stream=True,
                                              timeout=(CONNECT_TIMEOUT,
                                                       READ_TIMEOUT))
                if stream.status_code == requests.codes.not_found:
                    # Try alternate URL for stream
                    url = '%s/Event/notification/alertStream' % self.root_url
                    stream = self.hik_request.get(url, stream=True)

                if stream.status_code != requests.codes.ok:
                    raise ValueError('Connection unsucessful.')
                else:
                    _LOGGING.debug('%s Connection Successful.', self.name)
                    fail_count = 0
                    self.watchdog.start()

                for line in stream.iter_lines():
                    # _LOGGING.debug('Processing line from %s', self.name)
                    # filter out keep-alive new lines
                    if line:
                        str_line = line.decode("utf-8", "ignore")
                        # New events start with --boundry
                        if str_line.find('<EventNotificationAlert') != -1:
                            # Start of event message
                            start_event = True
                            parse_string += str_line
                        elif str_line.find('</EventNotificationAlert>') != -1:
                            # Message end found found
                            parse_string += str_line
                            start_event = False
                            if parse_string:
                                tree = ET.fromstring(parse_string)
                                self.process_stream(tree)
                                self.update_stale()
                                parse_string = ""
                        else:
                            if start_event:
                                parse_string += str_line

                    if kill_event.is_set():
                        # We were asked to stop the thread so lets do so.
                        break
                    elif reset_event.is_set():
                        # We need to reset the connection.
                        raise ValueError('Watchdog failed.')

                if kill_event.is_set():
                    # We were asked to stop the thread so lets do so.
                    _LOGGING.debug('Stopping event stream thread for %s',
                                   self.name)
                    self.watchdog.stop()
                    self.hik_request.close()
                    return
                elif reset_event.is_set():
                    # We need to reset the connection.
                    raise ValueError('Watchdog failed.')

            except (ValueError,
                    requests.exceptions.ConnectionError,
                    requests.exceptions.ChunkedEncodingError) as err:
                fail_count += 1
                reset_event.clear()
                _LOGGING.warning('%s Connection Failed (count=%d). Waiting %ss. Err: %s',
                                 self.name, fail_count, (fail_count * 5) + 5, err)
                parse_string = ""
                self.watchdog.stop()
                self.hik_request.close()
                time.sleep(5)
                self.update_stale()
                time.sleep(fail_count * 5)
                continue
1357723
def _display(self, sent, now, chunk, mbps):
        
        if self.parent is not None:
            self.parent._display(self.parent.offset + sent, now, chunk, mbps)
            return

        elapsed = now - self.startTime

        if sent > 0 and self.total is not None and sent <= self.total:
            eta = (self.total - sent) * elapsed.total_seconds() / sent
            eta = datetime.timedelta(seconds=eta)
        else:
            eta = None

        self.output.write(
            "\r %s: Sent %s%s%s ETA: %s (%s) %s%20s\r" % (
                elapsed,
                util.humanize(sent),
                "" if self.total is None else " of %s" % (util.humanize(self.total),),
                "" if self.total is None else " (%d%%)" % (int(100 * sent / self.total),),
                eta,
                "" if not mbps else "%.3g Mbps " % (mbps,),
                chunk or "",
                " ",
            )
        )

        self.output.flush()
690676
private void actionWillProduce()
    {
        if (checker.checkProduction(current))
        {
            startProduction(current);
            state = ProducerState.PRODUCING;
        }
        else
        {
            for (final ProducerListener listener : listeners)
            {
                listener.notifyCanNotProduce(current);
            }
        }
    }
794346
def update_stream(self):
        

        need_to_restart = False

        # If we think we are running, but something has gone wrong in the streaming thread
        # Restart it.
        if self.stream is not None and not self.stream.running:
            logger.warning("Stream exists but isn't running")
            self.listener.error = False
            self.listener.streaming_exception = None
            need_to_restart = True

        # Check if the tracking list has changed
        if self.term_checker.check():
            logger.info("Terms have changed")
            need_to_restart = True

        # If we aren't running and we are allowing unfiltered streams
        if self.stream is None and self.unfiltered:
            need_to_restart = True

        if not need_to_restart:
            return

        logger.info("Restarting stream...")
        
        # Stop any old stream
        self.stop_stream()

        # Start a new stream
        self.start_stream()
105308
def is_running(self):
        
        return self._process.state() in [self._process.Running, self._process.Starting]
684368
protected function logProcessStandardStreams(): void
    {
        if (!empty($output = $this->process->getIncrementalOutput())) {
            $this->logger->notice('Received data on stdout: {output}', [
                'pid' => $this->processPid,
                'stream' => 'stdout',
                'output' => $output,
            ]);
        }

        if (!empty($errorOutput = $this->process->getIncrementalErrorOutput())) {
            $this->logger->error('Received data on stderr: {output}', [
                'pid' => $this->processPid,
                'stream' => 'stderr',
                'output' => $errorOutput,
            ]);
        }
    }
727640
function realtimeSimulationPipe(stream) {
  const parser = csv.parse({delimeter: ",", columns: true});
  return Bacon
  .fromEvent(stream.pipe(parser), 'data')
  .bufferingThrottle(1000 / 50)
  .map(v => Object.assign({}, v, { time: new Date().getTime() }))
}
354918
def handle_streams(stdout_stream, stderr_stream, &block)
        logger.debug "Monitoring stdout/stderr streams for output"
        streams = [stdout_stream, stderr_stream]
        until streams.empty?
          # Find which streams are ready for reading, timeout 0.1s
          selected, = select(streams, nil, nil, 0.1)

          # Try again if none were ready
          next if selected.nil? or selected.empty?

          selected.each do |stream|
            if stream.eof?
              logger.debug "Stream reached end-of-file"
              if @success.nil?
                logger.debug "Process hasn't finished, keeping stream"
              else
                logger.debug "Removing stream"
                streams.delete(stream)
              end
              next
            end

            while data = @reader.call(stream)
              data = ((@options[:mode] == :chars) ? data.chr : data)
              stream_name = (stream == stdout_stream) ? :stdout : :stderr
              output data, stream_name, &block unless block.nil?
              buffer data, stream_name unless @options[:no_buffer]
            end
          end
        end
      end
724758
def pause():
    ''''''

    server = getServer()
    server.core.playback.pause()
    pos = server.core.playback.get_time_position()
    print('Paused at {}'.format(formatTimeposition(pos)))
792776
function isStreamReady(self) {
	const method = 'isStreamReady';
	let ready = false;
	if (self._stream) {
		const stream = self._stream;
		ready = stream.readable && stream.writable && stream.reading;
		logger.debug('%s - stream.readable %s :: %s', method, stream.readable, self.getPeerAddr());
		logger.debug('%s - stream.writable %s :: %s', method, stream.writable, self.getPeerAddr());
		logger.debug('%s - stream.reading %s :: %s', method, stream.reading, self.getPeerAddr());
		logger.debug('%s - stream.read_status %s :: %s', method, stream.read_status, self.getPeerAddr());
		logger.debug('%s - stream.received_status %s :: %s', method, stream.received_status, self.getPeerAddr());
	}

	return ready;
}
1081593
def IsRunning(self):
    """"""
    current_urn = self.Get(self.Schema.CURRENT_FLOW_URN)
    if not current_urn:
      return False

    try:
      current_flow = aff4.FACTORY.Open(
          urn=current_urn, aff4_type=flow.GRRFlow, token=self.token, mode="r")
    except aff4.InstantiationError:
      # This isn't a flow, something went really wrong, clear it out.
      logging.error("Unable to open cron job run: %s", current_urn)
      self.DeleteAttribute(self.Schema.CURRENT_FLOW_URN)
      self.Flush()
      return False

    return current_flow.GetRunner().IsRunning()
840936
@Override
    protected void checkForTimeouts() {
        final boolean bTrace = TraceComponent.isAnyTracingEnabled();

        // See if anything may have timed out
        final long now = super.currentTime;
        if (now < nextTimeoutTime) {
            if (bTrace && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "checkForTimeouts bypassing timeout processing");
            }
            return;
        }

        Set<SelectionKey> selectorKeys = selector.keys();
        if (bTrace && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "checkForTimeouts - checking " + selectorKeys.size() + " keys for timeouts");
        }
        if (selectorKeys.isEmpty()) {
            // if this isn't the primary (first) selector, see if it should be closed
            if (countIndex > 0) {
                // if we have already been waiting, and still no keys, and this
                // isn't the primary selector, we should close this
                if (waitingToQuit) {
                    quit = true;
                } else {
                    wqm.updateCount(countIndex, WorkQueueManager.CS_DELETE_IN_PROGRESS, channelType);
                    waitingToQuit = true;
                    nextTimeoutTime = now + TCPFactoryConfiguration.getChannelSelectorWaitToTerminate();
                }
            } else {
                nextTimeoutTime = now + TCPFactoryConfiguration.getChannelSelectorIdleTimeout();
            }
        } else {
            waitingToQuit = false;
            // go through requests, timing out those that need it, and calculating new
            // timeout
            // set nexttimeouttime to whatever the selectoridletimeout is, and work
            // back from there
            nextTimeoutTime = now + TCPFactoryConfiguration.getChannelSelectorIdleTimeout();
            for (SelectionKey key : selectorKeys) {
                try {
                    if (key.interestOps() <= 0) {
                        // skip if not waiting on read/writes
                        continue;
                    }
                    TCPBaseRequestContext req = (TCPBaseRequestContext) key.attachment();
                    if (!req.hasTimeout()) {
                        // skip if read/write does not have a timeout
                        continue;
                    }
                    if (req.getTimeoutTime() <= now) {
                        if (bTrace && tc.isEventEnabled()) {
                            Tr.event(this, tc, "Inactivity timeout on channel " + req.getTCPConnLink().getSocketIOChannel().getChannel());
                        }

                        // create timeout exception to pass to callback error method
                        // Add local and remote address information
                        String ioeMessage = "Socket operation timed out before it could be completed";
                        try {
                            SocketAddress iaLocal = req.getTCPConnLink().getSocketIOChannel().getSocket().getLocalSocketAddress();
                            SocketAddress iaRemote = req.getTCPConnLink().getSocketIOChannel().getSocket().getRemoteSocketAddress();
                            ioeMessage = ioeMessage + " local=" + iaLocal + " remote=" + iaRemote;
                        } catch (Exception x) {
                            // do not alter the message if the socket got nuked while we tried to look at it
                        }
                        IOException e = new SocketTimeoutException(ioeMessage);

                        if (wqm.dispatch(req, e)) {
                            // reset interest ops so selector won't fire again for this key
                            key.interestOps(0);
                        } else {
                            // try again in another second
                            nextTimeoutTime = now;
                        }
                    } else {
                        // adjust times for 1 second granularity of ApproxTime
                        if (req.getTimeoutTime() < nextTimeoutTime) {
                            nextTimeoutTime = req.getTimeoutTime();
                        }
                    }
                } catch (CancelledKeyException cke) {
                    // either we didn't get the key, or we already dispatched the
                    // error. In either case, there is nothing more to do
                    continue;
                }
            } // end-key-loop
        }
    }