Data can be numpy array or the size of data to allocate.
181926
def glBufferData(target, data, usage):
    
    if isinstance(data, int):
        size = data
        data = ctypes.c_voidp(0)
    else:
        if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
            data = data.copy('C')
        data_ = data
        size = data_.nbytes
        data = data_.ctypes.data
    res = _lib.glBufferData(target, size, data, usage)
219372
def data(self, data: numpy.ndarray) -> None:
        
        self.__data_item.set_data(numpy.copy(data))
1065716
def subset(data, sel0=None, sel1=None, blen=None, storage=None, create='array',
           **kwargs):
    """"""

    # TODO refactor sel0 and sel1 normalization with ndarray.subset

    # setup
    storage = _util.get_storage(storage)
    blen = _util.get_blen_array(data, blen)
    length = len(data)
    if sel0 is not None:
        sel0 = np.asanyarray(sel0)
    if sel1 is not None:
        sel1 = np.asanyarray(sel1)

    # ensure boolean array for dim 0
    if sel0 is not None and sel0.dtype.kind != 'b':
        # assume indices, convert to boolean condition
        tmp = np.zeros(length, dtype=bool)
        tmp[sel0] = True
        sel0 = tmp

    # ensure indices for dim 1
    if sel1 is not None and sel1.dtype.kind == 'b':
        # assume boolean condition, convert to indices
        sel1, = np.nonzero(sel1)

    # shortcuts
    if sel0 is None and sel1 is None:
        return copy(data, blen=blen, storage=storage, create=create, **kwargs)
    elif sel1 is None:
        return compress(sel0, data, axis=0, blen=blen, storage=storage,
                        create=create, **kwargs)
    elif sel0 is None:
        return take(data, sel1, axis=1, blen=blen, storage=storage,
                    create=create, **kwargs)

    # build output
    sel0_nnz = count_nonzero(sel0)
    out = None
    for i in range(0, length, blen):
        j = min(i+blen, length)
        bsel0 = sel0[i:j]
        # don't access data unless we have to
        if np.any(bsel0):
            block = data[i:j]
            res = _numpy_subset(block, bsel0, sel1)
            if out is None:
                out = getattr(storage, create)(res, expectedlen=sel0_nnz,
                                               **kwargs)
            else:
                out.append(res)

    return out
1290075
private void allocateElements(int numElements) {
        int initialCapacity = MIN_INITIAL_CAPACITY;
        // Find the best power of two to hold elements.
        // Tests "<=" because arrays aren't kept full.
        if (numElements >= initialCapacity) {
            initialCapacity = numElements;
            initialCapacity |= (initialCapacity >>>  1);
            initialCapacity |= (initialCapacity >>>  2);
            initialCapacity |= (initialCapacity >>>  4);
            initialCapacity |= (initialCapacity >>>  8);
            initialCapacity |= (initialCapacity >>> 16);
            initialCapacity++;

            if (initialCapacity < 0)    // Too many elements, must back off
                initialCapacity >>>= 1; // Good luck allocating 2^30 elements
        }
        elements = new Object[initialCapacity];
    }
587350
def append(self, data, size):
        
        return lib.zchunk_append(self._as_parameter_, data, size)
308387
def check_images(data):
    
    if isinstance(data, ndarray):
        data = fromarray(data)
    
    if not isinstance(data, Images):
        data = fromarray(asarray(data))

    if len(data.shape) not in set([3, 4]):
        raise Exception('Number of image dimensions %s must be 2 or 3' % (len(data.shape)))

    return data
1063668
def preallocate(self, data_loader, training):
        
        batch_size = data_loader.batch_size
        max_len = data_loader.dataset.max_len

        src_length = [max_len] * batch_size
        tgt_length = [max_len] * batch_size

        if self.batch_first:
            shape = (batch_size, max_len)
        else:
            shape = (max_len, batch_size)

        src = torch.full(shape, 4, dtype=torch.int64)
        tgt = torch.full(shape, 4, dtype=torch.int64)
        src = src, src_length
        tgt = tgt, tgt_length
        self.iterate(src, tgt, update=False, training=training)
        self.model.zero_grad()
818487
def _compile_dimension_size(self, base_index, array,
                                property, sized_elements):
        """"""
        sort_index = base_index + 2
        sized_elements.sort(key=lambda x: x[sort_index])
        for element_data in sized_elements:
            start, end = element_data[base_index], element_data[sort_index]
            end += start
            element, size = element_data[4:6]

            # Find the total current size of the set
            set_size = sum(array[start:end]) + (end-start-1)*self.margin

            # Work out the extra space we need
            extra_space_needed = getattr(size, property) - set_size
            if extra_space_needed < 0: continue

            # Distribute it among the entries
            extra_space_each = extra_space_needed / (end-start)
            for index in range(start, end):
                array[index] += extra_space_each
458638
def as_int_array(self):
        
        return self.view(
            type=ndarray,
            dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize),
        )
242301
function ArrayType (data, length) {
    if (!(this instanceof ArrayType)) {
      return new ArrayType(data, length)
    }
    debug('creating new array instance')
    ArrayIndex.call(this)
    var item_size = ArrayType.BYTES_PER_ELEMENT
    if (0 === arguments.length) {
      // new IntArray()
      // use the "fixedLength" if provided, otherwise throw an Error
      if (fixedLength > 0) {
        this.length = fixedLength
        this.buffer = new Buffer(this.length * item_size)
      } else {
        throw new Error('A "length", "array" or "buffer" must be passed as the first argument')
      }
    } else if ('number' == typeof data) {
      // new IntArray(69)
      this.length = data
      this.buffer = new Buffer(this.length * item_size)
    } else if (isArray(data)) {
      // new IntArray([ 1, 2, 3, 4, 5 ], {len})
      // use optional "length" if provided, otherwise use "fixedLength, otherwise
      // use the Array's .length
      var len = 0
      if (null != length) {
        len = length
      } else if (fixedLength > 0) {
        len = fixedLength
      } else {
        len = data.length
      }
      if (data.length < len) {
        throw new Error('array length must be at least ' + len + ', got ' + data.length)
      }
      this.length = len
      this.buffer = new Buffer(len * item_size)
      for (var i = 0; i < len; i++) {
        this[i] = data[i]
      }
    } else if (Buffer.isBuffer(data)) {
      // new IntArray(Buffer(8))
      var len = 0
      if (null != length) {
        len = length
      } else if (fixedLength > 0) {
        len = fixedLength
      } else {
        len = data.length / item_size | 0
      }
      var expectedLength = item_size * len
      this.length = len
      if (data.length != expectedLength) {
        if (data.length < expectedLength) {
          throw new Error('buffer length must be at least ' + expectedLength + ', got ' + data.length)
        } else {
          debug('resizing buffer from %d to %d', data.length, expectedLength)
          data = data.slice(0, expectedLength)
        }
      }
      this.buffer = data
    }
  }
1031604
def set_data(self, data):
		""
		if data is None:
			self.data_size = 0
			self.data = None
			return
		self.data_size = len(data)
		# create a string buffer so that null bytes aren't interpreted
		#  as the end of the string
		self.data = ctypes.cast(ctypes.create_string_buffer(data), ctypes.c_void_p)
45083
def expand_array(data,
                 scans,
                 c_align,
                 c_exp,
                 scan_size=16,
                 tpz_size=16,
                 nties=200,
                 track_offset=0.5,
                 scan_offset=0.5):
    """"""
    nties = np.asscalar(nties)
    tpz_size = np.asscalar(tpz_size)
    s_scan, s_track = da.meshgrid(np.arange(nties * tpz_size),
                                  np.arange(scans * scan_size))
    s_track = (s_track.reshape(scans, scan_size, nties, tpz_size) % scan_size +
               track_offset) / scan_size
    s_scan = (s_scan.reshape(scans, scan_size, nties, tpz_size) % tpz_size +
              scan_offset) / tpz_size

    a_scan = s_scan + s_scan * (1 - s_scan) * c_exp + s_track * (
        1 - s_track) * c_align
    a_track = s_track

    data_a = data[:scans * 2:2, np.newaxis, :-1, np.newaxis]
    data_b = data[:scans * 2:2, np.newaxis, 1:, np.newaxis]
    data_c = data[1:scans * 2:2, np.newaxis, 1:, np.newaxis]
    data_d = data[1:scans * 2:2, np.newaxis, :-1, np.newaxis]

    fdata = ((1 - a_track) *
             ((1 - a_scan) * data_a + a_scan * data_b) + a_track * (
                 (1 - a_scan) * data_d + a_scan * data_c))
    return fdata.reshape(scans * scan_size, nties * tpz_size)
1037403
def all_gather(data):
    
    world_size = get_world_size()
    if world_size == 1:
        return [data]

    # serialized to a Tensor
    buffer = pickle.dumps(data)
    storage = torch.ByteStorage.from_buffer(buffer)
    tensor = torch.ByteTensor(storage).to("cuda")

    # obtain Tensor size of each rank
    local_size = torch.IntTensor([tensor.numel()]).to("cuda")
    size_list = [torch.IntTensor([0]).to("cuda") for _ in range(world_size)]
    dist.all_gather(size_list, local_size)
    size_list = [int(size.item()) for size in size_list]
    max_size = max(size_list)

    # receiving Tensor from all ranks
    # we pad the tensor because torch all_gather does not support
    # gathering tensors of different shapes
    tensor_list = []
    for _ in size_list:
        tensor_list.append(torch.ByteTensor(size=(max_size,)).to("cuda"))
    if local_size != max_size:
        padding = torch.ByteTensor(size=(max_size - local_size,)).to("cuda")
        tensor = torch.cat((tensor, padding), dim=0)
    dist.all_gather(tensor_list, tensor)

    data_list = []
    for size, tensor in zip(size_list, tensor_list):
        buffer = tensor.cpu().numpy().tobytes()[:size]
        data_list.append(pickle.loads(buffer))

    return data_list
578602
def bytes_required(self):
        
        return np.sum([hcu.array_bytes(a) for a
            in self.arrays(reify=True).itervalues()])
72357
private int allocate(int size)
    {
        while (true)
        {
            int prev = allocatePosition.get();
            int next = prev + size;
            if (next >= buffer.capacity())
                return -1;
            if (allocatePosition.compareAndSet(prev, next))
                return prev;
        }
    }
81106
def _initialise_data(self, memmap_dir=None):
        """"""

        if self.number_values == 0:
            pass
        elif self.data_type.nptype is None:
            self._data = []
        else:
            if memmap_dir:
                memmap_file = tempfile.NamedTemporaryFile(
                    mode='w+b', prefix="nptdms_", dir=memmap_dir)
                self._data = np.memmap(
                    memmap_file.file,
                    mode='w+',
                    shape=(self.number_values,),
                    dtype=self.data_type.nptype)
            else:
                self._data = np.zeros(
                    self.number_values, dtype=self.data_type.nptype)
            self._data_insert_position = 0
        if self._data is not None:
            log.debug("Allocated %d sample slots for %s", len(self._data),
                      self.path)
        else:
            log.debug("Allocated no space for %s", self.path)
616238
private static void enlargeTables(float[][] data, int[][] rowIndex, int cols, int currentRow, int currentCol) {
        while (data[currentRow].length < currentCol + cols) {
            if(data[currentRow].length == SPARSE_MATRIX_DIM) {
                currentCol = 0;
                cols -= (data[currentRow].length - currentCol);
                currentRow++;
                data[currentRow] = malloc4f(ALLOCATED_ARRAY_LEN);
                rowIndex[currentRow] = malloc4(ALLOCATED_ARRAY_LEN);
            } else {
                int newLen = (int) Math.min((long) data[currentRow].length << 1L, (long) SPARSE_MATRIX_DIM);
                data[currentRow] = Arrays.copyOf(data[currentRow], newLen);
                rowIndex[currentRow] = Arrays.copyOf(rowIndex[currentRow], newLen);
            }
        }
    }