Return Context Manager for a file-like (stream) object to store volume info.
7768
def receiveVolumeInfo(self, paths):
        
        path = self.selectReceivePath(paths)
        path = path + Store.theInfoExtension

        if Store.skipDryRun(logger, self.dryrun)("receive info to %s", path):
            return None

        self._client.receiveInfo(path)

        return _SSHStream(self._client)
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)
728195
def exhaust_stream(f):
    """"""

    def wrapper(self, stream, *args, **kwargs):
        try:
            return f(self, stream, *args, **kwargs)
        finally:
            exhaust = getattr(stream, "exhaust", None)
            if exhaust is not None:
                exhaust()
            else:
                while 1:
                    chunk = stream.read(1024 * 64)
                    if not chunk:
                        break

    return update_wrapper(wrapper, f)
264189
def cli(env, volume_id):
    """"""

    file_manager = SoftLayer.FileStorageManager(env.client)

    snapshot_schedules = file_manager.list_volume_schedules(volume_id)

    table = formatting.Table(['id',
                              'active',
                              'type',
                              'replication',
                              'date_created',
                              'minute',
                              'hour',
                              'day',
                              'week',
                              'day_of_week',
                              'date_of_month',
                              'month_of_year',
                              'maximum_snapshots'])

    for schedule in snapshot_schedules:

        if 'REPLICATION' in schedule['type']['keyname']:
            replication = '*'
        else:
            replication = formatting.blank()

        file_schedule_type = schedule['type']['keyname'].replace('REPLICATION_', '')
        file_schedule_type = file_schedule_type.replace('SNAPSHOT_', '')

        property_list = ['MINUTE', 'HOUR', 'DAY', 'WEEK',
                         'DAY_OF_WEEK', 'DAY_OF_MONTH',
                         'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT']

        schedule_properties = []
        for prop_key in property_list:
            item = formatting.blank()
            for schedule_property in schedule.get('properties', []):
                if schedule_property['type']['keyname'] == prop_key:
                    if schedule_property['value'] == '-1':
                        item = '*'
                    else:
                        item = schedule_property['value']
                    break
            schedule_properties.append(item)

        table_row = [
            schedule['id'],
            '*' if schedule.get('active', '') else '',
            file_schedule_type,
            replication,
            schedule.get('createDate', '')
        ]
        table_row.extend(schedule_properties)
        table.add_row(table_row)

    env.fout(table)
937673
def open_file(path, grib_errors='warn', **kwargs):
    """"""
    if 'mode' in kwargs:
        warnings.warn("the `mode` keyword argument is ignored and deprecated", FutureWarning)
        kwargs.pop('mode')
    stream = messages.FileStream(path, message_class=cfmessage.CfMessage, errors=grib_errors)
    return Dataset(*build_dataset_components(stream, **kwargs))
989208
def _wavGetInfo(f:Union[IO, str]) -> Tuple[SndInfo, Dict[str, Any]]:
    
    if isinstance(f, (str, bytes)):
        f = open(f, 'rb')
        needsclosing = True
    else:
        needsclosing = False
    fsize, bigendian = _wavReadRiff(f)
    fmt = ">i" if bigendian else "<i"
    while (f.tell() < fsize):
        chunk_id = f.read(4)
        if chunk_id == b'fmt ':
            chunksize, sampfmt, chans, sr, byterate, align, bits = _wavReadFmt(f, bigendian)
        elif chunk_id == b'data':
            datasize = _struct.unpack(fmt, f.read(4))[0]
            nframes = int(datasize / (chans * (bits / 8)))
            break
        else:
            _warnings.warn("chunk not understood: %s" % chunk_id)
            data = f.read(4)
            size = _struct.unpack(fmt, data)[0]
            f.seek(size, 1)
    encoding = _encoding(sampfmt, bits)
    if needsclosing:
        f.close()
    info = SndInfo(sr, nframes, chans, encoding, "wav")
    return info, {'fsize': fsize, 'bigendian': bigendian, 'datasize': datasize}
1196807
def load_context(context, file_path=None):
    """"""
    if not file_path:
        file_path = _get_context_filepath()
    if os.path.exists(file_path):
        with io.open(file_path, encoding='utf-8') as f:
            for line in f:
                execute(line, context)
635964
def __getFileObj(self, f):
        """"""
        if not f:
            raise ShapefileException("No file-like object available.")
        elif hasattr(f, "write"):
            return f
        else:
            pth = os.path.split(f)[0]
            if pth and not os.path.exists(pth):
                os.makedirs(pth)
            return open(f, "wb+")
628156
private Volume[] getVolumes(TestContext context) {
        String[] volumes = StringUtils.commaDelimitedListToStringArray(getParameter("volumes", context));
        Volume[] volumeSpecs = new Volume[volumes.length];

        for (int i = 0; i < volumes.length; i++) {
            volumeSpecs[i] = new Volume(volumes[i]);
        }

        return volumeSpecs;
    }
282529
def get_file_head(file_name):
    """"""

    text = None
    try:
        with open(file_name, 'r', encoding='utf-8') as fh:
            text = fh.read(512000)
    except:
        try:
            with open(file_name, 'r', encoding=sys.getfilesystemencoding()) as fh:
                text = fh.read(512000)  # pragma: nocover
        except:
            log.traceback(logging.DEBUG)
    return text
780598
def get_file_stream_api(self):
        """"""
        if not self._file_stream_api:
            if self._current_run_id is None:
                raise UsageError(
                    'Must have a current run to use file stream API.')
            self._file_stream_api = FileStreamApi(self, self._current_run_id)
        return self._file_stream_api
934777
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static StorageManager getStorageManager(Context context) {
        return (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
    }
144719
def get_file_info(hash, context=None):
    
    if context is None:
        stmt = _get_sql('get-file-info.sql')
        args = dict(hash=hash)
    else:
        stmt = _get_sql('get-file-info-in-context.sql')
        id, version = get_id_n_version(context)
        args = dict(hash=hash, id=id, version=version)

    with db_connect() as db_conn:
        with db_conn.cursor() as cursor:
            cursor.execute(stmt, args)
            try:
                filename, media_type = cursor.fetchone()
            except TypeError:
                raise FileNotFound(hash)
    return filename, media_type
290056
def _filehandler(configurable):
    """"""

    filename = configurable.log_name.replace('.', sep)
    path = join(configurable.log_path, '{0}.log'.format(filename))

    return FileHandler(path, mode='a+')
821052
def make_streams(name, value, boundary, encoding):
    """"""

    filename = None
    mime = None

    # user passed in a special dict.
    if isinstance(value, collections.Mapping) and "name" in value and "value" in value:
        filename = value["name"]
        try:
            mime = value["mime"]
        except KeyError:
            pass
        value = value["value"]

    if not filename:
        filename = getattr(value, "name", None)
        if filename:
            filename = os.path.split(filename)[1]

    mime = mime or "application/octet-stream"

    name, filename, mime = [escape_header(v) for v in (name, filename, mime)]

    stream = BytesIO()
    stream.write("--{}\r\n".format(boundary).encode(encoding))
    if not filename:
        stream.write(
            'Content-Disposition: form-data; name="{}"\r\n'.format(name).encode(
                encoding
            )
        )
    else:
        stream.write(
            'Content-Disposition: form-data; name="{}"; filename="{}"\r\n'.format(
                name, filename
            ).encode(encoding)
        )
        if mime:
            stream.write("Content-Type: {}\r\n".format(mime).encode(encoding))
    stream.write(b"\r\n")

    if hasattr(value, "read"):
        stream.seek(0)
        return stream, value, BytesIO("\r\n".encode(encoding))

    # not a file-like object, encode headers and value in one go
    value = value if isinstance(value, (str, bytes)) else json.dumps(value)
    if isinstance(value, bytes):
        stream.write(value)
    else:
        stream.write(value.encode(encoding))
    stream.write(b"\r\n")
    stream.seek(0)
    return (stream,)
1070424
def save_context(context):
    """"""
    file_path = _get_context_filepath()
    content = format_to_http_prompt(context, excluded_options=EXCLUDED_OPTIONS)
    with io.open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
827161
def get_volume_object_info(self, location):
        
        param = {'location': location}
        data = self._api.get(url=self._URL['object'].format(
            id=self.id), params=param).json()
        return VolumeObject(api=self._api, **data)