Map per-topic results to per-topic futures in futmap.
        The result value of each (successful) future is None.
510895
def _make_topics_result(f, futmap):
        
        try:
            result = f.result()
            for topic, error in result.items():
                fut = futmap.get(topic, None)
                if fut is None:
                    raise RuntimeError("Topic {} not found in future-map: {}".format(topic, futmap))

                if error is not None:
                    # Topic-level exception
                    fut.set_exception(KafkaException(error))
                else:
                    # Topic-level success
                    fut.set_result(None)
        except Exception as e:
            # Request-level exception, raise the same for all topics
            for topic, fut in futmap.items():
                fut.set_exception(e)
722929
def _get_results(FetcherClass, services, kwargs, num_results=None, fast=0, verbose=False, timeout=None):
    
    results = []

    if not num_results or fast:
        num_results = len(services)

    with futures.ThreadPoolExecutor(max_workers=len(services)) as executor:
        fetches = {}
        for service in services[:num_results]:
            tail = [x for x in services if x is not service]
            random.shuffle(tail)
            srv = FetcherClass(services=[service] + tail, verbose=verbose, timeout=timeout)
            fetches[executor.submit(srv.action, **kwargs)] = srv

        if fast == 1:
            raise NotImplementedError
            # ths code is a work in progress. futures.FIRST_COMPLETED works differently than I thought...
            to_iterate, still_going = futures.wait(fetches, return_when=futures.FIRST_COMPLETED)
            for x in still_going:
                try:
                    x.result(timeout=1.001)
                except futures._base.TimeoutError:
                    pass

        elif fast > 1:
            raise Exception("fast level greater than 1 not yet implemented")
        else:
            to_iterate = futures.as_completed(fetches)

        for future in to_iterate:
            service = fetches[future]
            results.append([service, future.result()])

    return results
271456
private function unmapTopic($topic)
    {
        if (array_key_exists($topic, self::ID_TO_TOPIC_ENUM)) {
            $result = self::ID_TO_TOPIC_ENUM[$topic];
            $this->logger->debug(sprintf('Topic ID "%s" has been unmapped to "%s".', $topic, $result));
        } else {
            $result = $topic;
            $this->logger->debug(sprintf('Topic ID "%s" does not exist in enum.', $topic));
        }

        return $result;
    }
1064104
def map_overlay_forecast(self):
        """"""
        return json.loads(self._query(LAYER, FORECAST, ALL, CAPABILITIES, "").decode(errors="replace"))
538613
def map_each(unit, options = {}, &block)
      iterate(unit, options.merge(:map_result => true), &block)
    end
239628
def sendResult(self, future):
        """"""
        future = copy.copy(future)

        # Remove the (now) extraneous elements from future class
        future.callable = future.args = future.kargs = future.greenlet = None

        if not future.sendResultBack:
            # Don't reply back the result if it isn't asked
            future.resultValue = None

        self._sendReply(
            future.id.worker,
            pickle.dumps(
                future,
                pickle.HIGHEST_PROTOCOL,
            ),
        )
612107
def _prepare_results(self, results):
        
        # if we want a result sorted by a score, and if we have a full result
        # (no slice), we can do it know, by creating keys for each values with
        # the sorted set score, and sort on them
        if self._sort_by_sortedset_after and (len(results) > 1 or self._values):
            conn = self.cls.get_connection()

            sort_params = {}
            base_tmp_key, tmp_keys = self._prepare_sort_by_score(results, sort_params)

            # compose the set to sort
            final_set = '%s_final_set' % base_tmp_key
            conn.sadd(final_set, *results)

            # apply the sort
            results = conn.sort(final_set, **sort_params)

            # finally delete all temporary keys
            conn.delete(*(tmp_keys + [final_set, base_tmp_key]))

        if self._store:
            # if store, redis doesn't return result, so don't return anything here
            return

        if self._values and self._values['mode'] != 'flat':
            results = self._to_values(results)

        return super(ExtendedCollectionManager, self)._prepare_results(results)
1246539
def _set_future_result(self):
        """"""
        # This must be done in a lock to prevent the polling thread
        # and main thread from both executing the completion logic
        # at the same time.
        with self._completion_lock:
            # If the operation isn't complete or if the result has already been
            # set, do not call set_result/set_exception again.
            # Note: self._result_set is set to True in set_result and
            # set_exception, in case those methods are invoked directly.
            if self.state != _DONE_STATE or self._result_set:
                return

            if self.error_result is not None:
                exception = _error_result_to_exception(self.error_result)
                self.set_exception(exception)
            else:
                self.set_result(self)
1367873
def for_each_time_range(t)
      RedisAnalytics.redis_key_timestamps.map{|x, y| t.strftime(x)}.each do |ts|
        yield(ts)
      end
    end
278357
def _make_resource_result(f, futmap):
        
        try:
            result = f.result()
            for resource, configs in result.items():
                fut = futmap.get(resource, None)
                if fut is None:
                    raise RuntimeError("Resource {} not found in future-map: {}".format(resource, futmap))
                if resource.error is not None:
                    # Resource-level exception
                    fut.set_exception(KafkaException(resource.error))
                else:
                    # Resource-level success
                    # configs will be a dict for describe_configs()
                    # and None for alter_configs()
                    fut.set_result(configs)
        except Exception as e:
            # Request-level exception, raise the same for all resources
            for resource, fut in futmap.items():
                fut.set_exception(e)
666631
def and_return_future(self, *return_values):
        
        futures = []
        for value in return_values:
            future = _get_future()
            future.set_result(value)
            futures.append(future)
        return self.and_return(*futures)
933083
ApiFuture<List<DocumentSnapshot>> getAll(
      final DocumentReference[] documentReferences,
      @Nullable FieldMask fieldMask,
      @Nullable ByteString transactionId) {
    final SettableApiFuture<List<DocumentSnapshot>> futureList = SettableApiFuture.create();
    final Map<DocumentReference, DocumentSnapshot> resultMap = new HashMap<>();

    ApiStreamObserver<BatchGetDocumentsResponse> responseObserver =
        new ApiStreamObserver<BatchGetDocumentsResponse>() {
          int numResponses;

          @Override
          public void onNext(BatchGetDocumentsResponse response) {
            DocumentReference documentReference;
            DocumentSnapshot documentSnapshot;

            numResponses++;
            if (numResponses == 1) {
              tracer.getCurrentSpan().addAnnotation("Firestore.BatchGet: First response");
            } else if (numResponses % 100 == 0) {
              tracer.getCurrentSpan().addAnnotation("Firestore.BatchGet: Received 100 responses");
            }

            switch (response.getResultCase()) {
              case FOUND:
                documentReference =
                    new DocumentReference(
                        FirestoreImpl.this, ResourcePath.create(response.getFound().getName()));
                documentSnapshot =
                    DocumentSnapshot.fromDocument(
                        FirestoreImpl.this,
                        Timestamp.fromProto(response.getReadTime()),
                        response.getFound());
                break;
              case MISSING:
                documentReference =
                    new DocumentReference(
                        FirestoreImpl.this, ResourcePath.create(response.getMissing()));
                documentSnapshot =
                    DocumentSnapshot.fromMissing(
                        FirestoreImpl.this,
                        documentReference,
                        Timestamp.fromProto(response.getReadTime()));
                break;
              default:
                return;
            }

            resultMap.put(documentReference, documentSnapshot);
          }

          @Override
          public void onError(Throwable throwable) {
            tracer.getCurrentSpan().addAnnotation("Firestore.BatchGet: Error");
            futureList.setException(throwable);
          }

          @Override
          public void onCompleted() {
            tracer.getCurrentSpan().addAnnotation("Firestore.BatchGet: Complete");
            List<DocumentSnapshot> documentSnapshots = new ArrayList<>();

            for (DocumentReference documentReference : documentReferences) {
              documentSnapshots.add(resultMap.get(documentReference));
            }

            futureList.set(documentSnapshots);
          }
        };

    BatchGetDocumentsRequest.Builder request = BatchGetDocumentsRequest.newBuilder();
    request.setDatabase(getDatabaseName());

    if (fieldMask != null) {
      request.setMask(fieldMask.toPb());
    }

    if (transactionId != null) {
      request.setTransaction(transactionId);
    }

    for (DocumentReference docRef : documentReferences) {
      request.addDocuments(docRef.getName());
    }

    tracer
        .getCurrentSpan()
        .addAnnotation(
            "Firestore.BatchGet: Start",
            ImmutableMap.of(
                "numDocuments", AttributeValue.longAttributeValue(documentReferences.length)));

    streamRequest(request.build(), responseObserver, firestoreClient.batchGetDocumentsCallable());

    return futureList;
  }
17232
def reducer_output(self, metro, values):
        
        records = []
        # build up list of data for each metro area and submit as one network
        # call instead of individually 
        for value in values:
            total, poi = value
            records.append(dict(
                metro_area=metro,
                poi=poi,
                count=total
            ))
            output = "{0}\t{1}\t{2}"
            output = output.format(metro.encode('utf-8'), total, poi.encode('utf-8'))
            yield None, output
        if self.mongo:
            self.mongo.insert_many(records)
1315116
def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None):
        
        future = None

        # Initialize variables to 0
        dd, hh, mm, ss = [0 for i in range(4)]
        if (in_days != None):
            dd = dd + in_days
        if (in_hours != None):
            hh = hh + in_hours
        if (in_minutes != None):
            mm = mm + in_minutes
        if (in_seconds != None):
            ss = ss + in_seconds

        # Set the hours, minutes and seconds from now (minus the days)
        dnow = datetime.datetime.utcnow()  # Now
        d = dnow + \
            datetime.timedelta(hours=hh, minutes=mm, seconds = ss)
        # Time from midnight
        for_total_seconds = d - \
            d.replace(hour=0, minute=0, second=0, microsecond=0)

        # Convert into minutes since midnight
        try:
            msm = for_total_seconds.total_seconds()/60.
        except:
            # For versions before 2.7
            msm = self.timedelta_total_seconds(for_total_seconds)/60.

        if (dd<len(self.days)):
            for timestep in self.days[dd].timesteps:
                if timestep.name >= msm:
                    future = timestep
                    return future
        else:
            print('ERROR: requested date is outside the forecast range selected,' + str(len(self.days)))
            return False
649312
def where_entry_visible_future(query):
    

    return orm.select(
        e for e in query
        if e.status in (model.PublishStatus.PUBLISHED.value,
                        model.PublishStatus.SCHEDULED.value))
614647
function resultRaw (results) {
    // throw error if results required and not retrieved
    if (this.args.required && !results.length) {
        // throw error
        throw this.error('no records found')
    }
    // if only ids were selected the return result object to fetch records
    if (this.select.isSelectOnlyIds) {
        // build result object
        var result = new ImmutableCoreModelResult({
            query: this,
            results: results,
        })
        // return result or all records if specified
        return this.args.all ? result.all() : result
    }
    // otherwise return ImmutableCoreModelInstance record(s)
    else {
        // query is for a single record
        if (this.args.limit === 1) {
            // return new instance or undefined
            return results.length
                ? this.newInstance(results[0])
                : undefined
        }
        // query is for multiple records
        else {
            return _.map(results, result => this.newInstance(result))
        }
    }
}
31647
function promiseMap(items, mapper, opt) {
  switch (items.length) {
    case 0:
      return mapZero();
    case 1:
      return mapOne(items, mapper);
    default:
      return mapMany(items, mapper, opt);
  }
}