Express load factor as 0.25 to trim a collection with more than 25% excess capacity
504316
public boolean trimToSizeIfGreaterThanPercent(double loadFactor)
    {
        double excessCapacity = 1.0 - (double) this.size / (double) this.items.length;
        if (excessCapacity > loadFactor)
        {
            this.trimToSize();
            return true;
        }
        return false;
    }
1292610
def supplement_filesystem(old_size, user_cap=False):
    """"""
    new_size = old_size
    if user_cap:
        if old_size <= _GiB_to_Byte(1.5):
            new_size = _GiB_to_Byte(3)
        else:
            new_size += _GiB_to_Byte(1.5)
    return int(new_size)
1273053
protected int chooseGrowCapacity(int size, double minLoad, double maxLoad) {
    return nextPrime(Math.max(size+1, (int) ((4*size / (3*minLoad+maxLoad)))));
  }
806801
def _preload_range(self):
        """"""
        queue = self._read_queue
        size = self._buffer_size
        start = self._seek
        end = int(start + size * self._max_buffers)
        workers_submit = self._workers.submit
        indexes = tuple(range(start, end, size))

        # Drops buffer out of current range
        for seek in tuple(queue):
            if seek not in indexes:
                del queue[seek]

        # Launch buffer preloading for current range
        read_range = self._read_range
        for seek in indexes:
            if seek not in queue:
                queue[seek] = workers_submit(read_range, seek, seek + size)
1063124
def mr(items, targets, **kwargs):
    
    bins = [(target, []) for target in targets]
    skip = []

    for item in items:
        capacities = [target - sum(content) for target, content in bins]
        weighted = weight(capacities, **kwargs)

        (target, content), capacity, _ = max(zip(bins, capacities, weighted),
                                             key=operator.itemgetter(2))
        if item <= capacity:
            content.append(item)
        else:
            skip.append(item)
    return bins, skip
1006561
function purgeExcess(dir, shrinkwrap, opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }

    findExcess(dir, shrinkwrap, opts, null, function (err, excessFiles) {
        if (err) {
            // if no node_modules then nothing to purge
            if (err.code === 'ENOENT') {
                return cb(null);
            }
            return cb(err);
        }

        var tasks = excessFiles.map(function (file) {
            var filePath = path.join(dir, file);
            console.log('removing', filePath);
            return rimraf.bind(null, filePath);
        });

        parallel(tasks, cb);
    });
}
244045
def visit_unload_from_select(element, compiler, **kw):
    """"""

    template = """
       UNLOAD (:select) TO :unload_location
       CREDENTIALS :credentials
       {manifest}
       {header}
       {delimiter}
       {encrypted}
       {fixed_width}
       {gzip}
       {add_quotes}
       {null}
       {escape}
       {allow_overwrite}
       {parallel}
       {region}
       {max_file_size}
    """
    el = element

    qs = template.format(
        manifest='MANIFEST' if el.manifest else '',
        header='HEADER' if el.header else '',
        delimiter=(
            'DELIMITER AS :delimiter' if el.delimiter is not None else ''
        ),
        encrypted='ENCRYPTED' if el.encrypted else '',
        fixed_width='FIXEDWIDTH AS :fixed_width' if el.fixed_width else '',
        gzip='GZIP' if el.gzip else '',
        add_quotes='ADDQUOTES' if el.add_quotes else '',
        escape='ESCAPE' if el.escape else '',
        null='NULL AS :null_as' if el.null is not None else '',
        allow_overwrite='ALLOWOVERWRITE' if el.allow_overwrite else '',
        parallel='PARALLEL OFF' if not el.parallel else '',
        region='REGION :region' if el.region is not None else '',
        max_file_size=(
            'MAXFILESIZE :max_file_size MB'
            if el.max_file_size is not None else ''
        ),
    )

    query = sa.text(qs)

    if el.delimiter is not None:
        query = query.bindparams(sa.bindparam(
            'delimiter', value=element.delimiter, type_=sa.String,
        ))

    if el.fixed_width:
        query = query.bindparams(sa.bindparam(
            'fixed_width',
            value=_process_fixed_width(el.fixed_width),
            type_=sa.String,
        ))

    if el.null is not None:
        query = query.bindparams(sa.bindparam(
            'null_as', value=el.null, type_=sa.String
        ))

    if el.region is not None:
        query = query.bindparams(sa.bindparam(
            'region', value=el.region, type_=sa.String
        ))

    if el.max_file_size is not None:
        max_file_size_mib = float(el.max_file_size) / 1024 / 1024
        query = query.bindparams(sa.bindparam(
            'max_file_size', value=max_file_size_mib, type_=sa.Float
        ))

    return compiler.process(
        query.bindparams(
            sa.bindparam('credentials', value=el.credentials, type_=sa.String),
            sa.bindparam(
                'unload_location', value=el.unload_location, type_=sa.String,
            ),
            sa.bindparam(
                'select',
                value=compiler.process(
                    el.select,
                    literal_binds=True,
                ),
                type_=sa.String,
            ),
        ),
        **kw
    )
1368536
def shrink(self, amount):
        """"""
        # Grow/shrink the pool if necessary.
        # Remove any dead threads from our list
        for t in self._threads:
            if not t.isAlive():
                self._threads.remove(t)
                amount -= 1

        # calculate the number of threads above the minimum
        n_extra = max(len(self._threads) - self.min, 0)

        # don't remove more than amount
        n_to_remove = min(amount, n_extra)

        # put shutdown requests on the queue equal to the number of threads
        # to remove. As each request is processed by a worker, that worker
        # will terminate and be culled from the list.
        for n in range(n_to_remove):
            self._queue.put(_SHUTDOWNREQUEST)
1335872
def _query_uncompressed(options, collection_name, num_to_skip,
          num_to_return, query, field_selector, opts, check_keys=False):
    """"""
    op_query, max_bson_size = _query(
        options,
        collection_name,
        num_to_skip,
        num_to_return,
        query,
        field_selector,
        opts,
        check_keys)
    rid, msg = __pack_message(2004, op_query)
    return rid, msg, max_bson_size
489408
public void trimToSize()
    {
        if (elements.length != size && elements.length > INITIAL_CAPACITY)
        {
            elements = Arrays.copyOf(elements, Math.max(INITIAL_CAPACITY, size));
        }
    }
831442
function(start_index, count) {

		if (count <= 0) Lava.t("Invalid item count supplied for removeRange");
		if (start_index + count >= this._count + 1) Lava.t("Index is out of range");

		var removed_uids = this._data_uids.splice(start_index, count),
			removed_values = this._data_values.splice(start_index, count),
			removed_names = this._data_names.splice(start_index, count);

		this._setLength(this._count - count);

		this._fire('items_removed', {
			uids: removed_uids,
			values: removed_values,
			names: removed_names
		});

		this._fire('collection_changed');

		return removed_values;

	}
658677
def trim(self, start, stop):
        """"""
        return self.client.ltrim(self.name, start, stop - 1)
389184
def limit_mem(limit=(4 * 1024**3)):
    ""
    rsrc = resource.RLIMIT_DATA
    soft, hard = resource.getrlimit(rsrc)
    resource.setrlimit(rsrc, (limit, hard))  # 4GB
    softnew, _ = resource.getrlimit(rsrc)
    assert softnew == limit

    _log = logging.getLogger(__name__)
    _log.debug(': %s => %s', soft, softnew)
724481
def slim_frame_data(frames, frame_allowance=25):
    
    frames_len = 0
    app_frames = []
    system_frames = []
    for frame in frames:
        frames_len += 1
        if frame.get('in_app'):
            app_frames.append(frame)
        else:
            system_frames.append(frame)

    if frames_len <= frame_allowance:
        return frames

    remaining = frames_len - frame_allowance
    app_count = len(app_frames)
    system_allowance = max(frame_allowance - app_count, 0)
    if system_allowance:
        half_max = int(system_allowance / 2)
        # prioritize trimming system frames
        for frame in system_frames[half_max:-half_max]:
            frame.pop('vars', None)
            frame.pop('pre_context', None)
            frame.pop('post_context', None)
            remaining -= 1

    else:
        for frame in system_frames:
            frame.pop('vars', None)
            frame.pop('pre_context', None)
            frame.pop('post_context', None)
            remaining -= 1

    if remaining:
        app_allowance = app_count - remaining
        half_max = int(app_allowance / 2)

        for frame in app_frames[half_max:-half_max]:
            frame.pop('vars', None)
            frame.pop('pre_context', None)
            frame.pop('post_context', None)

    return frames
1355840
def remove_total_size(apps, schema_editor):
    """"""
    Data = apps.get_model('flow', 'Data')
    for data in Data.objects.all():
        for field_schema, fields in iterate_fields(data.output, data.process.output_schema):
            name = field_schema['name']
            value = fields[name]
            if 'type' in field_schema:
                if field_schema['type'].startswith('basic:file:'):
                    del value['total_size']
                elif field_schema['type'].startswith('list:basic:file:'):
                    for obj in value:
                        del obj['total_size']
                elif field_schema['type'].startswith('basic:dir:'):
                    del value['total_size']
                elif field_schema['type'].startswith('list:basic:dir:'):
                    for obj in value:
                        del obj['total_size']
        data.save()
1053002
def truncate(data, l=20):
    ""
    info = (data[:l] + '..') if len(data) > l else data
    return info
372887
function sizeFilter (item /*{File|FileLikeObject}*/, options) {
      var size = item.size,
          // Use passed size limit or default to 10MB
          sizeLimit = vm.sizeLimit || 10 * 1000 * 1000;
      if (size > sizeLimit) {
        var err = new Error('File too big (' + size + ')');
        vm.onUploadFinished(err);
        throw err;
      }
      return size < sizeLimit;
    }