gstreamer buffer to numpy array conversion
765051
def gst_buffer_to_numpy_array(buf, chan):
    
    samples = frombuffer(buf.data, dtype='float32').reshape((-1, chan))
    return samples
201860
def _to_numpy(nd4j_array):
    
    buff = nd4j_array.data()
    address = buff.pointer().address()
    dtype = get_context_dtype()
    mapping = {
        'double': ctypes.c_double,
        'float': ctypes.c_float
    }
    Pointer = ctypes.POINTER(mapping[dtype])
    pointer = ctypes.cast(address, Pointer)
    np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape()))
    return np_array
785618
def buffer_to_audio(buffer: bytes) -> np.ndarray:
    """"""
    return np.fromstring(buffer, dtype='<i2').astype(np.float32, order='C') / 32768.0
1158095
function toArray(buffer) {
    if(!buffer) buffer = new Buffer(0);
    var view = new Uint8Array(buffer.length);
    for (var i = 0; i < buffer.length; ++i) {
        view[i] = buffer[i];
    }
    return view;
  }
1291061
def be_array_from_bytes(fmt, data):
    
    arr = array.array(str(fmt), data)
    return fix_byteorder(arr)
434186
def toJArray(gateway, jtype, arr):
    
    jarr = gateway.new_array(jtype, len(arr))
    for i in range(0, len(arr)):
        jarr[i] = arr[i]
    return jarr
857192
function base64ArrayBuffer(bytes) {
    var base64    = ''
    var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

    var byteLength    = bytes.byteLength
    var byteRemainder = byteLength % 3
    var mainLength    = byteLength - byteRemainder
   
    var a, b, c, d
    var chunk
   
    // Main loop deals with bytes in chunks of 3
    for (var i = 0; i < mainLength; i = i + 3) {
      // Combine the three bytes into a single integer
      chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
   
      // Use bitmasks to extract 6-bit segments from the triplet
      a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
      b = (chunk & 258048)   >> 12 // 258048   = (2^6 - 1) << 12
      c = (chunk & 4032)     >>  6 // 4032     = (2^6 - 1) << 6
      d = chunk & 63               // 63       = 2^6 - 1
   
      // Convert the raw binary segments to the appropriate ASCII encoding
      base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
    }
   
    // Deal with the remaining bytes and padding
    if (byteRemainder == 1) {
      chunk = bytes[mainLength]
   
      a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
   
      // Set the 4 least significant bits to zero
      b = (chunk & 3)   << 4 // 3   = 2^2 - 1
   
      base64 += encodings[a] + encodings[b] + '=='
    } else if (byteRemainder == 2) {
      chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
   
      a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
      b = (chunk & 1008)  >>  4 // 1008  = (2^6 - 1) << 4
   
      // Set the 2 least significant bits to zero
      c = (chunk & 15)    <<  2 // 15    = 2^4 - 1
   
      base64 += encodings[a] + encodings[b] + encodings[c] + '='
    }
    
    return base64
  }
474014
def decode_qp_numpy(msg, return_matrix=True):
    
    import numpy as np

    result = msg['answer']

    # Build some little endian type encodings
    double_type = np.dtype(np.double)
    double_type = double_type.newbyteorder('<')
    int_type = np.dtype(np.int32)
    int_type = int_type.newbyteorder('<')

    # Decode the simple buffers
    result['energies'] = np.frombuffer(base64.b64decode(result['energies']),
                                       dtype=double_type)

    if 'num_occurrences' in result:
        result['num_occurrences'] = \
            np.frombuffer(base64.b64decode(result['num_occurrences']),
                        dtype=int_type)

    result['active_variables'] = \
        np.frombuffer(base64.b64decode(result['active_variables']),
                      dtype=int_type)

    # Measure out the binary data size
    num_solutions = len(result['energies'])
    active_variables = result['active_variables']
    num_variables = len(active_variables)
    total_variables = result['num_variables']

    # Decode the solutions, which will be a continuous run of bits
    byte_type = np.dtype(np.uint8)
    byte_type = byte_type.newbyteorder('<')
    bits = np.unpackbits(np.frombuffer(base64.b64decode(result['solutions']),
                         dtype=byte_type))

    # Clip off the extra bits from encoding
    if num_solutions:
        bits = np.reshape(bits, (num_solutions, bits.size // num_solutions))
        bits = np.delete(bits, range(num_variables, bits.shape[1]), 1)

    # Switch from bits to spins
    default = 3
    if msg['type'] == 'ising':
        bits = bits.astype(np.int8)
        bits *= 2
        bits -= 1
        default = 0

    # Fill in the missing variables
    solutions = np.full((num_solutions, total_variables), default, dtype=np.int8)
    solutions[:, active_variables] = bits
    result['solutions'] = solutions

    # If the final result shouldn't be numpy formats switch back to python objects
    if not return_matrix:
        result['energies'] = result['energies'].tolist()
        if 'num_occurrences' in result:
            result['num_occurrences'] = result['num_occurrences'].tolist()
        result['active_variables'] = result['active_variables'].tolist()
        result['solutions'] = result['solutions'].tolist()

    return result
547192
function dataViewToArrayBuffer(str) {
    var bufView = new Uint8Array(dv.byteLength);
    for (var i = 0; i < bufView.length; i++) {
      bufView[i] = dv.getUint8(i);
    }
    return bufView.buffer;
  }
1124959
def _get_array(val, shape, default=None, dtype=np.float64):
    """"""
    assert val is not None or default is not None
    if hasattr(val, '__len__') and len(val) == 0:  # pragma: no cover
        val = None
    # Do nothing if the array is already correct.
    if (isinstance(val, np.ndarray) and
            val.shape == shape and
            val.dtype == dtype):
        return val
    out = np.zeros(shape, dtype=dtype)
    # This solves `ValueError: could not broadcast input array from shape (n)
    # into shape (n, 1)`.
    if val is not None and isinstance(val, np.ndarray):
        if val.size == out.size:
            val = val.reshape(out.shape)
    out.flat[:] = val if val is not None else default
    assert out.shape == shape
    return out
73491
def _numpy_bytes_to_char(arr):
    
    # ensure the array is contiguous
    arr = np.array(arr, copy=False, order='C', dtype=np.string_)
    return arr.reshape(arr.shape + (1,)).view('S1')
809699
def _serialize_buffer(buffer, array_serialization=None):
    """"""
    if array_serialization == 'binary':
        # WARNING: in NumPy 1.9, tostring() has been renamed to tobytes()
        # but tostring() is still here for now for backward compatibility.
        return buffer.ravel().tostring()
    elif array_serialization == 'base64':
        return {'storage_type': 'base64',
                'buffer': base64.b64encode(buffer).decode('ascii')
                }
    raise ValueError("The array serialization method should be 'binary' or "
                     "'base64'.")
798227
def _to_array(self, alpha, normalization='4pi', csphase=1):
        
        coeffs = _shtools.SHVectorToCilm(self.tapers[:, alpha])

        if normalization == 'schmidt':
            for l in range(self.lmax + 1):
                coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
        elif normalization == 'ortho':
            coeffs *= _np.sqrt(4.0 * _np.pi)

        if csphase == -1:
            for m in range(self.lmax + 1):
                if m % 2 == 1:
                    coeffs[:, :, m] = - coeffs[:, :, m]

        return coeffs
716400
function parse_PtgExtraArray(blob, length, opts) {
	var rows = 0, cols = 0;
	if(opts.biff == 12) {
		rows = blob.read_shift(4); // DRw
		cols = blob.read_shift(4); // DCol
	} else {
		cols = 1 + blob.read_shift(1); //DColByteU
		rows = 1 + blob.read_shift(2); //DRw
	}
	if(opts.biff >= 2 && opts.biff < 8) { --rows; if(--cols == 0) cols = 0x100; }
	// $FlowIgnore
	for(var i = 0, o/*:Array<Array<any>>*/ = []; i != rows && (o[i] = []); ++i)
		for(var j = 0; j != cols; ++j) o[i][j] = parse_SerAr(blob, opts.biff);
	return o;
}
875037
def _internal_write(out_stream, arr):
    

    if arr.size == 0:
        raise FormatError('Cannot encode empty array.')

    try:
        type_byte, struct_lib_type = _DATA_TYPES_NUMPY[str(arr.dtype)]
    except KeyError:
        raise FormatError('numpy ndarray type not supported by IDX format.')

    if arr.ndim > _MAX_IDX_DIMENSIONS:
        raise FormatError(
            'IDX format cannot encode array with dimensions > 255')

    if max(arr.shape) > _MAX_AXIS_LENGTH:
        raise FormatError('IDX format cannot encode array with more than ' +
                          str(_MAX_AXIS_LENGTH) + ' elements along any axis')

    # Write magic number
    out_stream.write(struct.pack('BBBB', 0, 0, type_byte, arr.ndim))

    # Write array dimensions
    out_stream.write(struct.pack('>' + 'I' * arr.ndim, *arr.shape))

    # Horrible hack to deal with horrible bug when using struct.pack to encode
    # unsigned ints in 2.7 and lower, see http://bugs.python.org/issue2263
    if sys.version_info < (2, 7) and str(arr.dtype) == 'uint8':
        arr_as_list = [int(i) for i in arr.reshape(-1)]
        out_stream.write(struct.pack('>' + struct_lib_type * arr.size,
                                     *arr_as_list))
    else:
        # Write array contents - note that the limit to number of arguments
        # doesn't apply to unrolled arguments
        out_stream.write(struct.pack('>' + struct_lib_type * arr.size,
                                     *arr.reshape(-1)))
888086
def _convert_1bit_array_to_byte_array(arr):
    
    # Padding if necessary
    while len(arr) < 8 or len(arr) % 8:
        arr.append(0)

    arr = _np.array(arr, dtype='uint8')
    bit_arr = []
    idx = 0
    # Iterate and combine 8-bits into a uint8
    for arr_idx in range(int(len(arr) / 8)):
        bit_arr.append(((arr[idx] << 7) & (1 << 7)) |
                        ((arr[idx+1] << 6) & (1 << 6)) |
                        ((arr[idx+2] << 5) & (1 << 5)) |
                        ((arr[idx+3] << 4) & (1 << 4)) |
                        ((arr[idx+4] << 3) & (1 << 3)) |
                        ((arr[idx+5] << 2) & (1 << 2)) |
                        ((arr[idx+6] << 1) & (1 << 1)) |
                        ((arr[idx+7] << 0) & (1 << 0))
                        )
        idx += 8
    return _np.array(bit_arr, dtype='uint8')
727818
def from_array(cls, array, filename=None, channels=3, scale_to_range=False,
                   grayscale=False, channel_bitdepth=8,
                   has_alpha=False, palette=None):
        
        if scale_to_range:
            amax = array.max()
            amin = array.min()
            _array = (2**channel_bitdepth - 1) * (array - amin) / (amax - amin)
        else:
            _array = array
        _array = numpy.rint(_array).astype(dtype=PNGWriter.get_dtype(channel_bitdepth))  # proper rounding
        return cls(_array, filename, channels=channels,
                   grayscale=grayscale, channel_bitdepth=channel_bitdepth,
                   has_alpha=has_alpha, palette=palette)