TODO(sorvell): This will fail if distribution that affects this question is pending; this is expected to be exceedingly rare, but if the issue comes up, we can force a flush in this case.
961519
function firstComposedNode(insertionPoint) {
    var n$ = insertionPoint.assignedNodes({flatten: true});
    var root = this.getRootNode(insertionPoint);
    for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) {
      // means that we're composed to this spot.
      if (root.isFinalDestination(insertionPoint, n)) {
        return n;
      }
    }
  }
1256469
private void pollUpstream() {
    if (!awaitingInner) {
      return;
    }

    boolean localDone = this.done;

    // Try to move the new item into the reframer
    InnerT newUpstreamItem = newItem.getAndSet(null);
    if (newUpstreamItem != null) {
      reframer.push(newUpstreamItem);
      // and reset the awaiting flag, if the item arrived or upstream closed
      awaitingInner = false;
    } else if (localDone) {
      awaitingInner = false;
    }
  }
758602
async function withRetrys(fn) {
  let tryCount = 0
  while (true) {
    try {
      return await fn() // Do our action.
    } catch (e) {
      // Roughly double wait time each failure
      let waitTime = Math.pow(100, 1 + tryCount / 6)
      // Randomly jiggle wait time by 20% either way. No thundering herd.
      waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4))
      // Max out at two minutes
      waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS)
      console.log('ERROR', e)
      console.log(`will retry in ${waitTime / 1000} seconds`)
      tryCount += 1
      await new Promise(resolve => setTimeout(resolve, waitTime))
    }
    if (tryCount >= MAX_RETRYS) {
      console.log('Exiting. Maximum number of retrys reached.')
      // Now it's up to our environment to restart us.
      // Hopefully with a clean start, things will work better
      process.exit(1)
    }
  }
}
1258499
function update() {
    // TODO(sorvell): instead the root should always be enqueued to helps record that it is dirty.
    // Then, in `render`, the top most (in the distribution tree) "dirty" root should be rendered.
    var distributionRoot = this._findDistributionRoot(this.host);
    //console.log('update from', this.host, 'root', distributionRoot.host, distributionRoot._clean);
    if (distributionRoot._clean) {
      distributionRoot._clean = false;
      enqueue(function() {
        distributionRoot.render();
      });
    }
  }
375348
private <R> boolean requiresFinalizer(boolean parallelPublisher, Set<K> keysToInclude,
         DeliveryGuarantee deliveryGuarantee) {
      // Parallel publisher has to use the finalizer to consolidate intermediate values on the remote nodes
      return parallelPublisher ||
            // Using segments with exactly once does one segment at a time and requires consolidation
            keysToInclude == null && deliveryGuarantee == DeliveryGuarantee.EXACTLY_ONCE;
   }
1146929
private CompletableFuture<WriterFlushResult> flushPendingAppends(Duration timeout) {
        // Gather an InputStream made up of all the operations we can flush.
        FlushArgs flushArgs;
        try {
            flushArgs = getFlushArgs();
        } catch (DataCorruptionException ex) {
            return Futures.failedFuture(ex);
        }

        long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "flushPendingAppends");

        if (flushArgs.getLength() == 0 && flushArgs.getAttributes().isEmpty()) {
            // Nothing to flush.
            WriterFlushResult result = new WriterFlushResult();
            LoggerHelpers.traceLeave(log, this.traceObjectId, "flushPendingAppends", traceId, result);
            return CompletableFuture.completedFuture(result);
        }

        // Flush them.
        TimeoutTimer timer = new TimeoutTimer(timeout);
        CompletableFuture<Void> flush;
        if (flushArgs.getLength() == 0) {
            flush = CompletableFuture.completedFuture(null);
        } else {
            flush = createSegmentIfNecessary(
                    () -> this.storage.write(this.handle.get(), this.metadata.getStorageLength(), flushArgs.getStream(), flushArgs.getLength(), timer.getRemaining()),
                    timer.getRemaining());
        }

        if (!flushArgs.getAttributes().isEmpty()) {
            flush = flush.thenComposeAsync(v -> handleAttributeException(
                    this.dataSource.persistAttributes(this.metadata.getId(), flushArgs.attributes, timer.getRemaining())));
        }

        return flush
                .thenApplyAsync(v -> {
                    WriterFlushResult result = updateStatePostFlush(flushArgs);
                    LoggerHelpers.traceLeave(log, this.traceObjectId, "flushPendingAppends", traceId, result);
                    return result;
                }, this.executor)
                .exceptionally(ex -> {
                    if (Exceptions.unwrap(ex) instanceof BadOffsetException) {
                        // We attempted to write at an offset that already contained other data. This can happen for a number of
                        // reasons, but we do not have enough information here to determine why. We need to enter reconciliation
                        // mode, which will determine the actual state of the segment in storage and take appropriate actions.
                        setState(AggregatorState.ReconciliationNeeded);
                    }

                    // Rethrow all exceptions.
                    throw new CompletionException(ex);
                });
    }
1252013
public static void waitRandomlySquared(long maxMsRoot) {
		long random = (long) (Math.random() * maxMsRoot);
		try {
			Thread.sleep(random * random);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
1236211
function failFast(logLevel, lessThan) {
    var ll = LatticeLogs;

    if (logLevel) {
      var compareTo = lessThan || process.env.LATTICE_LOGLEVEL || ll.ERROR;
      if (!ll.equalOrBelow(logLevel, compareTo)) return true;
    }

    return /\b(NONE|OFF|NO|0)\b/i.test(process.env.LATTICE_ERRORS || '');
  }
917120
def needs_distribute_ready(self):
        ''''''
        # Try to pre-empty starvation by comparing current RDY against
        # the last value sent.
        alive = [c for c in self.connections() if c.alive()]
        if any(c.ready <= (c.last_ready_sent * 0.25) for c in alive):
            return True
1203743
private void waitForJournalFlush() throws UnavailableException {
    if (mFlushCounter == INVALID_FLUSH_COUNTER) {
      // Check this before the precondition.
      return;
    }

    RetryPolicy retry = new TimeoutRetry(FLUSH_RETRY_TIMEOUT_MS, FLUSH_RETRY_INTERVAL_MS);
    while (retry.attempt()) {
      try {
        mAsyncJournalWriter.flush(mFlushCounter);
        return;
      } catch (IOException e) {
        LOG.warn("Journal flush failed. retrying...", e);
      } catch (JournalClosedException e) {
        throw new UnavailableException(String.format("Failed to complete request: %s",
            e.getMessage()), e);
      } catch (Throwable e) {
        ProcessUtils.fatalError(LOG, e, "Journal flush failed");
      }
    }
    ProcessUtils.fatalError(LOG, "Journal flush failed after %d attempts", retry.getAttemptCount());
  }
1109436
def std_err(self):
        

        return np.sqrt(np.sum(np.square(self.resids), axis=0) / self.df_err)
645312
private boolean waitForAvailabilityInternal() {
      final Directory directory = indexManager.getDirectoryProvider().getDirectory();
      try {
         Lock lock = directory.obtainLock(IndexWriter.WRITE_LOCK_NAME);
         lock.close();
         return true;
      } catch (LockObtainFailedException lofe) {
         return false;
      } catch (IOException e) {
         log.error(e);
         return false;
      }
   }
814823
private void failAssignment(String streamSegmentName, Throwable reason) {
        finishPendingRequests(streamSegmentName, PendingRequest::completeExceptionally, reason);
    }
189552
private void flush(KafkaTransactionState transaction) throws FlinkKafka011Exception {
		if (transaction.producer != null) {
			transaction.producer.flush();
		}
		long pendingRecordsCount = pendingRecords.get();
		if (pendingRecordsCount != 0) {
			throw new IllegalStateException("Pending record count must be zero at this point: " + pendingRecordsCount);
		}

		// if the flushed requests has errors, we should propagate it also and fail the checkpoint
		checkErroneous();
	}
1152446
function safeUnstashAll() {
  // TODO: will a re-stash ever be needed? This is fine for now because this
  // basically assumes that this folows a `safeStashAll`
  return execP('git stash pop && git reset HEAD . && git stash pop --index')
    .catch(function(err) {
      if (err && err.message && err.message.indexOf('No stash found') > -1) {
        // this is ok. Caused by second `stash pop` returning and error
        return;
      }
      return Promise.reject(err);
    });
}
864768
public CircuitBreaker<R> withFailureThreshold(int failureThreshold) {
    Assert.isTrue(failureThreshold >= 1, "failureThreshold must be greater than or equal to 1");
    return withFailureThreshold(failureThreshold, failureThreshold);
  }
1064211
private boolean shouldSubmitMove(PolicyInfo policy,
      Map<String, Integer> nodeToNumBlocks,
      List<BlockInfo> stripeBlocks) {
    
    if (policy == null) {
      return true;
    }
    int targetRepl = Integer.parseInt(policy.getProperty("targetReplication"));
    int parityRepl = Integer.parseInt(policy.getProperty("metaReplication"));

    Codec codec = Codec.getCodec(policy.getCodecId());
    int numParityBlks = codec.parityLength;
    int numSrcBlks = stripeBlocks.size() - numParityBlks;
    int expectNumReplicas = numSrcBlks * targetRepl + numParityBlks * parityRepl;
    
    int actualNumReplicas = 0;
    for (int num : nodeToNumBlocks.values()) {
      actualNumReplicas += num;
    }
    
    if (actualNumReplicas != expectNumReplicas) {
      String msg = "Expected number of replicas in the stripe: " + expectNumReplicas 
          + ", but actual number is: " + actualNumReplicas + ". ";
      if (stripeBlocks.size() > 0) {
        msg += "filePath: " + stripeBlocks.get(0).file.getPath();
      }
      LOG.warn(msg);
    }
    return actualNumReplicas == expectNumReplicas;
  }