we cache the sizes of our adapters so get accesses are faster
967894
protected void cacheSizes() {
        mAdapterSizes.clear();
        int size = 0;

        for (IAdapter<Item> adapter : mAdapters) {
            if (adapter.getAdapterItemCount() > 0) {
                mAdapterSizes.append(size, adapter);
                size = size + adapter.getAdapterItemCount();
            }
        }

        //we also have to add this for the first adapter otherwise the floorIndex method will return the wrong value
        if (size == 0 && mAdapters.size() > 0) {
            mAdapterSizes.append(0, mAdapters.get(0));
        }

        mGlobalSize = size;
    }
379726
function initAdapters(container) {

        var calls = [];

        if (container === 'webserver') {
            _.each(adapters, function (adapter) {
                if (adapter.webInit) {
                    calls.push(adapter.webInit);
                }
            });
        }
        else {
            _.each(adapters, function (adapter) {
                if (adapter.init) {
                    calls.push(adapter.init);
                }
            });
        }

        return chainPromises(calls, config)
            .then(function (returnConfig) {
                if (returnConfig) {
                    return returnConfig;
                }
                else {
                    throw new Error('An adapter in the chain is not returning the config.');
                }
            });
    }
1239520
def _get_cache_size(replace=False):
    """"""

    if not replace:
        size = _cached_search_compile.cache_info().currsize
    else:
        size = _cached_replace_compile.cache_info().currsize
    return size
632768
static <T> int listSizeInBytes(Buffer.Writer<T> writer, List<T> values) {
    int sizeInBytes = 5;
    for (int i = 0, length = values.size(); i < length; i++) {
      sizeInBytes += writer.sizeInBytes(values.get(i));
    }
    return sizeInBytes;
  }
994412
def generate_adapter(adapter, name='url_for', map_name='url_map'):
    """"""
    values = {
        u'server_name':     dumps(adapter.server_name),
        u'script_name':     dumps(adapter.script_name),
        u'subdomain':       dumps(adapter.subdomain),
        u'url_scheme':      dumps(adapter.url_scheme),
        u'name':            name,
        u'map_name':        map_name
    }
    return u'''\
var %(name)s = %(map_name)s(
    %(server_name)s,
    %(script_name)s,
    %(subdomain)s,
    %(url_scheme)s
);''' % values
449121
function getIndexSizes(done, results) {
  var client = results.client;
  var ns = mongodbNS(results.namespace);
  client
    .db(ns.database)
    .collection(ns.collection)
    .stats(function(err, res) {
      if (err) {
        if (isNotAuthorizedError(err)) {
          debug(
            'Not authorized to get collection stats.  Returning default for indexSizes {}.'
          );
          return done(null, {});
        }
        return done(err);
      }

      res = _.mapValues(res.indexSizes, function(size) {
        return { size: size };
      });
      done(null, res);
    });
}
830168
function Prefetch(o) {
  this.url = o.url;
  this.ttl = o.ttl;
  this.cache = o.cache;
  this.prepare = o.prepare;
  this.transform = o.transform;
  this.transport = o.transport;
  this.thumbprint = o.thumbprint;

  this.storage = new PersistentStorage(o.cacheKey);
}
601381
@SuppressWarnings("unchecked")
    public static <Item extends IItem, A extends IAdapter> FastAdapter<Item> with(@Nullable Collection<A> adapters, @Nullable Collection<IAdapterExtension<Item>> extensions) {
        FastAdapter<Item> fastAdapter = new FastAdapter<>();
        if (adapters == null) {
            fastAdapter.mAdapters.add((IAdapter<Item>) items());
        } else {
            fastAdapter.mAdapters.addAll((Collection<IAdapter<Item>>) adapters);
        }
        for (int i = 0; i < fastAdapter.mAdapters.size(); i++) {
            fastAdapter.mAdapters.get(i).withFastAdapter(fastAdapter).setOrder(i);
        }
        fastAdapter.cacheSizes();

        if (extensions != null) {
            for (IAdapterExtension<Item> extension : extensions) {
                fastAdapter.addExtension(extension);
            }
        }

        return fastAdapter;
    }
977662
def iter_adapters():
    ''''''
    adapters = adapter_catalog.values()
    return sorted(adapters, key=lambda a: a.model.__name__)
1056813
private void ensureCapacity() {
    if (size < resourceIds.length) {
      return;
    }
    int newCapacity = (resourceIds.length * 3) / 2 + 1;
    // Increase size of resourceIds
    String[] oldResourceIds = resourceIds;
    resourceIds = new String[newCapacity];
    System.arraycopy(oldResourceIds, 0, resourceIds, 0, oldResourceIds.length);
    // Increase size of blockData
    int[] oldBlockData = blockData;
    blockData = new int[newCapacity * blockInts];
    System.arraycopy(oldBlockData, 0, blockData, 0, oldBlockData.length);
    // Increase size of byResourceIndices (no need to copy old, because would be restored in method ensureSorted)
    resourceIdsIndex = new int[newCapacity];
    sorted = false;
  }
1295934
function Cache(maxSize, debug, storage) {
    this.maxSize_ = maxSize || -1;
    this.debug_ = debug || false;
    this.storage_ = storage || new Cache.BasicCacheStorage();

    this.fillFactor_ = .75;

    this.stats_ = {};
    this.stats_['hits'] = 0;
    this.stats_['misses'] = 0;
    this.log_('Initialized cache with size ' + maxSize);
}
113705
def avail_sizes(conn=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_sizes function must be called with '
            '-f or --function, or with the --list-sizes option'
        )

    if not conn:
        conn = get_conn()   # pylint: disable=E0602

    sizes = conn.list_sizes()
    ret = {}
    for size in sizes:
        if isinstance(size.name, six.string_types) and not six.PY3:
            size_name = size.name.encode('ascii', 'salt-cloud-force-ascii')
        else:
            size_name = str(size.name)  # future lint: disable=blacklisted-function

        ret[size_name] = {}
        for attr in dir(size):
            if attr.startswith('_') or attr in ('driver', 'get_uuid'):
                continue

            try:
                attr_value = getattr(size, attr)
            except Exception:
                pass

            if isinstance(attr_value, six.string_types) and not six.PY3:
                attr_value = attr_value.encode(
                    'ascii', 'salt-cloud-force-ascii'
                )
            ret[size_name][attr] = attr_value
    return ret
427002
function getAccessor (accessor, bufferViews) {
  if (accessor._data) return accessor

  const numberOfComponents = GLTF_ACCESSOR_TYPE_COMPONENTS_NUMBER[accessor.type]
  if (accessor.byteOffset === undefined) accessor.byteOffset = 0

  accessor._bufferView = bufferViews[accessor.bufferView]

  const TypedArrayConstructor = WEBGL_TYPED_ARRAY_BY_COMPONENT_TYPES[accessor.componentType]
  const byteSize = GLTF_ACCESSOR_COMPONENT_TYPE_SIZE[accessor.componentType]

  const data = new TypedArrayConstructor(accessor._bufferView._data.slice(
    accessor.byteOffset,
    accessor.byteOffset + accessor.count * numberOfComponents * byteSize
  ))
  accessor._data = data

  // Sparse accessors
  // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/schema/accessor.sparse.schema.json
  if (accessor.sparse !== undefined) {
    const TypedArrayIndicesConstructor =
      WEBGL_TYPED_ARRAY_BY_COMPONENT_TYPES[accessor.sparse.indices.componentType]

    // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/schema/accessor.sparse.indices.schema.json
    const sparseIndices = new TypedArrayIndicesConstructor(
      bufferViews[accessor.sparse.indices.bufferView]._data,
      accessor.sparse.indices.byteOffset || 0,
      accessor.sparse.count
    )

    // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/schema/accessor.sparse.values.schema.json
    const sparseValues = new TypedArrayConstructor(
      bufferViews[accessor.sparse.values.bufferView]._data,
      accessor.sparse.values.byteOffset || 0,
      accessor.sparse.count * numberOfComponents
    )

    if (accessor._data !== null) {
      accessor._data = accessor._data.slice()
    }

    let valuesIndex = 0
    for (let indicesIndex = 0; indicesIndex < sparseIndices.length; indicesIndex++) {
      let dataIndex = sparseIndices[indicesIndex] * numberOfComponents
      for (let componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) {
        accessor._data[dataIndex++] = sparseValues[valuesIndex++]
      }
    }
  }

  return accessor
}
1068075
function loadAdapters() {
        var adapters = {};
        var adaptersDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/adapters');

        if (!fs.existsSync(adaptersDir)) {
            return this.injector.adapters || {};
        }

        var me = this;
        var adapterNames = fs.readdirSync(adaptersDir);

        _.each(adapterNames, function (adapterName) {
            if (adapterName.substring(adapterName.length - 3) !== '.js') {  // only dirs, not js files
                var adapterImpl = me.injector.adapterMap[adapterName];
                adapterName = utils.getPascalCase(adapterImpl + '.' + adapterName + '.adapter');
                adapters[adapterName] = me.injector.loadModule(adapterName);
            }
        });

        // add the adapters that come from plugins to the list
        _.extend(adapters, this.injector.adapters);

        // return the adapters
        return adapters;
    }
1279743
protected void allocateBuffers(int arraySize) {
    assert Integer.bitCount(arraySize) == 1;

    // Compute new hash mixer candidate before expanding.
    final int newKeyMixer = this.orderMixer.newKeyMixer(arraySize);

    // Ensure no change is done if we hit an OOM.
    KType[] prevKeys = Intrinsics.<KType[]> cast(this.keys);
    try {
      int emptyElementSlot = 1;
      this.keys = Intrinsics.<KType> newArray(arraySize + emptyElementSlot);
    } catch (OutOfMemoryError e) {
      this.keys = prevKeys;
      throw new BufferAllocationException(
          "Not enough memory to allocate buffers for rehashing: %,d -> %,d", 
          e,
          this.keys == null ? 0 : size(), 
          arraySize);
    }

    this.resizeAt = expandAtCount(arraySize, loadFactor);
    this.keyMixer = newKeyMixer;
    this.mask = arraySize - 1;
  }
883585
private void increaseCapacity() {
    int newCapacity = (valueslength.capacity() == 0) ? DEFAULT_INIT_SIZE
        : valueslength.capacity() < 64 ? valueslength.capacity() * 2
            : valueslength.capacity() < 1024 ? valueslength.capacity() * 3 / 2
                : valueslength.capacity() * 5 / 4;

    final ShortBuffer nv = ShortBuffer.allocate(newCapacity);
    valueslength.rewind();
    nv.put(valueslength);
    valueslength = nv;
  }
432255
public long cacheSize() {
    if (use_lru) {
      return (int) (lru_name_cache.size() + lru_id_cache.size());
    }
    return name_cache.size() + id_cache.size();
  }