Helper method to poll the list of marker documents until all of them are gone.

@param core the core reference.
@param bucket the name of the bucket.
@return an observable completing when all marker documents are gone.
322961
private static Observable<Boolean> pollMarkerDocuments(final ClusterFacade core, final String bucket) {
        return Observable
            .from(FLUSH_MARKERS)
            .flatMap(new Func1<String, Observable<GetResponse>>() {
                @Override
                public Observable<GetResponse> call(final String id) {
                    return deferAndWatch(new Func1<Subscriber, Observable<? extends GetResponse>>() {
                        @Override
                        public Observable<? extends GetResponse> call(Subscriber subscriber) {
                            GetRequest request = new GetRequest(id, bucket);
                            request.subscriber(subscriber);
                            return core.send(request);
                        }
                    });
                }
            })
            .reduce(0, new Func2<Integer, GetResponse, Integer>() {
                @Override
                public Integer call(Integer foundDocs, GetResponse response) {
                    if (response.content() != null && response.content().refCnt() > 0) {
                        response.content().release();
                    }
                    if (response.status() == ResponseStatus.SUCCESS) {
                        foundDocs++;
                    }
                    return foundDocs;
                }
            })
            .filter(new Func1<Integer, Boolean>() {
                @Override
                public Boolean call(Integer foundDocs) {
                    return foundDocs == 0;
                }
            })
            .repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() {
                @Override
                public Observable<?> call(Observable<? extends Void> observable) {
                    return observable.flatMap(new Func1<Void, Observable<?>>() {
                        @Override
                        public Observable<?> call(Void aVoid) {
                            return Observable.timer(500, TimeUnit.MILLISECONDS);
                        }
                    });
                }
            })
            .take(1)
            .map(new Func1<Integer, Boolean>() {
                @Override
                public Boolean call(Integer integer) {
                    return true;
                }
            });
    }
547184
public Observable<UsagesListResultInner> listUsagesAsync(String location) {
        return listUsagesWithServiceResponseAsync(location).map(new Func1<ServiceResponse<UsagesListResultInner>, UsagesListResultInner>() {
            @Override
            public UsagesListResultInner call(ServiceResponse<UsagesListResultInner> response) {
                return response.body();
            }
        });
    }
986106
@Nonnull
  @VisibleForTesting
  List<CompletableFuture<AppendEntriesResponse>> sendRequests(final RaftStateContext ctx) {

    List<CompletableFuture<AppendEntriesResponse>> responses =
        managers.values().stream()
            .map(ReplicaManager::requestUpdate)
            .collect(toList());

    responses.forEach(response ->
        response.thenAccept(result -> {
          updateCommitted();
          checkTermOnResponse(ctx, result);
        }));


    // Cope if we're the only node in the cluster.
    if (responses.isEmpty()) {
      updateCommitted();
    }

    return responses;
  }
1042923
public void stream(@Nonnull final ApiStreamObserver<DocumentSnapshot> responseObserver) {
    stream(
        new QuerySnapshotObserver() {
          @Override
          public void onNext(QueryDocumentSnapshot documentSnapshot) {
            responseObserver.onNext(documentSnapshot);
          }

          @Override
          public void onError(Throwable throwable) {
            responseObserver.onError(throwable);
          }

          @Override
          public void onCompleted() {
            responseObserver.onCompleted();
          }
        },
        null);
  }
607252
public static <T extends Comparable<T>> void bucketSort(final List<T> c, final int fromIndex, final int toIndex) {
        Array.bucketSort(c, fromIndex, toIndex);
    }
725228
public Observable<ServiceResponse<Void>> deleteIterationWithServiceResponseAsync(UUID projectId, UUID iterationId) {
        if (projectId == null) {
            throw new IllegalArgumentException("Parameter projectId is required and cannot be null.");
        }
        if (iterationId == null) {
            throw new IllegalArgumentException("Parameter iterationId is required and cannot be null.");
        }
        if (this.client.apiKey() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null.");
        }
        return service.deleteIteration(projectId, iterationId, this.client.apiKey(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteIterationDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }
1363135
private void completeResponse(final CouchbaseResponse response,
        final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
        // Noone is listening anymore, handle tracing and/or orphan reporting
        // depending on if enabled or not.
        CouchbaseRequest request = response.request();
        if (request != null && !request.isActive()) {
            if (env().operationTracingEnabled() && request.span() != null) {
                Scope scope = env().tracer().scopeManager()
                        .activate(request.span(), true);
                scope.span().setBaggageItem("couchbase.orphan", "true");
                scope.close();
            }
            if (env().orphanResponseReportingEnabled()) {
                env().orphanResponseReporter().report(response);
            }
        }

        try {
            observable.onNext(response);
            observable.onCompleted();
        } catch (Exception ex) {
            LOGGER.warn("Caught exception while onNext on observable", ex);
            observable.onError(ex);
        }
    }
1322219
@Nonnull
  public ApiFuture<DocumentSnapshot> get(@Nonnull DocumentReference documentRef) {
    Preconditions.checkState(isEmpty(), READ_BEFORE_WRITE_ERROR_MSG);

    return ApiFutures.transform(
        firestore.getAll(new DocumentReference[] {documentRef}, /*fieldMask=*/ null, transactionId),
        new ApiFunction<List<DocumentSnapshot>, DocumentSnapshot>() {
          @Override
          public DocumentSnapshot apply(List<DocumentSnapshot> snapshots) {
            return snapshots.isEmpty() ? null : snapshots.get(0);
          }
        });
  }
627987
public Observable<Page<GeoRegionInner>> listGeoRegionsAsync() {
        return listGeoRegionsWithServiceResponseAsync()
            .map(new Func1<ServiceResponse<Page<GeoRegionInner>>, Page<GeoRegionInner>>() {
                @Override
                public Page<GeoRegionInner> call(ServiceResponse<Page<GeoRegionInner>> response) {
                    return response.body();
                }
            });
    }
1308742
@Private
  @Override
  public void aggregationCompleted(final List<Integer> taskletIds, final TOutput result) {
    try {
      completedTasklets(result, taskletIds);
    } catch (final InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
154143
static <T> void bucketSort(final List<? extends T> c, final int fromIndex, final int toIndex, final Comparator<? super T> cmp) {
        N.checkFromToIndex(fromIndex, toIndex, c == null ? 0 : c.size());

        if ((N.isNullOrEmpty(c) && fromIndex == 0 && toIndex == 0) || fromIndex == toIndex) {
            return;
        }

        if (toIndex - fromIndex < 32) {
            sort(c, fromIndex, toIndex, cmp);
            return;
        }

        final Comparator<? super T> comparator = cmp == null ? Comparators.NATURAL_ORDER : cmp;
        final Multiset<T> multiset = new Multiset<>();
        ListIterator<T> itr = (ListIterator<T>) c.listIterator(fromIndex);
        int i = fromIndex;

        while (itr.hasNext()) {
            if (i++ >= toIndex) {
                break;
            }

            multiset.add(itr.next());
        }

        final Map<T, Integer> m = multiset.toMapSortedBy(new Comparator<Map.Entry<T, MutableInt>>() {
            @Override
            public int compare(Entry<T, MutableInt> a, Entry<T, MutableInt> b) {
                return comparator.compare(a.getKey(), a.getKey());
            }
        });

        itr = (ListIterator<T>) c.listIterator(fromIndex);

        for (Map.Entry<T, Integer> entry : m.entrySet()) {
            final T key = entry.getKey();
            for (int j = 0; j < entry.getValue(); j++) {
                itr.next();
                itr.set(key);
            }
        }
    }
129
private Observable<DocumentFragment<Lookup>> getCountIn(final String id, final LookupSpec spec,
        final long timeout, final TimeUnit timeUnit) {
        return Observable.defer(new Func0<Observable<DocumentFragment<Lookup>>>() {
            @Override
            public Observable<DocumentFragment<Lookup>> call() {
                final SubGetCountRequest request = new SubGetCountRequest(id, spec.path(), bucketName);
                request.xattr(spec.xattr());
                request.accessDeleted(accessDeleted);
                addRequestSpan(environment, request, "subdoc_count");
                return applyTimeout(deferAndWatch(new Func1<Subscriber, Observable<SimpleSubdocResponse>>() {
                    @Override
                    public Observable<SimpleSubdocResponse> call(Subscriber s) {
                        request.subscriber(s);
                        return core.send(request);
                    }
                }).map(new Func1<SimpleSubdocResponse, DocumentFragment<Lookup>>() {
                    @Override
                    public DocumentFragment<Lookup> call(SimpleSubdocResponse response) {
                        try {
                            if (response.status().isSuccess()) {
                                try {
                                    long count = subdocumentTranscoder.decode(response.content(), Long.class);
                                    SubdocOperationResult<Lookup> single = SubdocOperationResult
                                        .createResult(spec.path(), Lookup.GET_COUNT, response.status(), count);
                                    return new DocumentFragment<Lookup>(id, response.cas(), response.mutationToken(),
                                        Collections.singletonList(single));
                                } finally {
                                    if (response.content() != null) {
                                        response.content().release();
                                    }
                                }
                            } else {
                                if (response.content() != null && response.content().refCnt() > 0) {
                                    response.content().release();
                                }

                                if (response.status() == ResponseStatus.SUBDOC_PATH_NOT_FOUND) {
                                    SubdocOperationResult<Lookup> single = SubdocOperationResult
                                        .createResult(spec.path(), Lookup.GET_COUNT, response.status(), null);
                                    return new DocumentFragment<Lookup>(id, response.cas(), response.mutationToken(), Collections.singletonList(single));
                                } else {
                                    throw SubdocHelper.commonSubdocErrors(response.status(), id, spec.path());
                                }
                            }
                        } finally {
                            if (environment.operationTracingEnabled()) {
                                environment.tracer().scopeManager()
                                    .activate(response.request().span(), true)
                                    .close();
                            }
                        }
                    }
                }), request, environment, timeout, timeUnit);
            }
        });
    }
486334
@Override
    public void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) {
        forget(point, AllocationStatus.HOST);

        flowController.waitTillReleased(point);

        // we call for caseless deallocation here
        //JCudaDriver.cuCtxSetCurrent(contextPool.getCuContextForDevice(0));
        free(point, AllocationStatus.HOST);

        point.setAllocationStatus(AllocationStatus.DEALLOCATED);

        long reqMem = AllocationUtils.getRequiredMemory(point.getShape()) * -1;
        zeroUseCounter.addAndGet(reqMem);
    }
979961
public synchronized TaskStatus findFinishedMap(int mapId) {
    TaskInProgress tip = maps[mapId];
    if (tip.isComplete()) {
      TaskStatus[] statuses = tip.getTaskStatuses();
      for(int i=0; i < statuses.length; i++) {
        if (statuses[i].getRunState() == TaskStatus.State.SUCCEEDED) {
          return statuses[i];
        }
      }
    }
    return null;
  }
677404
private void pushSnapshot(final Timestamp readTime, ByteString nextResumeToken) {
    final List<DocumentChange> changes = computeSnapshot(readTime);
    if (!hasPushed || !changes.isEmpty()) {
      final QuerySnapshot querySnapshot =
          QuerySnapshot.withChanges(query, readTime, documentSet, changes);
      userCallbackExecutor.execute(
          new Runnable() {
            @Override
            public void run() {
              listener.onEvent(querySnapshot, null);
            }
          });
      hasPushed = true;
    }

    changeMap.clear();
    resumeToken = nextResumeToken;
  }
942439
public Histogram<T> setBucketCount( int count ) {
        if (count != this.bucketCount) {
            this.bucketCount = count;
            this.bucketWidth = null;
            this.buckets.clear();
        }
        return this;
    }
361750
protected void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) {
        allocationsMap.remove(objectId);

        memoryHandler.purgeZeroObject(bucketId, objectId, point, copyback);

        getFlowController().getEventsProvider().storeEvent(point.getLastWriteEvent());
        getFlowController().getEventsProvider().storeEvent(point.getLastReadEvent());
    }