Listens for respones from the chess webworker and updates observables awaiting the response
492325
function listenForWorkerResults() {
    chessWorker.addEventListener('message', (event) => {
      const gameId = event.data.reqid.gameRootMessage;
      const { ply } = event.data.reqid;

      if (event.data.topic === 'dests') {
        const destsMapKey = getDestsKey(gameId, ply);
        const awaitingDestsObs = get(awaitingWorkerResponses, destsMapKey);

        if (awaitingDestsObs) {
          const validDests = event.data.payload.dests;
          awaitingDestsObs.set(validDests);
          delete awaitingWorkerResponses[destsMapKey];
        }
      } else if (event.data.topic === 'threefoldTest') {
        const canDrawKey = getDrawKey(gameId, ply);

        const awaitingCanDraw = get(awaitingWorkerResponses, canDrawKey);

        if (awaitingCanDraw) {
          const canClaimDraw = event.data.payload.threefoldRepetition;
          awaitingCanDraw.set(canClaimDraw);
          delete awaitingWorkerResponses[canDrawKey];
        }
      }
    });
  }
1235786
async def observer_poll(self, message):
        """"""
        # Sleep until we need to notify the observer.
        await asyncio.sleep(message['interval'])

        # Dispatch task to evaluate the observable.
        await self.channel_layer.send(
            CHANNEL_WORKER, {'type': TYPE_EVALUATE, 'observer': message['observer']}
        )
899985
function reload() {
    var defer = q.defer();

    if (browserSync.active) {
        browserSync.reload();
        defer.resolve();
    } else
    startServer().then(defer.resolve);

    return defer.promise;
}
420533
function processWaitingPublishPromises( self, newPromiseResolves ) {
   const waitingResolves = self.waitingPromiseResolves_;
   self.waitingPromiseResolves_ = newPromiseResolves;

   waitingResolves.forEach( resolve => resolve() );

   if( self.eventQueue_.length === 0 ) {
      // nothing was queued by any subscriber. The publishers can instantly be notified of delivery.
      newPromiseResolves.forEach( resolve => resolve() );
      self.waitingPromiseResolves_ = [];
   }
}
979861
function turnOnListeningAndUpdate(listenToObservable, updateObservable, updateFunction, queue) {
	var onValueOrOnEmitFn;

	// Use either onValue or onEmit depending on which Symbols are on the `observable`
	if (listenToObservable[onValueSymbol]) {
		onValueOrOnEmitFn = canReflect.onValue;
	} else if (listenToObservable[onEmitSymbol]) {
		onValueOrOnEmitFn = onEmit;
	}

	if (onValueOrOnEmitFn) {
		onValueOrOnEmitFn(listenToObservable, updateFunction, queue);

		//!steal-remove-start
		if(process.env.NODE_ENV !== 'production') {

			// The updateObservable is mutated by listenToObservable
			canReflectDeps.addMutatedBy(updateObservable, listenToObservable);

			// The updateFunction mutates updateObservable
			updateFunction[getChangesSymbol] = function getChangesDependencyRecord() {
				var s = new Set();
				s.add(updateObservable);
				return {
					valueDependencies: s
				};
			};

		}

		//!steal-remove-end
	}
}
912833
function softwareUpdate_waitForCheckFinished(timeout) {
    timeout = timeout ? timeout : gTimeoutUpdateCheck;

    this._controller.waitFor(function() {
      return this.currentPage != WIZARD_PAGES.checking;
    }, "Check for updates has been completed.", timeout, null, this);
  }
1169449
def run(self):
        
        while not self.stopEvent.isSet():
            try:
                # no need to monitor if no observers
                if 0 < self.observable.countObservers():
                    currentReaders = self.readerProc()
                    addedReaders = []
                    removedReaders = []

                    if currentReaders != self.readers:
                        for reader in currentReaders:
                            if reader not in self.readers:
                                addedReaders.append(reader)
                        for reader in self.readers:
                            if reader not in currentReaders:
                                removedReaders.append(reader)

                        if addedReaders or removedReaders:
                            # Notify observers
                            self.readers = []
                            for r in currentReaders:
                                self.readers.append(r)
                            self.observable.setChanged()
                            self.observable.notifyObservers((addedReaders,
                                                            removedReaders))

                # wait every second on stopEvent
                self.stopEvent.wait(self.period)

            except Exception:
                # FIXME Tighten the exceptions caught by this block
                traceback.print_exc()
                # Most likely raised during interpreter shutdown due
                # to unclean exit which failed to remove all observers.
                # To solve this, we set the stop event and pass the
                # exception to let the thread finish gracefully.
                self.stopEvent.set()
181067
@Override
    public void waitForData() throws CouldNotPerformException, InterruptedException {
        try {
            if (isDataAvailable()) {
                return;
            }
            logger.debug("Wait for " + this.toString() + " data...");
            getDataFuture().get();
            dataObservable.waitForValue();
        } catch (ExecutionException | CancellationException ex) {
            if (shutdownInitiated) {
                throw new InterruptedException("Interrupt request because system shutdown was initiated!");
            }
            throw new CouldNotPerformException("Could not wait for data!", ex);
        }
    }
1086754
def _wait_for_state_change(self, target_states, update_interval=10):
        
        while self.state not in target_states:
            if self.state == 'error':
                raise Exception('server is in error state')

            # update server state every 10s
            sleep(update_interval)
            self.populate()
206360
def wait_for_datasocket(interval = 0.1, &block)
      if @datasocket.nil? && interval < 25
        if EM.reactor_running?
          EventMachine.add_timer(interval) { wait_for_datasocket(interval * 2, &block) }
        else
          sleep interval
          wait_for_datasocket(interval * 2, &block)
        end
        return
      end
      yield @datasocket
    end
774422
def handleIncomingReply(self, observer_name, reqId, frm, result,
                            numReplies):
        
        preparedReq = self._prepared.get((result[IDENTIFIER], reqId))
        if not preparedReq:
            raise RuntimeError('no matching prepared value for {},{}'.
                               format(result[IDENTIFIER], reqId))
        typ = result.get(TXN_TYPE)
        if typ and typ in self.replyHandler:
            self.replyHandler[typ](result, preparedReq)
200551
function bindCallback(callbackFunc, resultSelector, scheduler) {
    if (resultSelector) {
        if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_4__["isScheduler"])(resultSelector)) {
            scheduler = resultSelector;
        }
        else {
            return function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_3__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
            };
        }
    }
    return function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var context = this;
        var subject;
        var params = {
            context: context,
            subject: subject,
            callbackFunc: callbackFunc,
            scheduler: scheduler,
        };
        return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) {
            if (!scheduler) {
                if (!subject) {
                    subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"]();
                    var handler = function () {
                        var innerArgs = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            innerArgs[_i] = arguments[_i];
                        }
                        subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
                        subject.complete();
                    };
                    try {
                        callbackFunc.apply(context, args.concat([handler]));
                    }
                    catch (err) {
                        subject.error(err);
                    }
                }
                return subject.subscribe(subscriber);
            }
            else {
                var state = {
                    args: args, subscriber: subscriber, params: params,
                };
                return scheduler.schedule(dispatch, 0, state);
            }
        });
    };
}
328146
function notifyAll(newState, newValue) {
    if (newState === webdriver.promise.Deferred.State_.REJECTED &&
        // We cannot check instanceof Error since the object may have been
        // created in a different JS context.
        goog.isObject(newValue) && goog.isString(newValue.message)) {
      newValue = flow.annotateError(/** @type {!Error} */(newValue));
    }

    state = newState;
    value = newValue;
    while (listeners.length) {
      notify(listeners.shift());
    }

    if (!handled && state == webdriver.promise.Deferred.State_.REJECTED) {
      pendingRejectionKey = propagateError(value);
    }
  }
828264
function onHeaders(ev, status, newUrl, oldUrl, statusCode, method, referrer, headers, resourceType) {
    if (resourceType !== 'mainFrame') return;

    let headerArray = [];

    Object.keys(headers).forEach(name => {
      headers[name].forEach(value => {
        headerArray.push({ name, value });
      });
    });

    response = {
      url: newUrl,
      method,
      status: statusCode,
      contentType: headers['content-type'][0],
      headers: headerArray
    };

    notify([ 'header event', status, newUrl, oldUrl, statusCode, method, referrer, headers, resourceType ]);
  }
857780
def async_update(self):
        """"""
        _LOGGER.debug('Calling update on Alarm.com')
        response = None
        if not self._login_info:
            yield from self.async_login()
        try:
            with async_timeout.timeout(10, loop=self._loop):
                response = yield from self._websession.get(
                    self.ALARMDOTCOM_URL + '{}/main.aspx'.format(
                        self._login_info['sessionkey']),
                    headers={'User-Agent': 'Mozilla/5.0 '
                                           '(Windows NT 6.1; '
                                           'WOW64; rv:40.0) '
                                           'Gecko/20100101 '
                                           'Firefox/40.1'}
                )

            _LOGGER.debug('Response from Alarm.com: %s', response.status)
            text = yield from response.text()
            _LOGGER.debug(text)
            tree = BeautifulSoup(text, 'html.parser')
            try:
                self.state = tree.select(self.ALARM_STATE)[0].get_text()
                _LOGGER.debug(
                    'Current alarm state: %s', self.state)
                self.sensor_status = tree.select(self.SENSOR_STATUS)[0].get_text()
                _LOGGER.debug(
                    'Current sensor status: %s', self.sensor_status)
            except IndexError:
                # We may have timed out. Re-login again
                self.state = None
                self.sensor_status = None
                self._login_info = None
                yield from self.async_update()
        except (asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.error("Can not load login page from Alarm.com")
            return False
        finally:
            if response is not None:
                yield from response.release()
732636
function notifyAll(newState, newValue) {
    if (newState === webdriver.promise.Deferred.State_.REJECTED &&
        // We cannot check instanceof Error since the object may have been
        // created in a different JS context.
        goog.isObject(newValue) && goog.isString(newValue.message)) {
      newValue = flow.annotateError(/** @type {!Error} */(newValue));
    }

    state = newState;
    value = newValue;
    while (listeners.length) {
      notify(listeners.shift());
    }

    if (!handled && state == webdriver.promise.Deferred.State_.REJECTED) {
      flow.pendingRejections_ += 1;
      pendingRejectionKey = flow.timer.setTimeout(function() {
        pendingRejectionKey = null;
        flow.pendingRejections_ -= 1;
        flow.abortFrame_(value);
      }, 0);
    }
  }
533709
function(r) {
    if (!seenConnectionBanner) {
      self.emit('connected', r);
      seenConnectionBanner = true;
      deferredSetup.resolve(r);
      return;
    }

    if (r.hasOwnProperty("rx") && self.serialPortData === null) {
      self.ignoredResponses--;
      if (!self.timedSendsOnly) {
        self.linesRequested = r.rx - 1;
      }
      // -1 is okay, that just means wait until we've sent two lines to send again
    } else if (self.ignoredResponses > 0) {
      self.ignoredResponses--;
      return;
    } else {
        if (!self.timedSendsOnly) {
          self.linesRequested++;
        }
    }

    self._sendLines();
  }