Create a block storage
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}
958282
async def create(cls, block_device: BlockDevice, size: int):
        
        params = {}
        if isinstance(block_device, BlockDevice):
            params['system_id'] = block_device.node.system_id
            params['device_id'] = block_device.id
        else:
            raise TypeError(
                'block_device must be a BlockDevice, not %s' % (
                    type(block_device).__name__))

        if not size:
            raise ValueError("size must be provided and greater than zero.")
        params['size'] = size
        return cls._object(await cls._handler.create(**params))
430559
def cli(env, volume_id):
    """"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volume = block_manager.get_block_volume_details(volume_id)
    block_volume = utils.NestedDict(block_volume)

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    storage_type = block_volume['storageType']['keyName'].split('_').pop(0)
    table.add_row(['ID', block_volume['id']])
    table.add_row(['Username', block_volume['username']])
    table.add_row(['Type', storage_type])
    table.add_row(['Capacity (GB)', "%iGB" % block_volume['capacityGb']])
    table.add_row(['LUN Id', "%s" % block_volume['lunId']])

    if block_volume.get('provisionedIops'):
        table.add_row(['IOPs', float(block_volume['provisionedIops'])])

    if block_volume.get('storageTierLevel'):
        table.add_row([
            'Endurance Tier',
            block_volume['storageTierLevel'],
        ])

    table.add_row([
        'Data Center',
        block_volume['serviceResource']['datacenter']['name'],
    ])
    table.add_row([
        'Target IP',
        block_volume['serviceResourceBackendIpAddress'],
    ])

    if block_volume['snapshotCapacityGb']:
        table.add_row([
            'Snapshot Capacity (GB)',
            block_volume['snapshotCapacityGb'],
        ])
        if 'snapshotSizeBytes' in block_volume['parentVolume']:
            table.add_row([
                'Snapshot Used (Bytes)',
                block_volume['parentVolume']['snapshotSizeBytes'],
            ])

    table.add_row(['# of Active Transactions', "%i"
                   % block_volume['activeTransactionCount']])

    if block_volume['activeTransactions']:
        for trans in block_volume['activeTransactions']:
            if 'transactionStatus' in trans and 'friendlyName' in trans['transactionStatus']:
                table.add_row(['Ongoing Transaction', trans['transactionStatus']['friendlyName']])

    table.add_row(['Replicant Count', "%u" % block_volume.get('replicationPartnerCount', 0)])

    if block_volume['replicationPartnerCount'] > 0:
        # This if/else temporarily handles a bug in which the SL API
        # returns a string or object for 'replicationStatus'; it seems that
        # the type is string for File volumes and object for Block volumes
        if 'message' in block_volume['replicationStatus']:
            table.add_row(['Replication Status', "%s"
                           % block_volume['replicationStatus']['message']])
        else:
            table.add_row(['Replication Status', "%s"
                           % block_volume['replicationStatus']])

        replicant_list = []
        for replicant in block_volume['replicationPartners']:
            replicant_table = formatting.Table(['Replicant ID',
                                                replicant['id']])
            replicant_table.add_row([
                'Volume Name',
                utils.lookup(replicant, 'username')])
            replicant_table.add_row([
                'Target IP',
                utils.lookup(replicant, 'serviceResourceBackendIpAddress')])
            replicant_table.add_row([
                'Data Center',
                utils.lookup(replicant,
                             'serviceResource', 'datacenter', 'name')])
            replicant_table.add_row([
                'Schedule',
                utils.lookup(replicant,
                             'replicationSchedule', 'type', 'keyname')])
            replicant_list.append(replicant_table)
        table.add_row(['Replicant Volumes', replicant_list])

    if block_volume.get('originalVolumeSize'):
        original_volume_info = formatting.Table(['Property', 'Value'])
        original_volume_info.add_row(['Original Volume Size', block_volume['originalVolumeSize']])
        if block_volume.get('originalVolumeName'):
            original_volume_info.add_row(['Original Volume Name', block_volume['originalVolumeName']])
        if block_volume.get('originalSnapshotName'):
            original_volume_info.add_row(['Original Snapshot Name', block_volume['originalSnapshotName']])
        table.add_row(['Original Volume Properties', original_volume_info])

    env.fout(table)
609048
@Override
	protected void writeDataBlock(byte[] data, int offset, int len, int blockHandle) throws DataStoreException
    {
    	try
        {
	        dataRandomAccessFile.seek((long)blockHandle*blockSize);
	        dataRandomAccessFile.write(data,offset,len);
        }
    	catch (IOException e)
    	{
    		throw new DataStoreException("Cannot write data block "+blockHandle+" : "+dataFile.getAbsolutePath(),e);
    	}
    }
266091
function createFileDecoder(path, opts) {
  return fs.createReadStream(path)
    .pipe(new containers.streams.BlockDecoder(opts));
}
701180
function() {
        if (!this.blocks) {
            this.createBlocks();
        }
        
        if (this.size && this.relativePosition) {
            var position = this.positionBlocks[this.relativePosition];
            for (var i = 0; i < position.blocks.length; i++) {
    
                var positionBlock = position.blocks[i];
                var block = this.blocks[i];
    
                // adjust sizes
                var l = positionBlock.anchor.left;
                var b = positionBlock.anchor.bottom;
                var r = positionBlock.anchor.right;
                var t = positionBlock.anchor.top;
    
                //note that we use the isNaN() test here because if the 
                // size object is initialized with a "auto" parameter, the 
                // size constructor calls parseFloat() on the string, 
                // which will turn it into NaN
                //
                var w = (isNaN(positionBlock.size.w)) ? this.size.w - (r + l) 
                                                      : positionBlock.size.w;
    
                var h = (isNaN(positionBlock.size.h)) ? this.size.h - (b + t) 
                                                      : positionBlock.size.h;
    
                block.div.style.width = (w < 0 ? 0 : w) + 'px';
                block.div.style.height = (h < 0 ? 0 : h) + 'px';
    
                block.div.style.left = (l != null) ? l + 'px' : '';
                block.div.style.bottom = (b != null) ? b + 'px' : '';
                block.div.style.right = (r != null) ? r + 'px' : '';            
                block.div.style.top = (t != null) ? t + 'px' : '';
    
                block.image.style.left = positionBlock.position.x + 'px';
                block.image.style.top = positionBlock.position.y + 'px';
            }
    
            this.contentDiv.style.left = this.padding.left + "px";
            this.contentDiv.style.top = this.padding.top + "px";
        }
    }
367827
def p_generate_block(self, p):
        ''
        p[0] = Block(p[2], lineno=p.lineno(1))
        p.set_lineno(0, p.lineno(1))
845417
def map_block_storage(service, pool, image):
    """"""
    cmd = [
        'rbd',
        'map',
        '{}/{}'.format(pool, image),
        '--user',
        service,
        '--secret',
        _keyfile_path(service),
    ]
    check_call(cmd)
579822
function blockChecksums(fs, path, size, callback) {
  var cache = {};

  fs.readFile(path, function (err, data) {
    if (!err) {
      // cache file
      cache[path] = data;
    } else if (err && err.code === 'ENOENT') {
      cache[path] = [];
    } else {
      return callback(err);
    }

    var length = cache[path].length;
    var incr = size;
    var start = 0;
    var end = incr > length ? length : incr;
    var blockIndex = 0;
    var result = [];
    var chunk;
    var weak;
    var strong;

    while (start < length) {
      chunk  = cache[path].slice(start, end);
      weak   = calcWeak32(chunk).sum;
      strong = md5sum(chunk);

      result.push({
        index: blockIndex,
        weak: weak,
        strong: strong
      });
      // update slice indices
      start += incr;
      end = (end + incr) > length ? length : end + incr;
      // update block index
      blockIndex++;
    }

    callback(null, result);
  });
}
108920
private DataBlock getWriteDataBlock() throws IOException {
        if (writableBlocks.size() != 0) {
            return writableBlocks.get(0);
        }

        lock.lock();
        try {
            if (writableBlocks.size() != 0) {
                return writableBlocks.get(0);
            }
            DataBlock dataBlock = new DataBlock(storeConfig);
            NAME_BLOCK_MAP.put(dataBlock.getFileId(), dataBlock);
            writableBlocks.add(dataBlock);
            return dataBlock;
        } finally {
            lock.unlock();
        }
    }
781340
private LocatedBlocks createLocatedBlocks(INode node) throws IOException {
     LocatedBlocks loc = null;
     if (node instanceof INodeFile) {
       loc = getFSNamesystem().getBlockLocationsInternal(
           (INodeFile)node, 0L, Long.MAX_VALUE, Integer.MAX_VALUE);
     }
     if (loc==null) {
       loc = EMPTY_BLOCK_LOCS;
     }
     return loc;
   }
224144
def _writeblock(cls, block, is_last=False):
        

        data = bytearray()
        code = (block.code | 128) if is_last else block.code
        datum = block.write()
        size = len(datum)
        if size > cls._MAX_SIZE:
            if block._distrust_size and block._invalid_overflow_size != -1:
                # The original size of this block was (1) wrong and (2)
                # the real size doesn't allow us to save the file
                # according to the spec (too big for 24 bit uint). Instead
                # simply write back the original wrong size.. at least
                # we don't make the file more "broken" as it is.
                size = block._invalid_overflow_size
            else:
                raise error("block is too long to write")
        assert not size > cls._MAX_SIZE
        length = struct.pack(">I", size)[-3:]
        data.append(code)
        data += length
        data += datum
        return data
1186135
def create(blocks, mode='basic', inplanes=16, divisor=4, num_classes=1000):
    
    block_dict = {
        'basic': BasicBlock,
        'bottleneck': Bottleneck
    }

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

    return ModelFactory.generic(instantiate)
1358357
Block addBlock(String path, INode[] inodes, Block block) throws IOException {
    waitForReady();

    writeLock();
    try {
      INodeFile fileNode = (INodeFile) inodes[inodes.length-1];
      INode.enforceRegularStorageINode(fileNode, 
          "addBlock only works for regular file, not " + path);
      
      // check quota limits and updated space consumed
      updateCount(inodes, inodes.length-1, 0,
          fileNode.getPreferredBlockSize()*fileNode.getReplication(), true);

      // associate the new list of blocks with this file
      BlockInfo blockInfo = 
          getFSNamesystem().blocksMap.addINode(block, fileNode,
              fileNode.getReplication());
      fileNode.getStorage().addBlock(blockInfo);

      if (NameNode.stateChangeLog.isDebugEnabled()) {
        NameNode.stateChangeLog.debug("DIR* FSDirectory.addFile: "
                                      + path + " with " + block
                                      + " block is added to the in-memory "
                                      + "file system");
      }
    } finally {
      writeUnlock();
    }
    return block;
  }
70570
void insertIntoList(BlockInfo head, int headIndex, BlockInfo tail, int tailIndex, int count) {
    if (head == null)
      return;
    
    // connect tail to now-head
    tail.setNext(tailIndex, blockList);
    if (blockList != null)
      blockList.setPrevious(blockList.findDatanode(this), tail);
    
    // create new head
    blockList = head;
    blockList.setPrevious(headIndex, null);
    
    // add new blocks to the count
    numOfBlocks += count;
  }
290347
def insert_or_append_blocks(self, blocks):
        """"""
        start = 0
        bulk_insert = self.bulk_insert
        blocks_len = len(blocks)
        select = 'SELECT ?,?,?,"",0'
        query = 'INSERT OR IGNORE INTO gauged_data (namespace, offset, ' \
            '`key`, data, flags) '
        execute = self.cursor.execute
        while start < blocks_len:
            rows = blocks[start:start+bulk_insert]
            params = []
            for namespace, offset, key, _, _ in rows:
                params.extend((namespace, offset, key))
            insert = (select + ' UNION ') * (len(rows) - 1) + select
            execute(query + insert, params)
            start += bulk_insert
        for namespace, offset, key, data, flags in blocks:
            execute('UPDATE gauged_data SET data = CAST(data || ? AS BLOB),'
                    'flags = ? WHERE namespace = ? AND offset = ? AND '
                    '`key` = ?', (data, flags, namespace, offset, key))
1175077
protected function setupFileDocBlock() {
	    $warn = PHP_EOL . "SAFE TO EDIT, BUILDER WILL NEVER OVERWRITE";
	    if (in_array($this->type, ['DataTable', 'EntityAbstract'])) {
	        $warn = PHP_EOL . "DO NOT MAKE CHANGES TO THIS FILE";
	    }
		$docBlock = DocBlockGenerator::fromArray(array(
			'shortDescription' => $this->type,
			'longDescription' => "Generated {$this->type}{$warn}",
			'tags' => array(
				array(
					'name' => 'package',
					'description' => $this->getNames()->namespace_entity),
				array(
					'name' => 'author',
					'description' => 'Philip Michael Raab<philip@cathedral.co.za>'),
				array(
					'name' => 'version',
					'description' => self::version))));
		$this->_file->setDocBlock($docBlock);
	}