inspired by `fibers/future`
179530
function wrap(fnOrObj, deepForFn) {
  if (typeof fnOrObj === 'object') {
    var wrapped = Object.create(fnOrObj);
    for(var k in fnOrObj){
      if(wrapped[k] instanceof Function) {
        wrapped[k] = wrap(wrapped[k], deepForFn);
      }
    }
    return wrapped;
  } else if (typeof fnOrObj === 'function') {
    var fn = function() {
      //fibext wrapped function
      //avoid leak arguments: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
      var $_len = arguments.length; var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
      
      var fiber = fibext(), rbw = false, ret;//rbw: resume before wait
      args.push(function(){
        ret = fiber.resume.apply(fiber, arguments);
        rbw = true;
      });
      fnOrObj.apply(this, args);
      rbw || (ret = fiber.wait());
      return ret;
    };
    fn.toString = function(){
      return 'fibext wrapped function: '+fnOrObj.toString();
    };

    // modules like `request` return a function that has more functions as properties. 
    if (deepForFn) {
      var proto = Object.create(fnOrObj);
      for (var pn in fnOrObj) {
        if (fnOrObj.hasOwnProperty(pn) && fnOrObj[pn] instanceof Function) {
          proto[pn] = proto[pn];
        }
      }
      fn.__proto__ = wrap(proto, false);
    }
    return fn;
  }
}
1074715
def sendFuture(self, future):
        """"""
        future = copy.copy(future)
        future.greenlet = None
        future.children = {}

        try:
            if shared.getConst(hash(future.callable), timeout=0):
                # Enforce name reference passing if already shared
                future.callable = SharedElementEncapsulation(hash(future.callable))
            self.socket.send_multipart([
                TASK,
                pickle.dumps(future.id, pickle.HIGHEST_PROTOCOL),
                pickle.dumps(future, pickle.HIGHEST_PROTOCOL),
            ])
        except (pickle.PicklingError, TypeError) as e:
            # If element not picklable, pickle its name
            # TODO: use its fully qualified name
            scoop.logger.warn("Pickling Error: {0}".format(e))
            future.callable = hash(future.callable)
            self.socket.send_multipart([
                TASK,
                pickle.dumps(future.id, pickle.HIGHEST_PROTOCOL),
                pickle.dumps(future, pickle.HIGHEST_PROTOCOL),
            ])
1168234
@SafeVarargs
    public static <T> ContinuableFuture<List<T>> allOf(final Future<? extends T>... cfs) {
        return allOf2(Arrays.asList(cfs));
    }
539163
private static String unwrapFutureString(CompletionStage<String> future) throws GetBytesException {
        try {
            return future.toCompletableFuture().get();
        } catch (Throwable e) {
            if (e.getCause() instanceof GetBytesException) {
                throw (GetBytesException) e.getCause();
            }
            throw new RuntimeException(e.getCause());
        }
    }
966363
function(futures) {
		this.resolve(function(err) {
			if (!err) {
				return;
			}
			if (futures instanceof Array) {
				for (var ii = 0; ii < futures.length; ++ii) {
					futures[ii].throw(err);
				}
			} else {
				futures.throw(err);
			}
		});
		return this;
	}
1048637
def next(self, *args):
        """"""
        self.initialize()
        self.future = asyncio.Future(loop=self.loop)
        self.handle = self.loop.call_at(self.get_next(), self.call_func, *args)
        return self.future
658640
function walk(patterns, cwd) {
	var externals, files, locals;

	if (typeof patterns === 'undefined') {
		return [];
	}

	patterns = (patterns instanceof Array) ? patterns : [patterns];
	cwd = cwd || process.cwd();

	externals = [];
	files = {};
	locals = {};

	each(patterns, function(pattern) {
		var globbed;

		globbed = glob.sync(pattern, {
			cwd: cwd
		});

		globbed.forEach(function(filename) {
			var file;

			file = new File(cwd, filename);
			files[file.path] = file;
		});
	});

	each(_flatten(files), function(file, path) {
		Array.prototype.push.apply(externals, file.external);
		locals[pubname(path, cwd)] = file;
	});

	unique(externals);

	return {
		externals: externals,
		locals: locals
	};
}
1365478
public static <A> Will<A> forFuture(Future<A> future) {
        return forListenableFuture(JdkFutureAdapters.listenInPoolThread(future));
    }
1079867
def sendFuture(self, future):
        """"""
        try:
            if shared.getConst(hash(future.callable),
                               timeout=0):
                # Enforce name reference passing if already shared
                future.callable = SharedElementEncapsulation(hash(future.callable))
            self.socket.send_multipart([b"TASK",
                                        pickle.dumps(future,
                                                     pickle.HIGHEST_PROTOCOL)])
        except pickle.PicklingError as e:
            # If element not picklable, pickle its name
            # TODO: use its fully qualified name
            scoop.logger.warn("Pickling Error: {0}".format(e))
            previousCallable = future.callable
            future.callable = hash(future.callable)
            self.socket.send_multipart([b"TASK",
                                        pickle.dumps(future,
                                                     pickle.HIGHEST_PROTOCOL)])
            future.callable = previousCallable
1155195
public <U> FutureStream<U> constructFutures(final Stream<CompletableFuture<U>> s) {
        final LazyReact toUse = withStreamOfFutures(true);
        return toUse.construct((Stream<U>) s);
    }
102588
private boolean acquireWriteFuture(int sliceLength) {
        if (sliceLength > 0) {
            Object writeResult = null;
            // determine a good timeout value based on the slice length to write
            int timeout = sliceLength * 500;
            // check for existing future
            if (writerFuture != null) {
                try {
                    // wait for a result from the last writer
                    writeResult = writerFuture.get(timeout, TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                    log.warn("Exception waiting for write result. Timeout: {}ms", timeout, e);
                    return false;
                }
            }
            log.debug("Write future result (expect null): {}", writeResult);
            return true;
        }
        return false;
    }
866355
def get_frame_with_future(self, frame_idx, env_idx):
        
        if frame_idx == self.current_idx:
            raise VelException("Cannot provide enough future for the frame")

        past_frame = self.get_frame(frame_idx, env_idx)

        if not self.dones_buffer[frame_idx, env_idx]:
            # We're not done
            next_idx = (frame_idx + 1) % self.buffer_capacity
            next_frame = self.state_buffer[next_idx, env_idx]

            if self.frame_history > 1:
                future_frame = np.concatenate([
                    past_frame.take(indices=np.arange(1, past_frame.shape[-1]), axis=-1), next_frame
                ], axis=-1)
            else:
                future_frame = next_frame
        else:
            # We are done
            future_frame = np.zeros_like(past_frame)

        return past_frame, future_frame
12589
@Override
    public Future<U> link(U current, BasicProfile to) {
        return toScala(doLink(current, to));
    }
969999
def map(self, fn):
        """"""
        return TimeSeries([(x, fn(y)) for x, y in self.points])
94785
public static <T> Future<T> narrowK(final Higher<future, T> future) {
        return (Future<T>)future;
    }
647441
def map(self, function, *iterables, **kwargs):
        
        self._check_pool_state()

        timeout = kwargs.get('timeout')
        chunksize = kwargs.get('chunksize', 1)

        if chunksize < 1:
            raise ValueError("chunksize must be >= 1")

        futures = [self.schedule(process_chunk, args=(function, chunk))
                   for chunk in iter_chunks(chunksize, *iterables)]

        map_future = MapFuture(futures)
        if not futures:
            map_future.set_result(MapResults(futures))
            return map_future

        def done_map(_):
            if not map_future.done():
                map_future.set_result(MapResults(futures, timeout=timeout))

        for future in futures:
            future.add_done_callback(done_map)
            setattr(future, 'map_future', map_future)

        return map_future
725653
def append(self, future):
        """"""
        if future._ended() and future.index is None:
            self.inprogress.add(future)
        elif future._ended() and future.index is not None:
            self.ready.append(future)
        elif future.greenlet is not None:
            self.inprogress.add(future)
        else:
            self.movable.append(future)

            # Send the oldest future in the movable deque until under the hwm
            over_hwm = self.timelen(self.movable) > self.highwatermark
            while over_hwm and len(self.movable) > 1:
                sending_future = self.movable.popleft()
                if sending_future.id[0] != scoop.worker:
                    sending_future._delete()
                self.socket.sendFuture(sending_future)
                over_hwm = self.timelen(self.movable) > self.highwatermark