Key idea is that we try to move towards upperbound, by randomly choose one
    value for each parameter. However, for the last parameter,
    we need to make sure that its value can help us get above lowerbound
422034
def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100):
    '''
    
    '''
    outputs = None

    if check_feasibility(x_bounds, lowerbound, upperbound) is True:
        # Order parameters by their range size. We want the smallest range first,
        # because the corresponding parameter has less numbers to choose from
        x_idx_sorted = []
        for i, _ in enumerate(x_bounds):
            if x_types[i] == "discrete_int":
                x_idx_sorted.append([i, len(x_bounds[i])])
            elif (x_types[i] == "range_int") or (x_types[i] == "range_continuous"):
                x_idx_sorted.append([i, math.floor(x_bounds[i][1] - x_bounds[i][0])])
        x_idx_sorted = sorted(x_idx_sorted, key=itemgetter(1))

        for _ in range(max_retries):
            budget_allocated = 0
            outputs = [None] * len(x_bounds)

            for i, _ in enumerate(x_idx_sorted):
                x_idx = x_idx_sorted[i][0]
                # The amount of unallocated space that we have
                budget_max = upperbound - budget_allocated
                # NOT the Last x that we need to assign a random number
                if i < (len(x_idx_sorted) - 1):
                    if x_bounds[x_idx][0] <= budget_max:
                        if x_types[x_idx] == "discrete_int":
                            # Note the valid integer
                            temp = []
                            for j in x_bounds[x_idx]:
                                if j <= budget_max:
                                    temp.append(j)
                            # Randomly pick a number from the integer array
                            if temp:
                                outputs[x_idx] = temp[random.randint(0, len(temp) - 1)]

                        elif (x_types[x_idx] == "range_int") or \
                                    (x_types[x_idx] == "range_continuous"):
                            outputs[x_idx] = random.randint(x_bounds[x_idx][0],
                                                            min(x_bounds[x_idx][-1], budget_max))

                else:
                    # The last x that we need to assign a random number
                    randint_lowerbound = lowerbound - budget_allocated
                    randint_lowerbound = 0 if randint_lowerbound < 0 else randint_lowerbound

                    # This check:
                    # is our smallest possible value going to overflow the available budget space,
                    # and is our largest possible value going to underflow the lower bound
                    if (x_bounds[x_idx][0] <= budget_max) and \
                            (x_bounds[x_idx][-1] >= randint_lowerbound):
                        if x_types[x_idx] == "discrete_int":
                            temp = []
                            for j in x_bounds[x_idx]:
                                # if (j <= budget_max) and (j >= randint_lowerbound):
                                if randint_lowerbound <= j <= budget_max:
                                    temp.append(j)
                            if temp:
                                outputs[x_idx] = temp[random.randint(0, len(temp) - 1)]
                        elif (x_types[x_idx] == "range_int") or \
                                (x_types[x_idx] == "range_continuous"):
                            outputs[x_idx] = random.randint(randint_lowerbound,
                                                            min(x_bounds[x_idx][1], budget_max))
                if outputs[x_idx] is None:
                    break
                else:
                    budget_allocated += outputs[x_idx]
            if None not in outputs:
                break
    return outputs
889805
private void findStartingPoint() {
    // Well, we already know the best Y value...
    final double bestY = minmaxY.getMin();
    double bestX = Double.POSITIVE_INFINITY;
    int bestI = -1;
    Iterator<double[]> iter = this.points.iterator();
    for(int i = 0; iter.hasNext(); i++) {
      double[] vec = iter.next();
      if(vec[1] == bestY && vec[0] < bestX) {
        bestX = vec[0];
        bestI = i;
      }
    }
    assert (bestI >= 0);
    // Bring the reference object to the head.
    if(bestI > 0) {
      points.add(0, points.remove(bestI));
    }
  }
358608
private void moveSlotBefore() {
		/*
		 * int slot = 0; while (slot < currentPage.getNumRecords() &&
		 * searchRange.largerThan(getKey(currentPage, slot))) slot++;
		 * 
		 * currentSlot = slot - 1;
		 */
		// Optimization: Use binary search rather than sequential search
		int startSlot = 0, endSlot = currentPage.getNumRecords() - 1;
		int middleSlot = (startSlot + endSlot) / 2;
		SearchKey searchMin = searchRange.getMin();

		if (endSlot >= 0) {
			while (middleSlot != startSlot) {
				if (searchMin.compareTo(
						getKey(currentPage, middleSlot, keyType.length())) > 0)
					startSlot = middleSlot;
				else
					endSlot = middleSlot;

				middleSlot = (startSlot + endSlot) / 2;
			}
			
			if (searchMin.compareTo(
					getKey(currentPage, endSlot, keyType.length())) > 0)
				currentSlot = endSlot;
			else if (searchMin.compareTo(
					getKey(currentPage, startSlot, keyType.length())) > 0)
				currentSlot = startSlot;
			else
				currentSlot = startSlot - 1;
		} else
			currentSlot = -1;
	}
791419
static int getRandomValueFromInterval(
            double randomizationFactor, double random, int currentIntervalMillis) {
        double delta = randomizationFactor * currentIntervalMillis;
        double minInterval = currentIntervalMillis - delta;
        double maxInterval = currentIntervalMillis + delta;
        // Get a random value from the range [minInterval, maxInterval].
        // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then
        // we want a 33% chance for selecting either 1, 2 or 3.
        int randomValue = (int) (minInterval + (random * (maxInterval - minInterval + 1)));
        return randomValue;
    }
1312171
function() {
      this.bounds.reset();
      if (this.slices.length) {
        this.bounds.addValue(this.slices[0].start);
        this.bounds.addValue(this.slices[this.slices.length - 1].end);
      }
      for (var id in this.counters) {
        this.counters[id].updateBounds();
        this.bounds.addRange(this.counters[id].bounds);
      }
      if (this.samples_ && this.samples_.length) {
        this.bounds.addValue(this.samples_[0].start);
        this.bounds.addValue(
            this.samples_[this.samples_.length - 1].end);
      }
    }
397930
private void ensureAvail(int n) {
    if (pos + n >= buf.length) {
      int newSize = Math.max(pos + n, buf.length * 2);
      buf = Arrays.copyOf(buf, newSize);
    }
  }
686751
function growBounding(bounding, x, y) {
        if (x < bounding[0]) {
            bounding[0] = x;
        } else if (x > bounding[2]) {
            bounding[2] = x;
        }

        if (y < bounding[1]) {
            bounding[1] = y;
        } else if (y > bounding[3]) {
            bounding[3] = y;
        }
    }
980910
function closestButNotGreaterThan(numbers, maxNumber) {
    var positiveNumbers = numbers.map(function(number){
        return Math.abs(number);
    });
    var positiveMaxNumber = Math.abs(maxNumber);

    var winner = positiveMaxNumber;
    var winningDifference = positiveMaxNumber;

    for (var i=0; i < positiveNumbers.length; i++) {
        var lessThanMax = positiveNumbers[i] <= positiveMaxNumber;
        var closerToMax = (positiveMaxNumber - positiveNumbers[i]) < winningDifference;
        if (lessThanMax && closerToMax) {
            winner = positiveNumbers[i];
            winningDifference = positiveMaxNumber-positiveNumbers[i];
        }
    }
    return winner;
}
238091
def randbetween(lower: int, upper: int) -> int:
    
    if not isinstance(lower, int) or not isinstance(upper, int):
        raise TypeError('lower and upper must be integers')
    if lower < 0 or upper <= 0:
        raise ValueError('lower and upper must be greater than zero')

    return randbelow(upper - lower + 1) + lower
879390
public void offer(float value)
  {
    // update min/max
    if (value < min) {
      min = value;
    }
    if (value > max) {
      max = value;
    }

    // initial value
    if (binCount == 0) {
      positions[0] = value;
      bins[0] = 1;
      count++;

      binCount++;
      return;
    }

    final int index = Arrays.binarySearch(positions, 0, binCount, value);

    if (index >= 0) {
      // we have an exact match, simply increase the count, but keep the approximate flag
      bins[index] = (bins[index] & APPROX_FLAG_BIT) | ((bins[index] & COUNT_BITS) + 1);
      count++;
      return;
    }

    // otherwise merge the value into a new or existing bin at the following position
    final int insertAt = -(index + 1);

    if (binCount < size) {
      // we have a spare slot, put the value into a new bin
      shiftRight(insertAt, binCount);

      positions[insertAt] = value;
      bins[insertAt] = 1;
      count++;

      binCount++;
      return;
    }

    // no more slots available merge the new value into and existing bin
    // or merge existing bins before inserting the new one

    int minPos = minDeltaIndex();
    float minDelta = minPos >= 0 ? positions[minPos + 1] - positions[minPos] : Float.POSITIVE_INFINITY;

    // determine the distance of new value to the nearest bins
    final float deltaRight = insertAt < binCount ? positions[insertAt] - value : Float.POSITIVE_INFINITY;
    final float deltaLeft = insertAt > 0 ? value - positions[insertAt - 1] : Float.POSITIVE_INFINITY;

    boolean mergeValue = false;
    if (deltaRight < minDelta) {
      minDelta = deltaRight;
      minPos = insertAt;
      mergeValue = true;
    }
    if (deltaLeft < minDelta) {
      minPos = insertAt - 1;
      mergeValue = true;
    }

    if (mergeValue) {
      // merge new value into an existing bin and set approximate flag
      final long k = bins[minPos] & COUNT_BITS;
      positions[minPos] = (positions[minPos] * k + value) / (k + 1);
      bins[minPos] = (k + 1) | APPROX_FLAG_BIT;
      count++;
    } else {
      // merge the closest bins together and insert new value as a separate bin
      mergeInsert(minPos, insertAt, value, 1);
    }
  }
367688
private void applyVerticalLimit()
    {
        if (mover.getY() < limitBottom && limitBottom != Integer.MIN_VALUE)
        {
            mover.teleportY(limitBottom);
        }
        else if (mover.getY() > limitTop && limitTop != Integer.MAX_VALUE)
        {
            mover.teleportY(limitTop);
        }
    }
420323
private int lowerBound(JoinFilterFunction searchFunction, int[] links, int first, int last, int probePosition, Page allProbeChannelsPage)
    {
        int middle;
        int step;
        int count = last - first;
        while (count > 0) {
            step = count / 2;
            middle = first + step;
            if (!applySearchFunction(searchFunction, links, middle, probePosition, allProbeChannelsPage)) {
                first = ++middle;
                count -= step + 1;
            }
            else {
                count = step;
            }
        }
        return first;
    }
485807
function spop() {
  var ind = Math.floor(Math.random() * this._keys.length)
    , val = this._keys[ind];
  this.delKey(val);
  return val;
}
915767
def uniform(low, high, random_state):
    '''
    
    '''
    assert high > low, 'Upper bound must be larger than lower bound'
    return random_state.uniform(low, high)
317959
function(v) {
				var pt = this._firstNumPT,
					val;
				this._super.setRatio.call(this, v);
				while (pt) {
					val = _parseColor(this._proxy[pt.p], false);
					val = val[0] << 16 | val[1] << 8 | val[2];
					if (pt.f) {
						this._target[pt.p](val);
					} else {
						this._target[pt.p] = val;
					}
					pt = pt._next;
				}
			}
1125222
function upperBound(value, arr) {
    let i = 0;
    let j = arr.length - 1;
    while (i < j) {
        const m = (i + j) >> 1;
        if (arr[m] > value) {
            j = m;
        } else {
            i = m + 1;
        }
    }
    return arr[i];
}
1081759
@GuardedBy("evictionLock")
  void determineAdjustment() {
    if (frequencySketch().isNotInitialized()) {
      setPreviousSampleHitRate(0.0);
      setMissesInSample(0);
      setHitsInSample(0);
      return;
    }

    int requestCount = hitsInSample() + missesInSample();
    if (requestCount < frequencySketch().sampleSize) {
      return;
    }

    double hitRate = (double) hitsInSample() / requestCount;
    double hitRateChange = hitRate - previousSampleHitRate();
    double amount = (hitRateChange >= 0) ? stepSize() : -stepSize();
    double nextStepSize = (Math.abs(hitRateChange) >= HILL_CLIMBER_RESTART_THRESHOLD)
        ? HILL_CLIMBER_STEP_PERCENT * maximum() * (amount >= 0 ? 1 : -1)
        : HILL_CLIMBER_STEP_DECAY_RATE * amount;
    setPreviousSampleHitRate(hitRate);
    setAdjustment((long) amount);
    setStepSize(nextStepSize);
    setMissesInSample(0);
    setHitsInSample(0);
  }