the shared allocation optimization.
165969
private void addArcInitialization(EnumDeclaration node) {
    String enumClassName = nameTable.getFullName(node.getTypeElement());
    List<Statement> stmts = node.getClassInitStatements().subList(0, 0);
    int i = 0;
    for (EnumConstantDeclaration constant : node.getEnumConstants()) {
      VariableElement varElement = constant.getVariableElement();
      ClassInstanceCreation creation = new ClassInstanceCreation(constant.getExecutablePair());
      TreeUtil.copyList(constant.getArguments(), creation.getArguments());
      Expression constName = options.stripEnumConstants()
          ? new StringLiteral("JAVA_LANG_ENUM_NAME_STRIPPED", typeUtil)
          : new NativeExpression(
            UnicodeUtils.format("JreEnumConstantName(%s_class_(), %d)", enumClassName, i),
            typeUtil.getJavaString().asType());
      creation.addArgument(constName);
      creation.addArgument(new NumberLiteral(i++, typeUtil));
      creation.setHasRetainedResult(true);
      stmts.add(new ExpressionStatement(new Assignment(new SimpleName(varElement), creation)));
    }
  }
537272
def main(dimension, iterations):
    
    optimizer = PSOOptimizer()
    solution = optimizer.minimize(sphere, -5.12, 5.12, dimension,
                                  max_iterations(iterations))
    return solution, optimizer
872723
function( cmp ){
      var self = this;
      var P = this._private.pass[0].length;
      var subsize = this.spreadSize();
      var N = this.length;

      cmp = cmp || function( a, b ){ // default comparison function
        if( a < b ){
          return -1;
        } else if( a > b ){
          return 1;
        }

        return 0;
      };

      self.require( cmp, '_$_$_cmp' );

      return self.spread(function( split ){ // sort each split normally
        var sortedSplit = split.sort( _$_$_cmp );
        resolve( sortedSplit );

      }).then(function( joined ){
        // do all the merging in the main thread to minimise data transfer

        // TODO could do merging in separate threads but would incur add'l cost of data transfer
        // for each level of the merge

        var merge = function( i, j, max ){
          // don't overflow array
          j = Math.min( j, P );
          max = Math.min( max, P );

          // left and right sides of merge
          var l = i;
          var r = j;

          var sorted = [];

          for( var k = l; k < max; k++ ){

            var eleI = joined[i];
            var eleJ = joined[j];

            if( i < r && ( j >= max || cmp(eleI, eleJ) <= 0 ) ){
              sorted.push( eleI );
              i++;
            } else {
              sorted.push( eleJ );
              j++;
            }

          }

          // in the array proper, put the sorted values
          for( var k = 0; k < sorted.length; k++ ){ // kth sorted item
            var index = l + k;

            joined[ index ] = sorted[k];
          }
        };

        for( var splitL = subsize; splitL < P; splitL *= 2 ){ // merge until array is "split" as 1

          for( var i = 0; i < P; i += 2*splitL ){
            merge( i, i + splitL, i + 2*splitL );
          }

        }

        return joined;
      });
    }
1272393
@Override
    public PointersPair alloc(AllocationStatus targetMode, AllocationPoint point, AllocationShape shape,
                    boolean initialize) {

        long reqMemory = AllocationUtils.getRequiredMemory(shape);
        CudaContext context = getCudaContext();
        switch (targetMode) {
            case HOST: {
                if (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) {

                    while (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) {

                        val before = MemoryTracker.getInstance().getActiveHostAmount();
                        memoryProvider.purgeCache();
                        Nd4j.getMemoryManager().invokeGc();
                        val after = MemoryTracker.getInstance().getActiveHostAmount();

                        log.debug("[HOST] before: {}; after: {};", before, after);

                        if (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) {
                            try {
                                log.warn("No available [HOST] memory, sleeping for a while... Consider increasing -Xmx next time.");
                                log.debug("Currently used: [" + zeroUseCounter.get() + "], allocated objects: [" + zeroAllocations.get(0) + "]");

                                memoryProvider.purgeCache();
                                Nd4j.getMemoryManager().invokeGc();
                                Thread.sleep(1000);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }


                PointersPair pair = memoryProvider.malloc(shape, point, targetMode);


                if (initialize) {
                    org.bytedeco.javacpp.Pointer.memset(pair.getHostPointer(), 0, reqMemory);
                    point.tickHostWrite();
                }


                pickupHostAllocation(point);

                return pair;
            }
            case DEVICE: {
                int deviceId = getDeviceId();

                PointersPair returnPair = new PointersPair();
                PointersPair tmpPair = new PointersPair();

                // if the initial memory location is device, there's a chance we don't have zero memory allocated
                if (point.getPointers() == null || point.getPointers().getHostPointer() == null) {
                    tmpPair = alloc(AllocationStatus.HOST, point, point.getShape(), initialize);

                    returnPair.setDevicePointer(tmpPair.getHostPointer());
                    returnPair.setHostPointer(tmpPair.getHostPointer());

                    point.setAllocationStatus(AllocationStatus.HOST);
                    point.setPointers(tmpPair);
                }
/*
                if (reqMemory < configuration.getMaximumSingleHostAllocation()
                                && deviceMemoryTracker.getAllocatedSize(deviceId) + reqMemory < configuration
                                                .getMaximumDeviceAllocation()) {
*/


                    //val timeStart = System.nanoTime();
                    //long free = NativeOpsHolder.getInstance().getDeviceNativeOps().getDeviceFreeMemory();
                    //val timeEnd = System.nanoTime();

                    //log.info("Free time: {} ns; Free memory: {} bytes", (timeEnd - timeStart), free);

                    if (deviceMemoryTracker.reserveAllocationIfPossible(Thread.currentThread().getId(), deviceId, reqMemory)) {
                        point.setDeviceId(deviceId);
                        val pair = memoryProvider.malloc(shape, point, targetMode);
                        if (pair != null) {
                            returnPair.setDevicePointer(pair.getDevicePointer());

                            point.setAllocationStatus(AllocationStatus.DEVICE);

                            if (point.getPointers() == null)
                                throw new RuntimeException("PointersPair can't be null");

                            point.getPointers().setDevicePointer(pair.getDevicePointer());

                            deviceAllocations.get(deviceId).put(point.getObjectId(), point.getObjectId());


                            val p = point.getBucketId();

                            if (p != null) {
                                val m = zeroAllocations.get(point.getBucketId());

                                // m can be null, if that's point from workspace - just no bucketId for it
                                if (m != null)
                                    m.remove(point.getObjectId());
                            }

                            deviceMemoryTracker.addToAllocation(Thread.currentThread().getId(), deviceId, reqMemory);

                            //  point.tickDeviceWrite();
                            point.tickHostWrite();

                            if (!initialize) {
                                point.tickDeviceWrite();
                                point.tickHostRead();
                            } else {
                                nativeOps.memsetAsync(pair.getDevicePointer(), 0, reqMemory, 0,
                                                context.getSpecialStream());
                                context.getSpecialStream().synchronize();

                                point.tickDeviceWrite();
                                point.tickHostRead();

                                //AtomicAllocator.getInstance().getFlowController().registerAction(ctx, point);
                            }
                        } else {
                            log.warn("Out of [DEVICE] memory, host memory will be used instead: deviceId: [{}], requested bytes: [{}]; Approximate free bytes: {}; Real free bytes: {}", deviceId, reqMemory, MemoryTracker.getInstance().getApproximateFreeMemory(deviceId), MemoryTracker.getInstance().getPreciseFreeMemory(deviceId));
                            log.info("Total allocated dev_0: {}", MemoryTracker.getInstance().getActiveMemory(0));
                            log.info("Cached dev_0: {}", MemoryTracker.getInstance().getCachedAmount(0));
                            log.info("Allocated dev_0: {}", MemoryTracker.getInstance().getAllocatedAmount(0));
                            log.info("Workspace dev_0: {}", MemoryTracker.getInstance().getWorkspaceAllocatedAmount(0));
                            //log.info("Total allocated dev_1: {}", MemoryTracker.getInstance().getActiveMemory(1));
                            // if device memory allocation failed (aka returned NULL), keep using host memory instead

                            returnPair.setDevicePointer(tmpPair.getHostPointer());

                            point.setAllocationStatus(AllocationStatus.HOST);

                            Nd4j.getMemoryManager().invokeGc();
                            try {
                                Thread.sleep(100);
                            } catch (Exception e) {

                            }
                        }
                    } else {
                        log.warn("Hard limit on [DEVICE] memory hit, please consider tuning memory parameters, deviceId [{}]",
                                        deviceId);

                        Nd4j.getMemoryManager().invokeGc();
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            //
                        }
                    }

                return returnPair;
            }
            default:
                throw new IllegalStateException("Can't allocate memory on target [" + targetMode + "]");
        }
    }
598340
def allocate(self, handles, initial=False, params={}):
        """"""
        assert all(re.search('^\d+$', h) for h in handles), "All handles must be numbers: {}".format(handles)
        self.requests.put(('allocate', (handles, initial, params)))
95719
function allocate(height, length) {
	var node = new Array(length);
	node.height = height;
	if (height > 0) {
		node.sizes = new Array(length);
	}
	return node;
}
1362900
private void optimize(long fileLength) {

		final int availableProcessors = Runtime.getRuntime().availableProcessors();

		final long free = Runtime.getRuntime().freeMemory() / 2;

		int workerSize = availableProcessors / 2;
		if (workerSize < 2) {
			workerSize = 2;
		}

		long bufferSize = free / workerSize;
		if (bufferSize > 1 * 1024 * 1024) {
			bufferSize = 1 * 1024 * 1024;
		}

		long blockSize = fileLength / workerSize;
		if (blockSize > 1 * 1024 * 1024) {
			blockSize = 1 * 1024 * 1024;
		}
		int iBlockSize = (int) blockSize;

		if (bufferSize > blockSize) {
			bufferSize = blockSize;
		}
		int iBufferSize = (int) bufferSize;

		this.setBlockSize(iBlockSize);
		this.setMaxNumOfThreads(workerSize);
		this.setBufferSizePerWorker(iBufferSize);
		this.setSubBufferSize(256);

	}
156652
def maximize(self,
                 init_points=5,
                 n_iter=25,
                 acq='ucb',
                 kappa=2.576,
                 xi=0.0,
                 **gp_params):
        """"""
        self._prime_subscriptions()
        self.dispatch(Events.OPTMIZATION_START)
        self._prime_queue(init_points)
        self.set_gp_params(**gp_params)

        util = UtilityFunction(kind=acq, kappa=kappa, xi=xi)
        iteration = 0
        while not self._queue.empty or iteration < n_iter:
            try:
                x_probe = next(self._queue)
            except StopIteration:
                x_probe = self.suggest(util)
                iteration += 1

            self.probe(x_probe, lazy=False)

        self.dispatch(Events.OPTMIZATION_END)
701917
private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) {
        ByteBufAllocator alloc = ctx.alloc();
        if (engineType.wantsDirectBuffer) {
            return alloc.directBuffer(capacity);
        } else {
            return alloc.buffer(capacity);
        }
    }
872468
Allocation allocate(Mutation mutation, int size)
    {
        final OpOrder.Group opGroup = appendOrder.start();
        try
        {
            int position = allocate(size);
            if (position < 0)
            {
                opGroup.close();
                return null;
            }
            markDirty(mutation, position);
            return new Allocation(this, opGroup, position, (ByteBuffer) buffer.duplicate().position(position).limit(position + size));
        }
        catch (Throwable t)
        {
            opGroup.close();
            throw t;
        }
    }
742545
def optimize(self):
        """"""

        def te(weights, r, proxies):
            """Helper func.  `pyfinance.tracking_error` doesn't work here."""
            if isinstance(weights, list):
                weights = np.array(weights)
            proxy = np.sum(proxies * weights, axis=1)
            te = np.std(proxy - r)  # not anlzd...
            return te

        ew = utils.equal_weights(n=self.n, sumto=self.sumto)
        bnds = tuple((0, 1) for x in range(self.n))
        cons = {"type": "eq", "fun": lambda x: np.sum(x) - self.sumto}

        xs = []
        funs = []
        for i, j in zip(self._r, self._proxies):
            opt = sco.minimize(
                te,
                x0=ew,
                args=(i, j),
                method="SLSQP",
                bounds=bnds,
                constraints=cons,
            )
            x, fun = opt["x"], opt["fun"]
            xs.append(x)
            funs.append(fun)
        self._xs = np.array(xs)
        self._funs = np.array(funs)

        return self
845291
def optimize(self, x0, target):
        """"""
        x = x0
        for _ in range(self.maxiter):
            delta = np.linalg.solve(self.h(x, target), -self.g(x, target))
            x = x + delta
            if np.linalg.norm(delta) < self.tol:
                break
        return x
433807
def _optimize_binning(x, range, method='Freedman'):
    
    N = x.shape[0]
    if method.lower() == 'freedman':
        s = sort(x)
        IQR = s[int(N * .75)] - s[int(
            N * .25)]  # Interquantile range (75% -25%)
        width = 2 * IQR * N ** (-1. / 3)

    elif method.lower() == 'scott':
        width = 3.49 * x.std() * N ** (-1. / 3)
    else:
        raise ValueError('Method must be Scott or Freedman', method)
    return int(diff(range) / width)
25987
private static void mult(int[] src, int srcLen, int v0, int v1, int[] dst) {
        long v = v0 & LONG_MASK;
        long carry = 0;
        for (int j = 0; j < srcLen; j++) {
            long product = v * (src[j] & LONG_MASK) + carry;
            dst[j] = (int) product;
            carry = product >>> 32;
        }
        dst[srcLen] = (int) carry;
        v = v1 & LONG_MASK;
        carry = 0;
        for (int j = 0; j < srcLen; j++) {
            long product = (dst[j + 1] & LONG_MASK) + v * (src[j] & LONG_MASK) + carry;
            dst[j + 1] = (int) product;
            carry = product >>> 32;
        }
        dst[srcLen + 1] = (int) carry;
    }
793047
private long allocateSubpage(int normCapacity) {
        // Obtain the head of the PoolSubPage pool that is owned by the PoolArena and synchronize on it.
        // This is need as we may add it back and so alter the linked-list structure.
        PoolSubpage<T> head = arena.findSubpagePoolHead(normCapacity);
        int d = maxOrder; // subpages are only be allocated from pages i.e., leaves
        synchronized (head) {
            int id = allocateNode(d);
            if (id < 0) {
                return id;
            }

            final PoolSubpage<T>[] subpages = this.subpages;
            final int pageSize = this.pageSize;

            freeBytes -= pageSize;

            int subpageIdx = subpageIdx(id);
            PoolSubpage<T> subpage = subpages[subpageIdx];
            if (subpage == null) {
                subpage = new PoolSubpage<T>(head, this, id, runOffset(id), pageSize, normCapacity);
                subpages[subpageIdx] = subpage;
            } else {
                subpage.init(head, normCapacity);
            }
            return subpage.allocate();
        }
    }
695420
public static AssociativeArray optimumSampleSize(int n, AssociativeArray populationNh, AssociativeArray populationStdh) {
        AssociativeArray nh = new AssociativeArray();
        
        double sumNhSh = 0.0;
        for(Map.Entry<Object, Object> entry : populationNh.entrySet()) {
            Object strata = entry.getKey();
            Integer populationInStrata = ((Number)entry.getValue()).intValue();
            Double populationStd = populationStdh.getDouble(strata);
            
            if(populationStd == null || populationInStrata <=0.0) {
                throw new IllegalArgumentException("Invalid strata population or strata std.");
            }
            
            double NhSh = populationInStrata*populationStd;
            
            sumNhSh+=NhSh;

            nh.put(strata, n*NhSh);
        }
        
        if(sumNhSh<=0) {
            throw new IllegalArgumentException("Invalid strata populations.");
        }
        
        for(Map.Entry<Object, Object> entry : nh.entrySet()) {
            Object strata = entry.getKey();
            nh.put(strata, TypeInference.toDouble(entry.getValue())/sumNhSh);
        }
        
        return nh;
    }
242325
function (Y) {
			var N = this.N;
			var dim = this.dim; // dim of output space
			var P = this.P;

			var pmul = this.iter < 100 ? 4 : 1; // trick that helps with local optima

			// compute current Q distribution, unnormalized first
			var Qu = zeros(N * N);
			var qsum = 0.0;
			for (var i = 0; i < N; i++) {
				for (var j = i + 1; j < N; j++) {
					var dsum = 0.0;
					for (var d = 0; d < dim; d++) {
						var dhere = Y[i][d] - Y[j][d];
						dsum += dhere * dhere;
					}
					var qu = 1.0 / (1.0 + dsum); // Student t-distribution
					Qu[i * N + j] = qu;
					Qu[j * N + i] = qu;
					qsum += 2 * qu;
				}
			}
			// normalize Q distribution to sum to 1
			var NN = N * N;
			var Q = zeros(NN);
			for (var q = 0; q < NN; q++) {
				Q[q] = Math.max(Qu[q] / qsum, 1e-100);
			}

			var cost = 0.0;
			var grad = [];
			for (var i = 0; i < N; i++) {
				var gsum = new Array(dim); // init grad for point i
				for (var d = 0; d < dim; d++) {
					gsum[d] = 0.0;
				}
				for (var j = 0; j < N; j++) {
					cost += -P[i * N + j] * Math.log(Q[i * N + j]); // accumulate cost (the non-constant portion at least...)
					var premult = 4 * (pmul * P[i * N + j] - Q[i * N + j]) * Qu[i * N + j];
					for (var d = 0; d < dim; d++) {
						gsum[d] += premult * (Y[i][d] - Y[j][d]);
					}
				}
				grad.push(gsum);
			}

			return {
				cost: cost,
				grad: grad
			};
		}