FIND HOLES IN A DENSE COLUMN OF INTEGERS
    RETURNS A LIST OF {"min"min, "max":max} OBJECTS
336423
def find_holes(db_module, db, table_name, column_name, _range, filter=None):
    
    if not filter:
        filter = {"match_all": {}}

    _range = wrap(_range)
    params = {
        "min": _range.min,
        "max": _range.max - 1,
        "column_name": db_module.quote_column(column_name),
        "table_name": db_module.quote_column(table_name),
        "filter": esfilter2sqlwhere(filter)
    }

    min_max = db.query("""
        SELECT
            min({{column_name}}) `min`,
            max({{column_name}})+1 `max`
        FROM
            {{table_name}} a
        WHERE
            a.{{column_name}} BETWEEN {{min}} AND {{max}} AND
            {{filter}}
    """, params)[0]

    db.execute("SET @last={{min}}-1", {"min": _range.min})
    ranges = db.query("""
        SELECT
            prev_rev+1 `min`,
            curr_rev `max`
        FROM (
            SELECT
                a.{{column_name}}-@last diff,
                @last prev_rev,
                @last:=a.{{column_name}} curr_rev
            FROM
                {{table_name}} a
            WHERE
                a.{{column_name}} BETWEEN {{min}} AND {{max}} AND
                {{filter}}
            ORDER BY
                a.{{column_name}}
        ) a
        WHERE
            diff>1
    """, params)

    if ranges:
        ranges.append({"min": min_max.max, "max": _range.max})
    else:
        if min_max.min:
            ranges.append({"min": _range.min, "max": min_max.min})
            ranges.append({"min": min_max.max, "max": _range.max})
        else:
            ranges.append(_range)

    return ranges
919261
def _retrieve_indices(cols):
        '''
        
        '''
        if isinstance(cols, int):
            return [cols]
        elif isinstance(cols, slice):
            start = cols.start if cols.start else 0
            stop = cols.stop
            step = cols.step if cols.step else 1
            return list(range(start, stop, step))
        elif isinstance(cols, list) and cols:
            if isinstance(cols[0], bool):
                return np.flatnonzero(np.asarray(cols))
            elif isinstance(cols[0], int):
                return cols
        else:
            raise TypeError('No valid column specifier. Only a scalar, list or slice of all'
                            'integers or a boolean mask are allowed.')
1164072
private void findFullGridIntBounds() {
		int[] iIntBounds = getIntBounds(ibounds);

		bounds = new int[6];
		if (jbounds==null) {
			bounds = iIntBounds;
		} else {
			int[] jIntBounds = getIntBounds(jbounds);
			bounds[0] = Math.min(iIntBounds[0],jIntBounds[0]);
			bounds[1] = Math.min(iIntBounds[1],jIntBounds[1]);
			bounds[2] = Math.min(iIntBounds[2],jIntBounds[2]);
			bounds[3] = Math.max(iIntBounds[3],jIntBounds[3]);
			bounds[4] = Math.max(iIntBounds[4],jIntBounds[4]);
			bounds[5] = Math.max(iIntBounds[5],jIntBounds[5]);
		}
	}
439305
def find_range(values, soft_range=[]):
    
    try:
        values = np.array(values)
        values = np.squeeze(values) if len(values.shape) > 1 else values
        if len(soft_range):
            values = np.concatenate([values, soft_range])
        if values.dtype.kind == 'M':
            return values.min(), values.max()
        return np.nanmin(values), np.nanmax(values)
    except:
        try:
            values = sorted(values)
            return (values[0], values[-1])
        except:
            return (None, None)
194732
def __range(a, bins):
    ''''''
    a = numpy.asarray(a)
    a_max = a.max()
    a_min = a.min()
    s = 0.5 * (a_max - a_min) / float(bins - 1)
    return (a_min - s, a_max + s)
1149823
public static int[] range(int min, int max) {
    int[] range = new int[max - min];
    for (int i = 0; i < (max - min); i++) {
      range[i] = i + min;
    }
    return range;
  }
90209
def _findrange(parlist,roots=['JUMP','DMXR1_','DMXR2_','DMX_','efac','log10_efac']):
    """"""

    rootdict = {root: [] for root in roots}

    res = []
    for par in parlist:
        found = False
        for root in roots:
            if len(par) > len(root) and par[:len(root)] == root:
                rootdict[root].append(int(par[len(root):]))
                found = True
        if not found:
            res.append(par)

    for root in roots:
        if rootdict[root]:
            if len(rootdict[root]) > 1:
                rmin, rmax = min(rootdict[root]), max(rootdict[root])
                res.append('{0}{{{1}-{2}}}{3}'.format(root,rmin,rmax,
                                                  '(incomplete)' if rmax - rmin != len(rootdict[root]) - 1 else ''))
            else:
                res.append('{0}{1}'.format(root,rootdict[root][0]))
    return res
264326
public static List random(Number min, Number max, long len) {
		return random(min, max, len, len);
	}
350710
function select(ids, coords, k, left, right, axis) {

    while (right > left) {
        if (right - left > 600) {
            const n = right - left + 1;
            const m = k - left + 1;
            const z = Math.log(n);
            const s = 0.5 * Math.exp(2 * z / 3);
            const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
            const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
            const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
            select(ids, coords, k, newLeft, newRight, axis);
        }

        const t = coords[2 * k + axis];
        let i = left;
        let j = right;

        swapItem(ids, coords, left, k);
        if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);

        while (i < j) {
            swapItem(ids, coords, i, j);
            i++;
            j--;
            while (coords[2 * i + axis] < t) i++;
            while (coords[2 * j + axis] > t) j--;
        }

        if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
        else {
            j++;
            swapItem(ids, coords, j, right);
        }

        if (j <= k) left = j + 1;
        if (k <= j) right = j - 1;
    }
}
61644
def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1):
  """"""
  assert length_bucket_step > 1.0
  x = min_length
  boundaries = []
  while x < max_length:
    boundaries.append(x)
    x = max(x + 1, int(x * length_bucket_step))
  return boundaries
762666
def intervals(_min, _max=None, size=1):
    
    if _max == None:
        _max = _min
        _min = 0
    _max = int(mo_math.ceiling(_max))
    _min = int(mo_math.floor(_min))

    output = ((x, min(x + size, _max)) for x in _range(_min, _max, size))
    return output
626521
def denormalize_bbox(bbox, rows, cols):
    
    if rows == 0:
        raise ValueError('Argument rows cannot be zero')
    if cols == 0:
        raise ValueError('Argument cols cannot be zero')

    x_min, y_min, x_max, y_max = bbox[:4]
    denormalized_bbox = [x_min * cols, y_min * rows, x_max * cols, y_max * rows]
    return denormalized_bbox + list(bbox[4:])
91281
def getCol(self, x):
        """"""
        return [self.getCell(x, i) for i in self.__size_range]
644878
def _get_bounds(mapper, values):
        

        array = np.array([mapper.get(x) for x in values])
        return array[:, 0], array[:, 1]
1140248
private void decodeDictionaryIds(
      int rowId,
      int num,
      WritableColumnVector column,
      WritableColumnVector dictionaryIds) {
    switch (descriptor.getPrimitiveType().getPrimitiveTypeName()) {
      case INT32:
        if (column.dataType() == DataTypes.IntegerType ||
            DecimalType.is32BitDecimalType(column.dataType())) {
          for (int i = rowId; i < rowId + num; ++i) {
            if (!column.isNullAt(i)) {
              column.putInt(i, dictionary.decodeToInt(dictionaryIds.getDictId(i)));
            }
          }
        } else if (column.dataType() == DataTypes.ByteType) {
          for (int i = rowId; i < rowId + num; ++i) {
            if (!column.isNullAt(i)) {
              column.putByte(i, (byte) dictionary.decodeToInt(dictionaryIds.getDictId(i)));
            }
          }
        } else if (column.dataType() == DataTypes.ShortType) {
          for (int i = rowId; i < rowId + num; ++i) {
            if (!column.isNullAt(i)) {
              column.putShort(i, (short) dictionary.decodeToInt(dictionaryIds.getDictId(i)));
            }
          }
        } else {
          throw constructConvertNotSupportedException(descriptor, column);
        }
        break;

      case INT64:
        if (column.dataType() == DataTypes.LongType ||
            DecimalType.is64BitDecimalType(column.dataType()) ||
            originalType == OriginalType.TIMESTAMP_MICROS) {
          for (int i = rowId; i < rowId + num; ++i) {
            if (!column.isNullAt(i)) {
              column.putLong(i, dictionary.decodeToLong(dictionaryIds.getDictId(i)));
            }
          }
        } else if (originalType == OriginalType.TIMESTAMP_MILLIS) {
          for (int i = rowId; i < rowId + num; ++i) {
            if (!column.isNullAt(i)) {
              column.putLong(i,
                DateTimeUtils.fromMillis(dictionary.decodeToLong(dictionaryIds.getDictId(i))));
            }
          }
        } else {
          throw constructConvertNotSupportedException(descriptor, column);
        }
        break;

      case FLOAT:
        for (int i = rowId; i < rowId + num; ++i) {
          if (!column.isNullAt(i)) {
            column.putFloat(i, dictionary.decodeToFloat(dictionaryIds.getDictId(i)));
          }
        }
        break;

      case DOUBLE:
        for (int i = rowId; i < rowId + num; ++i) {
          if (!column.isNullAt(i)) {
            column.putDouble(i, dictionary.decodeToDouble(dictionaryIds.getDictId(i)));
          }
        }
        break;
      case INT96:
        if (column.dataType() == DataTypes.TimestampType) {
          if (!shouldConvertTimestamps()) {
            for (int i = rowId; i < rowId + num; ++i) {
              if (!column.isNullAt(i)) {
                Binary v = dictionary.decodeToBinary(dictionaryIds.getDictId(i));
                column.putLong(i, ParquetRowConverter.binaryToSQLTimestamp(v));
              }
            }
          } else {
            for (int i = rowId; i < rowId + num; ++i) {
              if (!column.isNullAt(i)) {
                Binary v = dictionary.decodeToBinary(dictionaryIds.getDictId(i));
                long rawTime = ParquetRowConverter.binaryToSQLTimestamp(v);
                long adjTime = DateTimeUtils.convertTz(rawTime, convertTz, UTC);
                column.putLong(i, adjTime);
              }
            }
          }
        } else {
          throw constructConvertNotSupportedException(descriptor, column);
        }
        break;
      case BINARY:
        // TODO: this is incredibly inefficient as it blows up the dictionary right here. We
        // need to do this better. We should probably add the dictionary data to the ColumnVector
        // and reuse it across batches. This should mean adding a ByteArray would just update
        // the length and offset.
        for (int i = rowId; i < rowId + num; ++i) {
          if (!column.isNullAt(i)) {
            Binary v = dictionary.decodeToBinary(dictionaryIds.getDictId(i));
            column.putByteArray(i, v.getBytes());
          }
        }
        break;
      case FIXED_LEN_BYTE_ARRAY:
        // DecimalType written in the legacy mode
        if (DecimalType.is32BitDecimalType(column.dataType())) {
          for (int i = rowId; i < rowId + num; ++i) {
            if (!column.isNullAt(i)) {
              Binary v = dictionary.decodeToBinary(dictionaryIds.getDictId(i));
              column.putInt(i, (int) ParquetRowConverter.binaryToUnscaledLong(v));
            }
          }
        } else if (DecimalType.is64BitDecimalType(column.dataType())) {
          for (int i = rowId; i < rowId + num; ++i) {
            if (!column.isNullAt(i)) {
              Binary v = dictionary.decodeToBinary(dictionaryIds.getDictId(i));
              column.putLong(i, ParquetRowConverter.binaryToUnscaledLong(v));
            }
          }
        } else if (DecimalType.isByteArrayDecimalType(column.dataType())) {
          for (int i = rowId; i < rowId + num; ++i) {
            if (!column.isNullAt(i)) {
              Binary v = dictionary.decodeToBinary(dictionaryIds.getDictId(i));
              column.putByteArray(i, v.getBytes());
            }
          }
        } else {
          throw constructConvertNotSupportedException(descriptor, column);
        }
        break;

      default:
        throw new UnsupportedOperationException(
          "Unsupported type: " + descriptor.getPrimitiveType().getPrimitiveTypeName());
    }
  }
1173153
def min(self):
        
        if(self._clean.isDict()):
            return self._wrap(list())
        return self._wrap(min(self.obj))
239150
def getLimits(locations, current, sortResults=True, verbose=False):
    
    limit = {}
    for l in locations:
        a, b = current.common(l)
        if a is None:
            continue
        for name, value in b.items():
            f = a[name]
            if name not in limit:
                limit[name] = {}
                limit[name]['<'] = {}
                limit[name]['='] = {}
                limit[name]['>'] = {}
                if f > 0:
                    limit[name]['>'] = {0: [Location()]}
                elif f<0:
                    limit[name]['<'] = {0: [Location()]}
                else:
                    limit[name]['='] = {0: [Location()]}
            if current[name] < value - _EPSILON:
                if value not in limit[name]["<"]:
                    limit[name]["<"][value] = []
                limit[name]["<"][value].append(l)
            elif current[name] > value + _EPSILON:
                if value not in limit[name][">"]:
                    limit[name][">"][value] = []
                limit[name][">"][value].append(l)
            else:
                if value not in limit[name]["="]:
                    limit[name]["="][value] = []
                limit[name]["="][value].append(l)
    if not sortResults:
        return limit
    # now we have all the data, let's sort to the relevant values
    l = {}
    for name, lims in  limit.items():
        less = []
        more = []
        if lims[">"].keys():
            less = sorted(lims[">"].keys())
            lim_min = less[-1]
        else:
            lim_min = None
        if lims["<"].keys():
            more = sorted(lims["<"].keys())
            lim_max = more[0]
        else:
            lim_max = None
        if lim_min is None and lim_max is not None:
            # extrapolation < min
            if len(limit[name]['='])>0:
                l[name] = (None, list(limit[name]['='].keys())[0], None)
            elif len(more) > 1 and len(limit[name]['='])==0:
                # extrapolation
                l[name] = (None,  more[0], more[1])
        elif lim_min is not None and lim_max is None:
            # extrapolation < max
            if len(limit[name]['='])>0:
                # less > 0, M > 0, more = None
                # -> end of a limit
                l[name] = (None, limit[name]['='], None)
            elif len(less) > 1 and len(limit[name]['='])==0:
                # less > 0, M = None, more = None
                # extrapolation
                l[name] = (less[-2], less[-1], None)
        else:
            if len(limit[name]['=']) > 0:
                l[name] = (None, list(limit[name]['='].keys())[0], None)
            else:
                l[name] = (lim_min,  None, lim_max)
    return l