Python Code Examples for convert bytes

49 Python code examples are found related to "convert bytes". These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Project: sal   Author: salopensource   File: 0083_auto_20190215_1009.py    License: Apache License 2.0 6 votes vote down vote up
def convert_drives_to_int_bytes(apps, schema_editor):
    """Convert existing drive numbers from kbytes to bytes.

    This uses the binary system to scale, since that is what was used
    by machine checkin to convert from bytes initially.
    """
    Machine = apps.get_model('server', 'Machine')
    for machine in Machine.objects.all():
        # Django already converted str to int for us, but we cast back
        # to int just to be safe.
        if machine.hd_total:
            machine.hd_total = int(machine.hd_total * 1024.0)

        if machine.hd_space:
            machine.hd_space = int(machine.hd_space * 1024.0)

        machine.save() 
Example 2
Project: pypowervm   Author: powervm   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def convert_bytes_to_gb(bytes_, low_value=.0001, dp=None):
    """Converts an integer of bytes to a decimal representation of gigabytes.

    If the value is too low, will return the 'low_value'.  This is useful
    for converting a small number of bytes (ex. 50) into gigabytes.  Rounding
    may be required.

    :param bytes_: The integer number of bytes.
    :param low_value: The minimum value that should be returned.  (Note: if dp
                      is also specified, the value returned may be rounded up
                      and thus be higher than low_value.)
    :param dp: If specified, the value is rounded up to the specified number of
               decimal places by round_gb_size_up.  (Note: None and zero are
               very different.)
    :returns: The decimal value.
    """
    gb_size = bytes_ / float(units.Gi)
    if gb_size < low_value:
        gb_size = low_value
    if dp is not None:
        gb_size = round_gb_size_up(gb_size, dp=dp)
    return gb_size 
Example 3
Project: stonix   Author: CSD-Public   File: CommandHelper.py    License: GNU General Public License v2.0 6 votes vote down vote up
def convert_bytes_to_string(self, data):
        """

        :param data:
        :return: data
        :rtype: str|list
        """

        self.logdispatcher.log(LogPriority.DEBUG, "Converting any bytes objects into strings...")

        data_type = type(data)

        if data_type is list:
            for e in data:
                if type(e) is bytes:
                    data = [e.decode('utf-8') for e in data]
        elif data_type is bytes:
            data = data.decode('utf-8')
            data = str(data)

        return data 
Example 4
def convert_to_bytes(file_or_bytes, resize=None):
    '''
    Will convert into bytes and optionally resize an image that is a file or a base64 bytes object.
    :param file_or_bytes: either a string filename or a bytes base64 image object
    :type file_or_bytes:  (Union[str, bytes])
    :param resize:  optional new size
    :type resize: (Tuple[int, int] or None)
    :return: (bytes) a byte-string object
    :rtype: (bytes)
    '''
    if isinstance(file_or_bytes, str):
        img = PIL.Image.open(file_or_bytes)
    else:
        img = PIL.Image.open(io.BytesIO(base64.b64decode(file_or_bytes)))

    cur_width, cur_height = img.size
    if resize:
        new_width, new_height = resize
        scale = min(new_height/cur_height, new_width/cur_width)
        img = img.resize((int(cur_width*scale), int(cur_height*scale)), PIL.Image.ANTIALIAS)
    bio = io.BytesIO()
    img.save(bio, format="PNG")
    del img
    return bio.getvalue() 
Example 5
Project: motu-client-python   Author: clstoulouse   File: utils_unit.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def convert_bytes(n):
    """Converts the given bytes into a string with the most appropriate
    unit power.
    
    Note that prefixes like M, G, T are power of 10 (ISO/IEC 80000-13:2008) and
    not power of 2."""        
    if   n >= SI_T:
        return '%.1f TB' % (float(n) / SI_T)
    elif n >= SI_G:
        return '%.1f GB' % (float(n) / SI_G)
    elif n >= SI_M:
        return '%.1f MB' % (float(n) / SI_M)
    elif n >= SI_K:
        return '%.1f kB' % (float(n) / SI_K)
    else:
        return '%d B' % n 
Example 6
Project: JeanGrey   Author: SideChannelMarvels   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def convert_r8faults_bytes(r8faults, ref, encrypt=True):
    """
    Convert a set of outputs glitched on round8 into a set of outputs glitched on round9
    :param r8faults: a list of glitched outputs as bytearrays
    :param ref: the reference output bytearray
    :returns: a list of glitched outputs as bytearrays
    """
    r9faults=[]
    for f8 in r8faults:
        if encrypt:
            r9faults.append(bytearray(ref[ 0: 0]+f8[ 0: 1]+ref[ 1: 7]+f8[ 7: 8]+ref[ 8:10]+f8[10:11]+ref[11:13]+f8[13:14]+ref[14:16]))
            r9faults.append(bytearray(ref[ 0: 1]+f8[ 1: 2]+ref[ 2: 4]+f8[ 4: 5]+ref[ 5:11]+f8[11:12]+ref[12:14]+f8[14:15]+ref[15:16]))
            r9faults.append(bytearray(ref[ 0: 2]+f8[ 2: 3]+ref[ 3: 5]+f8[ 5: 6]+ref[ 6: 8]+f8[ 8: 9]+ref[ 9:15]+f8[15:16]+ref[16:16]))
            r9faults.append(bytearray(ref[ 0: 3]+f8[ 3: 4]+ref[ 4: 6]+f8[ 6: 7]+ref[ 7: 9]+f8[ 9:10]+ref[10:12]+f8[12:13]+ref[13:16]))
        else:
            r9faults.append(bytearray(ref[ 0: 0]+f8[ 0: 1]+ref[ 1: 5]+f8[ 5: 6]+ref[ 6:10]+f8[10:11]+ref[11:15]+f8[15:16]+ref[16:16]))
            r9faults.append(bytearray(ref[ 0: 1]+f8[ 1: 2]+ref[ 2: 6]+f8[ 6: 7]+ref[ 7:11]+f8[11:12]+ref[12:12]+f8[12:13]+ref[13:16]))
            r9faults.append(bytearray(ref[ 0: 2]+f8[ 2: 3]+ref[ 3: 7]+f8[ 7: 8]+ref[ 8: 8]+f8[ 8: 9]+ref[ 9:13]+f8[13:14]+ref[14:16]))
            r9faults.append(bytearray(ref[ 0: 3]+f8[ 3: 4]+ref[ 4: 4]+f8[ 4: 5]+ref[ 5: 9]+f8[ 9:10]+ref[10:14]+f8[14:15]+ref[15:16]))
    return r9faults 
Example 7
Project: IOTA_demo   Author: llSourcell   File: conv.py    License: MIT License 6 votes vote down vote up
def convertBigintToBytes(big):
    bytesArrayTemp = [(abs(big) >> pos * 8) % (1 << 8) for pos in
                      range(48)]

    # big endian and balanced
    bytesArray = list(map(lambda x: (x if x <= 0x7F else x - 0x100),
                     reversed(bytesArrayTemp)))

    if big < 0:
        # 1-compliment
        bytesArray = list(map(lambda x: ~x, bytesArray))

        # add1
        for pos in reversed(range(len(bytesArray))):
            add = (bytesArray[pos] & 0xFF) + 1
            bytesArray[pos] = (add if add <= 0x7F else add - 0x100)
            if bytesArray[pos] != 0:
                break

    return bytesArray 
Example 8
Project: iota.py   Author: iotaledger   File: conv.py    License: MIT License 6 votes vote down vote up
def convertBigIntToBytes(big: int) -> List[int]:
    bytesArrayTemp = [(abs(big) >> pos * 8) % (1 << 8) for pos in
                      range(48)]

    # big endian and balanced
    bytesArray = list(map(
        lambda x: (x if x <= 0x7F else x - 0x100),
        reversed(bytesArrayTemp)
    ))

    if big < 0:
        # 1-compliment
        bytesArray = list(map(lambda x: ~x, bytesArray))

        # add1
        for pos in reversed(range(len(bytesArray))):
            add = (bytesArray[pos] & 0xFF) + 1
            bytesArray[pos] = (add if add <= 0x7F else add - 0x100)
            if bytesArray[pos] != 0:
                break

    return bytesArray 
Example 9
Project: openxenmanager   Author: OpenXenManager   File: window.py    License: GNU General Public License v2.0 6 votes vote down vote up
def convert_bytes(self, bytes):
        # Convert bytes to string
        # http://www.5dollarwhitebox.org/drupal/node/84

        bytes = float(bytes)
        if bytes >= 1099511627776:
            terabytes = bytes / 1099511627776
            size = '%.1fT' % terabytes
        elif bytes >= 1073741824:
            gigabytes = bytes / 1073741824
            size = '%.1fG' % gigabytes
        elif bytes >= 1048576:
            megabytes = bytes / 1048576
            size = '%.1fM' % megabytes
        elif bytes >= 1024:
            kilobytes = bytes / 1024
            size = '%.1fK' % kilobytes
        else:
            size = '%.1fb' % bytes
        return size 
Example 10
Project: iota.py   Author: iotaledger   File: conv.py    License: MIT License 6 votes vote down vote up
def convertBytesToBigInt(ba: List[int]) -> int:
    # copy of array
    bytesArray = list(map(lambda x: x, ba))

    # number sign in MSB
    signum = (1 if bytesArray[0] >= 0 else -1)

    if signum == -1:
        # sub1
        for pos in reversed(range(len(bytesArray))):
            sub = (bytesArray[pos] & 0xFF) - 1
            bytesArray[pos] = (sub if sub <= 0x7F else sub - 0x100)
            if bytesArray[pos] != -1:
                break

        # 1-compliment
        bytesArray = list(map(lambda x: ~x, bytesArray))

    # sum magnitudes and set sign
    return sum((x & 0xFF) << pos * 8 for (pos, x) in
               enumerate(reversed(bytesArray))) * signum 
Example 11
Project: orzdba   Author: cnlubo   File: orzdba.py    License: Apache License 2.0 6 votes vote down vote up
def convertBytes(bytes, lst=None):
    """

    :param bytes:
    :param lst:
    :return:
    """
    if lst is None:
        lst = ['Bytes', 'K', 'M', 'G', 'TB', 'PB', 'EB']
    i = int(math.floor(  # 舍弃小数点,取小
        math.log(bytes, 1024)  # 求对数(对数:若 a**b = N 则 b 叫做以 a 为底 N 的对数)
    ))

    if i >= len(lst):
        i = len(lst) - 1
    return ('%.0f' + lst[i]) % (bytes / math.pow(1024, i)) 
Example 12
Project: pymobiledevice   Author: iOSForensics   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def convert_bytes(bytes):
    bytes = float(bytes)
    if bytes >= 1099511627776:
        terabytes = bytes / 1099511627776
        size = '%.2fT' % terabytes
    elif bytes >= 1073741824:
        gigabytes = bytes / 1073741824
        size = '%.2fG' % gigabytes
    elif bytes >= 1048576:
        megabytes = bytes / 1048576
        size = '%.2fM' % megabytes
    elif bytes >= 1024:
        kilobytes = bytes / 1024
        size = '%.2fK' % kilobytes
    else:
        size = '%.2fb' % bytes
    return size 
Example 13
Project: anchore-engine   Author: anchore   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def convert_bytes_size(size_str):
    """
    Converts a size string to an int. Allows trailing units

    e.g. "10" -> 10, "1kb" -> 1024, "1gb" -> 1024*1024*1024
    :param size_str:
    :return:
    """

    m = BYTES_REGEX.fullmatch(size_str.lower())
    if m:
        number = int(m.group(1))

        if m.group(2) is not None:
            unit = m.group(2)
            conversion = SIZE_UNITS.get(unit)
            if conversion:
                return conversion * number
        return number
    else:
        raise ValueError("Invalid size string: {}".format(size_str)) 
Example 14
Project: upvm   Author: ryran   File: sysvalidator.py    License: Apache License 2.0 6 votes vote down vote up
def convert_size_string_to_bytes(size):
    unit = size[-1:]
    sz = float(size[:-1])
    if unit == 'b':
        return sz
    elif unit == 'K':
        return sz * 1024**1
    elif unit == 'M':
        return sz * 1024**2
    elif unit == 'G':
        return sz * 1024**3
    elif unit == 'T':
        return sz * 1024**4
    elif unit == 'P':
        return sz * 1024**5
    elif unit == 'E':
        return sz * 1024**6
    else:
        print(c.RED("Invalid size specified (use e.g., '256M', '10G')"))
        exit(1) 
Example 15
Project: IOTA_demo   Author: llSourcell   File: conv.py    License: MIT License 6 votes vote down vote up
def convertBytesToBigInt(ba):
    # copy of array
    bytesArray = list(map(lambda x: x, ba))

    # number sign in MSB
    signum = (1 if bytesArray[0] >= 0 else -1)

    if signum == -1:
        # sub1
        for pos in reversed(range(len(bytesArray))):
            sub = (bytesArray[pos] & 0xFF) - 1
            bytesArray[pos] = (sub if sub <= 0x7F else sub - 0x100)
            if bytesArray[pos] != -1:
                break

        # 1-compliment
        bytesArray = list(map(lambda x: ~x, bytesArray))

    # sum magnitudes and set sign
    return sum((x & 0xFF) << pos * 8 for (pos, x) in
               enumerate(reversed(bytesArray))) * signum 
Example 16
Project: psutil   Author: giampaolo   File: procsmem.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_bytes(n):
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return "%sB" % n 
Example 17
Project: BotHub   Author: mkaraniya   File: speedtest.py    License: Apache License 2.0 5 votes vote down vote up
def convert_from_bytes(size):
    power = 2**10
    n = 0
    units = {
        0: "",
        1: "kilobytes",
        2: "megabytes",
        3: "gigabytes",
        4: "terabytes"
    }
    while size > power:
        size /= power
        n += 1
    return f"{round(size, 2)} {units[n]}" 
Example 18
Project: nmos-testing   Author: AMWA-TV   File: GenericTest.py    License: Apache License 2.0 5 votes vote down vote up
def convert_bytes(self, data):
        """Convert bytes which may be contained within a dict or tuple into strings"""
        if isinstance(data, bytes):
            return data.decode('ascii')
        if isinstance(data, dict):
            return dict(map(self.convert_bytes, data.items()))
        if isinstance(data, tuple):
            return map(self.convert_bytes, data)
        return data 
Example 19
Project: rasa-for-botfront   Author: botfront   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def convert_bytes_to_string(data: Union[bytes, bytearray, Text]) -> Text:
    """Convert `data` to string if it is a bytes-like object."""

    if isinstance(data, (bytes, bytearray)):
        return data.decode(io_utils.DEFAULT_ENCODING)

    return data 
Example 20
Project: pfp   Author: d0c-s4vage   File: compat_io.py    License: MIT License 5 votes vote down vote up
def ConvertBytesToFloat(params, ctxt, scope, stream, coord):
    raise NotImplementedError()


# hfloat ConvertBytesToHFloat( uchar byteArray[] ) 
Example 21
Project: RSqueak   Author: hpi-swa   File: variable.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_to_bytes_layout(self, wordsize):
        words = self.words
        new_words = [r_uint(0)] * len(words * wordsize)
        for i, word in enumerate(words):
            new_words[i * 4 + 0] = r_uint((word >> 0) & 0xff)
            new_words[i * 4 + 1] = r_uint((word >> 8) & 0xff)
            new_words[i * 4 + 2] = r_uint((word >> 16) & 0xff)
            new_words[i * 4 + 3] = r_uint((word >> 24) & 0xff)
        self.words = new_words
        return self 
Example 22
Project: openxenmanager   Author: OpenXenManager   File: window.py    License: GNU General Public License v2.0 5 votes vote down vote up
def convert_bytes_mb(self, n):
        # Convert bytes to mb string

        n = float(n)
        K, M = 1 << 10, 1 << 20
        if n >= M:
            return '%d' % (float(n) / M)
        elif n >= K:
            return '%d' % (float(n) / K)
        else:
            return '%d' % n 
Example 23
Project: cyipopt   Author: matthias-k   File: ipopt_wrapper.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def convert_to_bytes(options):
    if sys.version_info >= (3, 0):
        for key in list(options.keys()):
            try:
                if bytes(key, 'utf-8') != key:
                    options[bytes(key, 'utf-8')] = options[key]
                    options.pop(key)
            except TypeError:
                pass 
Example 24
Project: P2P-music-sharing   Author: Ezi0aaudit0re   File: fileIO.py    License: MIT License 5 votes vote down vote up
def convert_to_bytes(file_path=path_to_file):
    read_data = None
    with open(file_path, 'r') as file:
        read_data = file.read()
    return read_data.encode("utf-8") 
Example 25
Project: thepiratebay   Author: appi147   File: app.py    License: MIT License 5 votes vote down vote up
def convert_to_bytes(size_str):
    '''
    Converts torrent sizes to a common count in bytes.
    '''
    size_data = size_str.split()

    multipliers = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']

    size_magnitude = float(size_data[0])
    multiplier_exp = multipliers.index(size_data[1])
    size_multiplier = 1024 ** multiplier_exp if multiplier_exp > 0 else 1

    return size_magnitude * size_multiplier 
Example 26
Project: pfp   Author: d0c-s4vage   File: compat_io.py    License: MIT License 5 votes vote down vote up
def ConvertBytesToDouble(params, ctxt, scope, stream, coord):
    raise NotImplementedError()


# float ConvertBytesToFloat( uchar byteArray[] ) 
Example 27
Project: evalai-cli   Author: Cloud-CV   File: submissions.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_bytes_to(byte, to, bsize=1024):
    """
    Convert bytes to KB, MB, GB etc.
    Arguments:
        bytes {int} -- The bytes which are to be converted
        to {str} -- To which unit it is to be converted
    """
    units_mapping = {"kb": 1, "mb": 2, "gb": 3, "tb": 4, "pb": 5, "eb": 6}
    unit = byte
    for value in range(units_mapping[to]):
        unit = int(unit / bsize)

    return unit 
Example 28
Project: dexplo   Author: dexplo   File: _utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_bytes_or_unicode(arr: ndarray) -> ndarray:
    if arr.dtype.kind == 'S':
        arr = arr.astype('U').astype('O')
    elif arr.dtype.kind == 'U':
        arr = arr.astype('O')
    return arr 
Example 29
Project: TeleTor   Author: iRay   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def convert_bytes(num):
    step_unit = 1000.0

    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < step_unit:
            return "%3.1f %s" % (num, x)
        num /= step_unit 
Example 30
Project: pinax-documents   Author: pinax   File: utils.py    License: MIT License 5 votes vote down vote up
def convert_bytes(bytes):
    bytes = float(bytes)
    if bytes >= 1099511627776:
        size, srepr = bytes / 1099511627776, "TB"
    elif bytes >= 1073741824:
        size, srepr = bytes / 1073741824, "GB"
    elif bytes >= 1048576:
        size, srepr = bytes / 1048576, "MB"
    elif bytes >= 1024:
        size, srepr = bytes / 1024, "KB"
    else:
        size, srepr = bytes, " bytes"
    return "%d%s" % (math.ceil(size), srepr) 
Example 31
Project: mmtf-python   Author: rcsb   File: converters.py    License: Apache License 2.0 5 votes vote down vote up
def convert_ints_to_bytes(in_ints, num):
    """Convert an integer array into a byte arrays. The number of bytes forming an integer
    is defined by num

    :param in_ints: the input integers
    :param num: the number of bytes per int
    :return the integer array"""
    out_bytes= b""
    for val in in_ints:
        out_bytes+=struct.pack(mmtf.utils.constants.NUM_DICT[num], val)
    return out_bytes 
Example 32
Project: dnxfirewall-cmd   Author: DOWRIGHTTV   File: dnx_protocol_tools.py    License: GNU General Public License v3.0 5 votes vote down vote up
def convert_dns_string_to_bytes(domain_name):
    if (not domain_name):
        return b'\x00'

    split_domain = domain_name.split('.')
    domain_bytes = []
    for part in split_domain:
        domain_bytes.append(byte_pack(len(part)))
        domain_bytes.append(part.encode('utf-8'))
    else:
        domain_bytes.append(b'\x00')

    return b''.join(domain_bytes)

# will create dns header specific to response. default resource record count is 1 
Example 33
Project: Katastrophe   Author: alyakhtar   File: bittorrent.py    License: MIT License 5 votes vote down vote up
def convertBytesToDecimal(headerBytes, power):
    size = 0
    for ch in headerBytes:
        size += int(ord(ch))*256**power
        power -= 1
    return size 
Example 34
Project: Cacher   Author: erikng   File: cacher.py    License: Apache License 2.0 5 votes vote down vote up
def convert_bytes_to_human_readable(number_of_bytes):
    if number_of_bytes < 0:
        raise ValueError("ERROR: number of bytes can not be less than 0")

    step_to_greater_unit = 1024.
    number_of_bytes = float(number_of_bytes)
    unit = 'bytes'
    if (number_of_bytes / step_to_greater_unit) >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'KB'

    if (number_of_bytes / step_to_greater_unit) >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'MB'

    if (number_of_bytes / step_to_greater_unit) >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'GB'

    if (number_of_bytes / step_to_greater_unit) >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'TB'

    precision = 1
    number_of_bytes = round(number_of_bytes, precision)
    return str(number_of_bytes) + ' ' + unit 
Example 35
Project: mmtf-python   Author: rcsb   File: converters.py    License: Apache License 2.0 5 votes vote down vote up
def convert_bytes_to_ints(in_bytes, num):
    """Convert a byte array into an integer array. The number of bytes forming an integer
    is defined by num
    :param in_bytes: the input bytes
    :param num: the number of bytes per int
    :return the integer array"""
    out_arr = []
    for i in range(len(in_bytes)//num):
        val = in_bytes[i * num:i * num + num]
        unpacked = struct.unpack(mmtf.utils.constants.NUM_DICT[num], val)
        out_arr.append(unpacked[0])
    return out_arr 
Example 36
Project: mcsema   Author: lifting-bits   File: exception.py    License: Apache License 2.0 5 votes vote down vote up
def convert_to_bytes(value):
  is64 = get_address_size_in_bytes() == 8
  if is64:
    sv = struct.pack("<Q", value)
  else:
    sv = struct.pack("<I", value)
  return " ".join("%02X" % ord(c) for c in sv) 
Example 37
Project: meerk40t   Author: meerk40t   File: CH341DriverBase.py    License: MIT License 5 votes vote down vote up
def convert_to_list_bytes(data):
    if isinstance(data, str):  # python 2
        return [ord(e) for e in data]
    else:
        return [e for e in data] 
Example 38
Project: yosai   Author: YosaiProject   File: mgt.py    License: Apache License 2.0 5 votes vote down vote up
def convert_bytes_to_identifiers(self, encrypted, subject_context):
        """
        If a cipher_service is available, it will be used to first decrypt the
        serialized message.  Then, the bytes are deserialized and returned.

        :param serialized:      the bytes to decrypt and then deserialize
        :param subject_context: the contextual data, that is being
                                used to construct a Subject instance
        :returns: the de-serialized identifier
        """

        # unlike Shiro, Yosai assumes that the message is encrypted:
        decrypted = self.decrypt(encrypted)

        return self.serialization_manager.deserialize(decrypted) 
Example 39
Project: pymacaroons   Author: ecordell   File: utils.py    License: MIT License 5 votes vote down vote up
def convert_to_bytes(string_or_bytes):
    if string_or_bytes is None:
        return None
    if isinstance(string_or_bytes, text_type):
        return string_or_bytes.encode('utf-8')
    elif isinstance(string_or_bytes, binary_type):
        return string_or_bytes
    else:
        raise TypeError("Must be a string or bytes object.") 
Example 40
Project: maas   Author: maas   File: __init__.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def convert_size_to_bytes(value):
    """
    Converts storage size values with units (GiB, TiB...) to bytes.

    :param value: A string containing a number and unit separated by at least
        one space character.  If unit is not specified, defaults to bytes.
    :return: An integer indicating the number of bytes for the given value in
        any other size unit.
    :raises UnknownCapacityUnitError: unsupported capacity unit.
    """
    # Split value on the first space.
    capacity_def = value.split(" ", 1)
    if len(capacity_def) == 1:
        # No unit specified, default to bytes.
        return int(capacity_def[0])

    capacity_value, capacity_unit = capacity_def
    capacity_value = float(capacity_value)
    capacity_unit = capacity_unit.strip()
    if capacity_unit in CAPACITY_UNITS:
        multiplier = CAPACITY_UNITS[capacity_unit]
    else:
        raise UnknownCapacityUnitError(
            "Unknown capacity unit '%s'" % capacity_unit
        )
    # Convert value to bytes.
    return int(capacity_value * multiplier)


# Architectures as defined by:
# https://github.com/lxc/lxd/blob/master/shared/osarch/architectures.go
# https://www.debian.org/releases/oldstable/i386/ch02s01.html.en 
Example 41
Project: yosai   Author: YosaiProject   File: mgt.py    License: Apache License 2.0 5 votes vote down vote up
def convert_identifiers_to_bytes(self, identifiers):
        """
        Encryption requires a binary type as input, so this method converts
        the identifier collection object to one.

        :type identifiers: a serializable IdentifierCollection object
        :returns: a bytestring
        """

        # serializes to bytes by default:
        return self.encrypt(self.serialization_manager.serialize(identifiers)) 
Example 42
Project: X-tra-Telegram   Author: Dark-Princ3   File: speedtest.py    License: Apache License 2.0 5 votes vote down vote up
def convert_from_bytes(size):
    power = 2**10
    n = 0
    units = {
        0: "",
        1: "kilobytes",
        2: "megabytes",
        3: "gigabytes",
        4: "terabytes"
    }
    while size > power:
        size /= power
        n += 1
    return f"{round(size, 2)} {units[n]}" 
Example 43
Project: heralding   Author: johnnykv   File: telnetsrvlib.py    License: GNU General Public License v3.0 5 votes vote down vote up
def convert_to_bytes(c):
  if isinstance(c, int):
    if c < 256:
      cb = bytes([c])
    else:
      cb = None
  elif isinstance(c, str):
    cb = bytes(c, 'utf-8')
  else:
    cb = c
  return cb


# vim: set syntax=python ai showmatch: 
Example 44
Project: pfp   Author: d0c-s4vage   File: compat_io.py    License: MIT License 5 votes vote down vote up
def ConvertDataToBytes(params, ctxt, scope, stream, coord):
    raise NotImplementedError()


# void DeleteBytes( int64 start, int64 size ) 
Example 45
Project: Sinopac-Order-API   Author: ypochien   File: pyT4.py    License: MIT License 5 votes vote down vote up
def convert_future_bytes_to_dict(future_order_res_bytes):
    future_record_field = 'trade_type,account,market_id,code_id,f_callput,ord_bs,ord_price,price_type,ord_qty,' \
                          'ord_no,ord_seq,ord_type,oct_type,f_mttype,f_composit,c_futopt,c_code,c_callput,' \
                          'c_buysell,c_price,c_quantity,ord_date,preord_date,ord_time,type,err_code,msg'
    FutureOrderRecord = namedtuple('FutureOrderRecord', future_record_field)
    future_order_res_format = '2s15s1s10s1s1s12s3s4s6s6s3s1s1s2s1s10s1s1s12s4s8s8s6s1s4s60s'
    if len(future_order_res_bytes) != struct.calcsize(future_order_res_format):
        return future_order_res_bytes
    future_order_res = FutureOrderRecord._make(struct.unpack_from(future_order_res_format, future_order_res_bytes))
    future_order_res_lst = [str(item, 'cp950') for item in future_order_res]
    return FutureOrderRecord(*future_order_res_lst)._asdict() 
Example 46
Project: Sinopac-Order-API   Author: ypochien   File: pyT4.py    License: MIT License 5 votes vote down vote up
def convert_stock_bytes_to_dict(stock_order_res_bytes):
    """委託回報為bytes。所以先轉為有結構的NameTuple,但每個item得從bytes to utf8"""
    stock_record_field = 'trade_type,account,code_id,ord_price,ord_qty,ord_seq,ord_date,effective_date,' \
                         'ord_time,ord_no,ord_soruce,org_ord_seq,ord_bs,ord_type,market_id,price_type,ord_status,Msg'
    StockOrderRecord = namedtuple('StockOrderRecord', stock_record_field)
    stock_order_res_format = '2s15s6s6s3s6s8s8s6s5s3s6s1s2s1s1s2s60s'
    if len(stock_order_res_bytes) != struct.calcsize(stock_order_res_format):
        return stock_order_res_bytes
    stock_order_res = StockOrderRecord._make(struct.unpack_from(stock_order_res_format, stock_order_res_bytes))
    stock_order_res_lst = [str(item, 'cp950') for item in stock_order_res]
    return StockOrderRecord(*stock_order_res_lst)._asdict() 
Example 47
Project: ctSESAM-python   Author: pinae   File: ctSESAM.py    License: GNU General Public License v3.0 5 votes vote down vote up
def convert_bytes_to_password(hashed_bytes, length):
    number = int.from_bytes(hashed_bytes, byteorder='big')
    password = ''
    while number > 0 and len(password) < length:
        password = password + password_characters[number % len(password_characters)]
        number = number // len(password_characters)
    return password 
Example 48
Project: django-gateone   Author: jimmy201602   File: utils.py    License: GNU General Public License v3.0 4 votes vote down vote up
def convert_to_bytes(size_val):
    """
    Given a *size_val* (string) such as '100M', returns an integer representing
    an equivalent amount of bytes.  Accepts the following '<num><char>' formats:

    =========== ==========  ==================================
    Character   Meaning     Example
    =========== ==========  ==================================
    B (or none) Bytes       '100' or '100b' -> 100
    K           Kilobytes   '1k' -> 1024
    M           Megabytes   '1m' -> 1048576
    G           Gigabytes   '1g' -> 1073741824
    T           Terabytes   '1t' -> 1099511627776
    P           Petabytes   '1p' -> 1125899906842624
    E           Exabytes    '1e' -> 1152921504606846976
    Z           Zettabytes  '1z' -> 1180591620717411303424L
    Y           Yottabytes  '7y' -> 1208925819614629174706176L
    =========== ==========  ==================================

    .. note::

        If no character is given the *size_val* will be assumed to be in bytes.

    .. tip::

        All characters will be converted to upper case before conversion
        (case-insensitive).

    Examples::

        >>> convert_to_bytes('2M')
        2097152
        >>> convert_to_bytes('2g')
        2147483648
    """
    symbols = "BKMGTPEZY"
    letter = size_val[-1:].strip().upper()
    if letter.isdigit(): # Assume bytes
        letter = 'B'
        num = size_val
    else:
        num = size_val[:-1]
    assert num.isdigit() and letter in symbols
    num = float(num)
    prefix = {symbols[0]:1}
    for i, size_val in enumerate(symbols[1:]):
        prefix[size_val] = 1 << (i+1)*10
    return int(num * prefix[letter]) 
Example 49
Project: pdf2image   Author: Belval   File: pdf2image.py    License: MIT License 4 votes vote down vote up
def convert_from_bytes(
    pdf_file,
    dpi=200,
    output_folder=None,
    first_page=None,
    last_page=None,
    fmt="ppm",
    jpegopt=None,
    thread_count=1,
    userpw=None,
    use_cropbox=False,
    strict=False,
    transparent=False,
    single_file=False,
    output_file=uuid_generator(),
    poppler_path=None,
    grayscale=False,
    size=None,
    paths_only=False,
    use_pdftocairo=False,
):
    """
        Description: Convert PDF to Image will throw whenever one of the condition is reached
        Parameters:
            pdf_file -> Bytes representing the PDF file
            dpi -> Image quality in DPI
            output_folder -> Write the resulting images to a folder (instead of directly in memory)
            first_page -> First page to process
            last_page -> Last page to process before stopping
            fmt -> Output image format
            jpegopt -> jpeg options `quality`, `progressive`, and `optimize` (only for jpeg format)
            thread_count -> How many threads we are allowed to spawn for processing
            userpw -> PDF's password
            use_cropbox -> Use cropbox instead of mediabox
            strict -> When a Syntax Error is thrown, it will be raised as an Exception
            transparent -> Output with a transparent background instead of a white one.
            single_file -> Uses the -singlefile option from pdftoppm/pdftocairo
            output_file -> What is the output filename or generator
            poppler_path -> Path to look for poppler binaries
            grayscale -> Output grayscale image(s)
            size -> Size of the resulting image(s), uses the Pillow (width, height) standard
            paths_only -> Don't load image(s), return paths instead (requires output_folder)
            use_pdftocairo -> Use pdftocairo instead of pdftoppm, may help performance
    """

    fh, temp_filename = tempfile.mkstemp()
    try:
        with open(temp_filename, "wb") as f:
            f.write(pdf_file)
            f.flush()
            return convert_from_path(
                f.name,
                dpi=dpi,
                output_folder=output_folder,
                first_page=first_page,
                last_page=last_page,
                fmt=fmt,
                jpegopt=jpegopt,
                thread_count=thread_count,
                userpw=userpw,
                use_cropbox=use_cropbox,
                strict=strict,
                transparent=transparent,
                single_file=single_file,
                output_file=output_file,
                poppler_path=poppler_path,
                grayscale=grayscale,
                size=size,
                paths_only=paths_only,
                use_pdftocairo=use_pdftocairo,
            )
    finally:
        os.close(fh)
        os.remove(temp_filename)