Convenince method for creating a 
  shared memory numpy array based on a CloudVolume
  and Bbox. c.f. sharedmemory.ndarray for information
  on the optional lock parameter.
9079
def bbox2array(vol, bbox, order='F', readonly=False, lock=None, location=None):
  """"""
  location = location or vol.shared_memory_id
  shape = list(bbox.size3()) + [ vol.num_channels ]
  return ndarray(shape=shape, dtype=vol.dtype, location=location, 
    readonly=readonly, lock=lock, order=order)
1161841
def array_bytes(array):
    
    return np.product(array.shape)*np.dtype(array.dtype).itemsize
563746
def create(blocks, mode='basic', inplanes=64, cardinality=4, image_features=64, divisor=4, num_classes=1000):
    
    block_dict = {
        # 'basic': BasicBlock,
        'bottleneck': ResNeXtBottleneck
    }

    def instantiate(**_):
        return ResNeXt(block_dict[mode], blocks, inplanes=inplanes, image_features=image_features, cardinality=cardinality, divisor=divisor, num_classes=num_classes)

    return ModelFactory.generic(instantiate)
761323
def array(self, size_chunk, start, bytesize):
        ''' 
        '''

        with open(self.img, 'rb') as f1:
            f1.seek(self.start_byte + start * self.bytesize)
            data = f1.read(size_chunk * self.bytesize)
            Z = np.fromstring(data, dtype=self.dtype, count=size_chunk)
            if self.grid == 'LOLA':
                return Z * float(self.SCALING_FACTOR)
            else:
                return Z
424387
def create_block_storage(kwargs=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The create_block_storage function must be called with '
            '-f or --function'
        )

    conn = get_conn()

    # Assemble the composite block storage object.
    block_storage = _get_block_storage(kwargs)

    data = conn.create_block_storage(block_storage=block_storage)

    return {'BlockStorage': data}
705231
def arrays_to_mgr(arrays, arr_names, index, columns, dtype=None):
    
    # figure out the index, if necessary
    if index is None:
        index = extract_index(arrays)
    else:
        index = ensure_index(index)

    # don't force copy because getting jammed in an ndarray anyway
    arrays = _homogenize(arrays, index, dtype)

    # from BlockManager perspective
    axes = [ensure_index(columns), index]

    return create_block_manager_from_arrays(arrays, arr_names, axes)
1328099
def pool(inputs, window_size, pooling_type, padding, strides=(1, 1)):
  """"""
  with tf.name_scope("pool", values=[inputs]):
    static_shape = inputs.get_shape()
    if not static_shape or len(static_shape) != 4:
      raise ValueError("Inputs to conv must have statically known rank 4.")
    # Add support for left padding.
    if padding == "LEFT":
      assert window_size[0] % 2 == 1 and window_size[1] % 2 == 1
      if len(static_shape) == 3:
        width_padding = 2 * (window_size[1] // 2)
        padding_ = [[0, 0], [width_padding, 0], [0, 0]]
      else:
        height_padding = 2 * (window_size[0] // 2)
        cond_padding = tf.cond(
            tf.equal(shape_list(inputs)[2], 1), lambda: tf.constant(0),
            lambda: tf.constant(2 * (window_size[1] // 2)))
        width_padding = 0 if static_shape[2] == 1 else cond_padding
        padding_ = [[0, 0], [height_padding, 0], [width_padding, 0], [0, 0]]
      inputs = tf.pad(inputs, padding_)
      inputs.set_shape([static_shape[0], None, None, static_shape[3]])
      padding = "VALID"

  return tf.nn.pool(inputs, window_size, pooling_type, padding, strides=strides)
646900
def createFromMaskedArray(cls, masked_arr):
        
        if isinstance(masked_arr, ArrayWithMask):
            return masked_arr

        check_class(masked_arr, (np.ndarray, ma.MaskedArray))

        # A MaskedConstant (i.e. masked) is a special case of MaskedArray. It does not seem to have
        # a fill_value so we use None to use the default.
        # https://docs.scipy.org/doc/numpy/reference/maskedarray.baseclass.html#numpy.ma.masked
        fill_value = getattr(masked_arr, 'fill_value', None)

        return cls(masked_arr.data, masked_arr.mask, fill_value)
252617
public static <K extends IMeasurableMemory, V extends IMeasurableMemory> ConcurrentLinkedHashCache<K, V> create(long weightedCapacity, EntryWeigher<K, V> entryWeiger)
    {
        ConcurrentLinkedHashMap<K, V> map = new ConcurrentLinkedHashMap.Builder<K, V>()
                                            .weigher(entryWeiger)
                                            .maximumWeightedCapacity(weightedCapacity)
                                            .concurrencyLevel(DEFAULT_CONCURENCY_LEVEL)
                                            .build();

        return new ConcurrentLinkedHashCache<K, V>(map);
    }
715864
def from_numpy(cls, 
      arr, vol_path='file:///tmp/image/'+generate_random_string(),
      resolution=(4,4,40), voxel_offset=(0,0,0), 
      chunk_size=(128,128,64), layer_type=None, max_mip=0,
      encoding='raw', compress=None
    ):
    
    if not layer_type:
      if arr.dtype in (np.bool, np.uint32, np.uint64, np.uint16):
        layer_type = 'segmentation'
      elif np.issubdtype(arr.dtype, np.integer) \
                        or np.issubdtype(arr.dtype, np.floating):
        layer_type = 'image'
      else:
        raise NotImplementedError

    if arr.ndim == 3:
      num_channels = 1
    elif arr.ndim == 4:
      num_channels = arr.shape[-1]
    else:
      raise NotImplementedError

    info = cls.create_new_info(num_channels, layer_type, arr.dtype.name, encoding, resolution, 
                               voxel_offset, arr.shape[:3], chunk_size=chunk_size, max_mip=max_mip)
    vol = CloudVolume(vol_path, info=info, bounded=True, compress=compress) 
    # save the info file
    vol.commit_info()
    vol.provenance.processing.append({
      'method': 'from_numpy',
      'date': strftime('%Y-%m-%d %H:%M %Z')
    })
    vol.commit_provenance()
    # save the numpy array
    vol[:,:,:] = arr
    return vol
42992
def write(self, b):
        
        if not self._writable:
            raise UnsupportedOperation('write')

        # This function write data in a buffer
        # "flush()" need to be called to really write content on
        # Cloud Storage
        size = len(b)
        with self._seek_lock:
            start = self._seek
            end = start + size
            self._seek = end

        buffer = self._write_buffer
        if end <= len(buffer):
            buffer = memoryview(buffer)
        buffer[start:end] = b
        return size
781441
def _create_bvals_bvecs(multiframe_dicom, bval_file, bvec_file, nifti, nifti_file):
    

    # create the empty arrays
    number_of_stack_slices = common.get_ss_value(multiframe_dicom[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)])
    number_of_stacks = int(int(multiframe_dicom.NumberOfFrames) / number_of_stack_slices)

    bvals = numpy.zeros([number_of_stacks], dtype=numpy.int32)
    bvecs = numpy.zeros([number_of_stacks, 3])

    # loop over all timepoints and create a list with all bvals and bvecs
    for stack_index in range(0, number_of_stacks):
        stack = multiframe_dicom[Tag(0x5200, 0x9230)][stack_index]
        if str(stack[Tag(0x0018, 0x9117)][0][Tag(0x0018, 0x9075)].value) == 'DIRECTIONAL':
            bvals[stack_index] = common.get_fd_value(stack[Tag(0x0018, 0x9117)][0][Tag(0x0018, 0x9087)])
            bvecs[stack_index, :] = common.get_fd_array_value(stack[Tag(0x0018, 0x9117)][0]
                                                              [Tag(0x0018, 0x9076)][0][Tag(0x0018, 0x9089)], 3)

    # truncate nifti if needed
    nifti, bvals, bvecs = _fix_diffusion_images(bvals, bvecs, nifti, nifti_file)

    # save the found bvecs to the file
    if numpy.count_nonzero(bvals) > 0 or numpy.count_nonzero(bvecs) > 0:
        common.write_bval_file(bvals, bval_file)
        common.write_bvec_file(bvecs, bvec_file)
    else:
        bval_file = None
        bvec_file = None
        bvals = None
        bvecs = None

    return bvals, bvecs, bval_file, bvec_file
220736
def asarray_ndim(a, *ndims, **kwargs):
    
    allow_none = kwargs.pop('allow_none', False)
    kwargs.setdefault('copy', False)
    if a is None and allow_none:
        return None
    a = np.array(a, **kwargs)
    if a.ndim not in ndims:
        if len(ndims) > 1:
            expect_str = 'one of %s' % str(ndims)
        else:
            # noinspection PyUnresolvedReferences
            expect_str = '%s' % ndims[0]
        raise TypeError('bad number of dimensions: expected %s; found %s' %
                        (expect_str, a.ndim))
    return a
977811
def create(self, *args, **kwargs):
        
        try:
            return super(CloudBlockStorageManager, self).create(*args,
                    **kwargs)
        except exc.BadRequest as e:
            msg = e.message
            if "Clones currently must be >= original volume size" in msg:
                raise exc.VolumeCloneTooSmall(msg)
            else:
                raise
1127550
def NewMemory(self, buffer, size, URL, encoding, options):
        
        ret = libxml2mod.xmlReaderNewMemory(self._o, buffer, size, URL, encoding, options)
        return ret
578602
def bytes_required(self):
        
        return np.sum([hcu.array_bytes(a) for a
            in self.arrays(reify=True).itervalues()])
1320421
def array_const(self):
        
        self.eat(TokenTypes.LBRACKET)
        node = Array(self.arg_list(TokenTypes.RBRACKET))
        self.eat(TokenTypes.RBRACKET)
        return node