Converts bytes expression to number of mebibytes.

    If no unit is specified, ``MiB`` is used.
9247
def parse_memory(s):
    """"""
    if isinstance(s, integer):
        out = s
    elif isinstance(s, float):
        out = math_ceil(s)
    elif isinstance(s, string):
        s = s.replace(' ', '')

        if not s:
            raise context.ValueError("Could not interpret %r as a byte unit" % s)

        if s[0].isdigit():
            for i, c in enumerate(reversed(s)):
                if not c.isalpha():
                    break

            index = len(s) - i
            prefix = s[:index]
            suffix = s[index:]

            try:
                n = float(prefix)
            except ValueError:
                raise context.ValueError("Could not interpret %r as a number" % prefix)
        else:
            n = 1
            suffix = s

        try:
            multiplier = _byte_sizes[suffix.lower()]
        except KeyError:
            raise context.ValueError("Could not interpret %r as a byte unit" % suffix)

        out = math_ceil(n * multiplier / (2 ** 20))
    else:
        raise context.TypeError("memory must be an integer, got %r"
                                % type(s).__name__)

    if out < 0:
        raise context.ValueError("memory must be positive")

    return out
740740
public static int toInt(byte[] bytes ) {
    int result = 0;
    for (int i = 0; i < 4; i++) {
      result = (result << 8) - Byte.MIN_VALUE + (int)bytes[i];
    }

    return result;
  }
757250
def int_bytes(cls, string):
        ''''''
        if string[-1] in ('k', 'm'):
            value = cls.int_0_inf(string[:-1])
            unit = string[-1]
            if unit == 'k':
                value *= 2 ** 10
            else:
                value *= 2 ** 20
            return value
        else:
            return cls.int_0_inf(string)
780524
def parse_bytes(field):
    '''
    
    '''
    if field[-1] in 'bB':
        field = field[:-1]

    try:
        for i, prefix in enumerate('KMGTPEZ'):
            if field.endswith(prefix + 'i'):
                factor = 2 ** (10 * (i + 1))
                return float(field[:-2]) * factor

        return float(field)
    except ValueError:
        return None
916693
def bytes(num=10)
      num = [[2048, num.to_i].min , 0].max
      numbers = []

      response = REXML::Document.new( open("https://www.fourmilab.ch/cgi-bin/Hotbits?fmt=xml&nbytes=#{num}"))
      status = REXML::XPath.first( response, "//status")
      case status.attributes['result'].to_i 
      when 200
       data = REXML::XPath.first( response, "//random-data" ).text.split
       data.each{|byte| numbers << byte.hex}
      when 503
       raise StandardError.new "#{status.text}"
      end

      numbers
    end
462205
def _unpack_from(buf, format_s, count=None, little_endian=True):
    """"""

    if count is not None:
        assert count > 0
        format_s = '%i%s' % (count, format_s)

    if little_endian is True:
        format_s = '<' + format_s
    else:
        format_s = '>' + format_s

    size = struct.calcsize(format_s)
    res = struct.unpack_from(format_s, buf.read(size))

    if count is not None:
        return res
    else:
        return res[0]
1236791
def _internal_convert(inp):
    
    '''
    
    '''

    # Read the "magic number" - 4 bytes.
    try:
        mn = struct.unpack('>BBBB', inp.read(4))
    except struct.error:
        raise FormatError(struct.error)

    # First two bytes are always zero, check it.
    if mn[0] != 0 or mn[1] != 0:
        msg = ("Incorrect first two bytes of the magic number: " +
               "0x{0:02X} 0x{1:02X}".format(mn[0], mn[1]))
        raise FormatError(msg)

    # 3rd byte is the data type code.
    dtype_code = mn[2]
    if dtype_code not in _DATA_TYPES_IDX:
        msg = "Incorrect data type code: 0x{0:02X}".format(dtype_code)
        raise FormatError(msg)

    # 4th byte is the number of dimensions.
    dims = int(mn[3])

    # See possible data types description.
    dtype, dtype_s, el_size = _DATA_TYPES_IDX[dtype_code]

    # 4-byte integer for length of each dimension.
    try:
        dims_sizes = struct.unpack('>' + 'I' * dims, inp.read(4 * dims))
    except struct.error as e:
        raise FormatError('Dims sizes: {0}'.format(e))

    # Full length of data.
    full_length = reduce(operator.mul, dims_sizes, 1)

    # Create a numpy array from the data
    try:
        result_array = numpy.frombuffer(
            inp.read(full_length * el_size),
            dtype=numpy.dtype(dtype)
        ).reshape(dims_sizes)
    except ValueError as e:
        raise FormatError('Error creating numpy array: {0}'.format(e))

    # Check for superfluous data.
    if len(inp.read(1)) > 0:
        raise FormatError('Superfluous data detected.')

    return result_array
991784
def to_unit(value, unit='B'):
    """"""
    byte_array = ['B', 'KB', 'MB', 'GB', 'TB']

    if not isinstance(value, (int, float)):
        value = float(value)

    if unit in byte_array:
        result = value / 1024**byte_array.index(unit)
        return round(result, PRECISION), unit

    return value
525235
def to_unit_memory(number):
    """"""
    kb = 1024

    number /= kb

    if number < 100:
        return '{} Kb'.format(round(number, 2))

    number /= kb
    if number < 300:
        return '{} Mb'.format(round(number, 2))

    number /= kb

    return '{} Gb'.format(round(number, 2))
619797
def bits_to_bytes(bits):
    
    if len(bits) % 8 != 0:
        raise Exception("num bits must be multiple of 8")

    res = ""

    for x in six.moves.range(0, len(bits), 8):
        byte_bits = bits[x:x+8]
        byte_val = int(''.join(map(str, byte_bits)), 2)
        res += chr(byte_val)

    return utils.binary(res)
1145776
def dbus_readBytesFD(self, fd, byte_count):
        
        f = os.fdopen(fd, 'rb')
        result = f.read(byte_count)
        f.close()
        return bytearray(result)
578229
def human_to_bytes(size):
    '''
    
    '''
    sbytes = size[:-1]
    unit = size[-1]
    if sbytes.isdigit():
        sbytes = int(sbytes)
        if unit == 'P':
            sbytes *= 1125899906842624
        elif unit == 'T':
            sbytes *= 1099511627776
        elif unit == 'G':
            sbytes *= 1073741824
        elif unit == 'M':
            sbytes *= 1048576
        else:
            sbytes = 0
    else:
        sbytes = 0
    return sbytes
1300531
def frombytes(self, bytes, offset=0):
        
        for b in bytes:
            self._buf[offset] = b
            offset += 1
712232
def read_bytes(self, num_bytes):
        """"""
        buffer_size = len(self._buffer)
        if buffer_size > num_bytes:
            # The buffer is larger than the requested amount of bytes.
            data, self._buffer = self._buffer[:num_bytes], self._buffer[num_bytes:]
        elif 0 < buffer_size <= num_bytes:
            # This might return less bytes than requested.
            data, self._buffer = self._buffer, bytearray()
        else:
            # Buffer is empty. Try to read `num_bytes` and call `read_bytes()`
            # again. This ensures that at most `num_bytes` are returned.
            self._buffer += self.__read__(num_bytes)
            return self.read_bytes(num_bytes)
        return data
684882
def bytes_from_readable_size(C, size, suffix='B'):
        """"""
        s = re.split("^([0-9\.]+)\s*([%s]?)%s?" % (''.join(C.SIZE_UNITS), suffix), size, flags=re.I)
        bytes, unit = round(float(s[1])), s[2].upper()
        while unit in C.SIZE_UNITS and C.SIZE_UNITS.index(unit) > 0:
            bytes *= 1024
            unit = C.SIZE_UNITS[C.SIZE_UNITS.index(unit) - 1]
        return bytes
597034
def filesize(num_bytes):
    """"""
    for prefix in '-KMGTEPZY':
        if num_bytes < 999.9:
            break
        num_bytes /= 1000.0
    if prefix == '-':
        return '{} B'.format(num_bytes)
    return '{:.3n} {}B'.format(num_bytes, prefix)
1146566
def extractTwos(m):
    """"""
    # the problem can be break down to count how many '0's are there in
    # the end of bin(m). This can be done this way: m & a stretch of '1's
    # which can be represent as (2 ** n) - 1.
    assert m >= 0
    i = 0
    while m & (2 ** i) == 0:
        i += 1
    return i, m >> i