Python struct.error() Examples

The following are 40 code examples for showing how to use struct.error(). 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.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module struct , or try the search function .

Example 1
Project: macops   Author: google   File: systemconfig.py    License: Apache License 2.0 6 votes vote down vote up
def _GetMACFromData(data):
  """Unpacks and formats MAC address data.

  Args:
    data: buffer, usually an NSCFData object
  Returns:
    string containing the MAC address
  Raises:
    InterfaceError: if data can't be unpacked
  """
  try:
    unpacked = struct.unpack_from('BBBBBB', data)
  except struct.error as e:
    logging.error('Could not unpack MAC address data: %s', e)
    raise InterfaceError(e)
  return ':'.join(['{:02x}'.format(i) for i in unpacked]) 
Example 2
Project: pywren-ibm-cloud   Author: pywren   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def readline(self):
        if self.eof:
            raise EOFError()

        if not self.first_byte and self.plusbytes != 0:
            self.first_byte = self.sb.read(self.plusbytes)
            if self.first_byte != b'\n':
                logger.debug('Discarding first partial row')
                self.sb._raw_stream.readline()
        try:
            retval = self.sb._raw_stream.readline()
        except struct.error:
            raise EOFError()
        self.pos += len(retval)

        if self.pos >= self.size:
            self.eof = True

        return retval 
Example 3
Project: lifx-python   Author: sharph   File: network.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def recvpacket(timeout = None):
    global connection
    if connection is None:
        connect()
    #connection.settimeout(timeout)
    #try:
    #    lengthdatum, addr = connection.recvfrom(2)
    #except socket.timeout:
    #    return None
    #connection.settimeout(None)
    #try:
    #    (length, ) = struct.unpack('<H', lengthdatum)
    #except struct.error:
    #    connect()
    #    return None
    #data, addr = connection.recvfrom(length - 2)
    try:
        data, addr = connection.recvfrom(1024)
    except socket.timeout:
        return None
    packet = packetcodec.decode_packet(data)
    if debug:
        print('recvpacket(): ', packet)
    return packet 
Example 4
Project: jawfish   Author: war-and-code   File: platform.py    License: MIT License 6 votes vote down vote up
def _syscmd_uname(option,default=''):

    """ Interface to the system's uname command.
    """
    if sys.platform in ('dos','win32','win16','os2'):
        # XXX Others too ?
        return default
    try:
        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
    except (AttributeError,os.error):
        return default
    output = f.read().strip()
    rc = f.close()
    if not output or rc:
        return default
    else:
        return output 
Example 5
Project: trelby   Author: trelby   File: truetype.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, s):
        # is this a valid font
        self.ok = False

        # parse functions for tables, and a flag for whether each has been
        # parsed successfully
        self.parseFuncs = {
            "head" : [self.parseHead, False],
            "name" : [self.parseName, False],
            "OS/2" : [self.parseOS2, False]
            }

        try:
            self.parse(s)
        except (struct.error, ParseError), e:
            self.error = e

            return 
Example 6
Project: Telethon   Author: LonamiWebs   File: utils.py    License: MIT License 6 votes vote down vote up
def resolve_inline_message_id(inline_msg_id):
    """
    Resolves an inline message ID. Returns a tuple of
    ``(message id, peer, dc id, access hash)``

    The ``peer`` may either be a :tl:`PeerUser` referencing
    the user who sent the message via the bot in a private
    conversation or small group chat, or a :tl:`PeerChannel`
    if the message was sent in a channel.

    The ``access_hash`` does not have any use yet.
    """
    try:
        dc_id, message_id, pid, access_hash = \
            struct.unpack('<iiiq', _decode_telegram_base64(inline_msg_id))
        peer = types.PeerChannel(-pid) if pid < 0 else types.PeerUser(pid)
        return message_id, peer, dc_id, access_hash
    except (struct.error, TypeError):
        return None, None, None, None 
Example 7
Project: py   Author: pytest-dev   File: test_terminalwriter.py    License: MIT License 6 votes vote down vote up
def test_getdimensions(monkeypatch):
    if sys.version_info >= (3, 3):
        import shutil
        Size = namedtuple('Size', 'lines columns')
        monkeypatch.setattr(shutil, 'get_terminal_size', lambda: Size(60, 100))
        assert terminalwriter._getdimensions() == (60, 100)
    else:
        fcntl = py.test.importorskip("fcntl")
        import struct
        l = []
        monkeypatch.setattr(fcntl, 'ioctl', lambda *args: l.append(args))
        try:
            terminalwriter._getdimensions()
        except (TypeError, struct.error):
            pass
        assert len(l) == 1
        assert l[0][0] == 1 
Example 8
Project: droidlysis   Author: cryptax   File: droidziprar.py    License: MIT License 6 votes vote down vote up
def open(self, filename):
        try:
            if self.zipmode:
                if self.verbose:
                    print( "Opening Zip archive "+filename)
                self.handle = zipfile.ZipFile(filename, 'r')
            else:
                if self.verbose:
                    print( "Opening Rar archive "+filename)
                self.handle = rarfile.RarFile(filename, 'r')

        except (struct.error, zipfile.BadZipfile, zipfile.LargeZipFile, IOError) as e:
            if self.verbose:
                print( "Exception caught in ZipFile: %s" % (repr(e)))
            self.handle = None

        return self.handle 
Example 9
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 6 votes vote down vote up
def __ubx_NAV_POSLLH(self, dev):
        payload = dev.read(size=30)
        payload_cpy = payload

        if self.__validate_checksum(1, 2, payload, dev):
            try:
                payload_cpy = payload_cpy[2:]
                # Remove padding (=) introduced by struct for processor optimization
                self.iTOW, self.lon, self.lat, self.height, self.hMSL, self.hAcc, self.vAcc = struct.unpack('=LllllLL', payload_cpy)
                self.ubx_class = '01'
                self.ubx_id = '02'

            except struct.error:
                print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))



    # time_of_week in ms / Dilution of Precision
    # DOP is Dimensionless / scaled by factor 100
    # Geometric / Position / Time / Vertical / Horizontal / Northing / Easting 
Example 10
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 6 votes vote down vote up
def __ubx_NAV_DOP(self, dev):
        payload = dev.read(size=20)
        payload_cpy = payload

        if self.__validate_checksum(1, 4, payload, dev):
            try:
                payload_cpy = payload_cpy[2:]
                self.iTOW, self.gDOP, self.pDOP, self.tDOP, self.vDOP, self.hDOP, self.nDOP, self.eDOP = struct.unpack('=L7H', payload_cpy)
                self.ubx_class = '01'
                self.ubx_id = '04'

            except struct.error:
                print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))


    # Time_of_week in ms / Fractional time_of_week ns / Week number
    # GPS Fix (6 valid types depending on status) / Fix status flags (4 types)
    # ECEF X cm / ECEF Y cm / ECEF Z cm / Position Accuracy cm
    # ECEF-Velocity X cm/s / ECEF-Velocity Y cm/s / ECEF-Velocity Z cm/s
    # Speed Accuracy cm/s / Position DOP (scale 0.01)
    # reserved / number of SV's used / reserved 
Example 11
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 6 votes vote down vote up
def __ubx_NAV_PVT(self, dev):
        payload = dev.read(size=94)
        payload_cpy = payload

        if(self.__validate_checksum(1, 7, payload, dev)):
            try:
                payload_cpy = payload[2:]
                self.iTOW, self.year, self.month, self.day, self.hour, self.minute, self.second, self.valid, self.tAcc, self.nano, self.fixType, self.flags, self.flags2, self.numSV, self.lon, self.lat, self.height, self.hMSL, self.hAcc, self.vAcc, self.velN, self.velE, self.velD, self.gSpeed, self.headMot, self.sAcc, self.headAcc, self.pDOP, reserved11, reserved12, reserved13, reserved14, reserved15, reserved16,  self.headVeh, self.magDec, self.magAcc = struct.unpack('=LH5BBLlB2BB4l2L5lLLH6BlhH', payload_cpy)

                self.ubx_class = '01'
                self.ubx_id = '07'
            except struct.error:
                print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))


    ## UBX-ACK 0x05 ##

    # UBX-ACK-ACK (0x05 0x01) 
Example 12
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 6 votes vote down vote up
def __ubx_ACK_ACK(self, dev):
        payload = dev.read(size=4)
        payload_cpy = payload

        if(self.__validate_checksum(5, 1, payload, dev)):
            try:
                payload_cpy = payload_cpy[2:]
                self.clsID, self.msgID = struct.unpack('=BB', payload_cpy)
                self.clsID, self.msgID = hex(self.clsID), hex(self.msgID)
                self.ubx_class = '05'
                self.ubx_id = '01'

            except struct.error:
                print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))


    # UBX-ACK-NAK (0x05 0x00) 
Example 13
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 6 votes vote down vote up
def __ubx_CFG_PRT(self, rate):
        header, ubx_class, ubx_id, length, uart_port = 46434, 6, 0, 20, 1

        rate = hex(rate)
        rate = rate[2:]
        while(len(rate) < 8):
            rate = '0' + rate

        rate1, rate2, rate3, rate4 = int(rate[-2:], 16), int(rate[-4:-2], 16), int(rate[2:4], 16), int(rate[:2], 16)

        payload = [length, 0, uart_port, 0, 0, 0, 208, 8, 0, 0, rate1, rate2, rate3, rate4, 7, 0, 3, 0, 0, 0, 0, 0]
        checksum = self.__calc_checksum(ubx_class, ubx_id, payload)
        payload = payload + checksum
        try:
            self.msg = struct.pack('>H26B', header, ubx_class, ubx_id, *payload)
            self.ubx_class = '06'
            self.ubx_id = '00'
        except struct.error:
            print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))


    # UBX-CFG-MSG (0x06 0x01) 
Example 14
Project: recruit   Author: Frank-qlu   File: ipaddress.py    License: Apache License 2.0 6 votes vote down vote up
def v4_int_to_packed(address):
    """Represent an address as 4 packed bytes in network (big-endian) order.

    Args:
        address: An integer representation of an IPv4 IP address.

    Returns:
        The integer address packed as 4 bytes in network (big-endian) order.

    Raises:
        ValueError: If the integer is negative or too large to be an
          IPv4 IP address.

    """
    try:
        return _compat_to_bytes(address, 4, 'big')
    except (struct.error, OverflowError):
        raise ValueError("Address negative or too large for IPv4") 
Example 15
Project: python-mysql-pool   Author: LuciferJack   File: protocol.py    License: MIT License 6 votes vote down vote up
def parse_column(self, packet, charset='utf-8'):
        """Parse a MySQL column-packet"""
        (packet, _) = utils.read_lc_string(packet[4:])  # catalog
        (packet, _) = utils.read_lc_string(packet)  # db
        (packet, _) = utils.read_lc_string(packet)  # table
        (packet, _) = utils.read_lc_string(packet)  # org_table
        (packet, name) = utils.read_lc_string(packet)  # name
        (packet, _) = utils.read_lc_string(packet)  # org_name

        try:
            (_, _, field_type,
             flags, _) = struct_unpack('<xHIBHBxx', packet)
        except struct.error:
            raise errors.InterfaceError("Failed parsing column information")

        return (
            name.decode(charset),
            field_type,
            None,  # display_size
            None,  # internal_size
            None,  # precision
            None,  # scale
            ~flags & FieldFlag.NOT_NULL,  # null_ok
            flags,  # MySQL specific
        ) 
Example 16
Project: python-mysql-pool   Author: LuciferJack   File: protocol.py    License: MIT License 6 votes vote down vote up
def parse_eof(self, packet):
        """Parse a MySQL EOF-packet"""
        if packet[4] == 0:
            # EOF packet deprecation
            return self.parse_ok(packet)

        err_msg = "Failed parsing EOF packet."
        res = {}
        try:
            unpacked = struct_unpack('<xxxBBHH', packet)
        except struct.error:
            raise errors.InterfaceError(err_msg)

        if not (unpacked[1] == 254 and len(packet) <= 9):
            raise errors.InterfaceError(err_msg)

        res['warning_count'] = unpacked[2]
        res['status_flag'] = unpacked[3]
        return res 
Example 17
Project: segpy   Author: sixty-north   File: packer.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def unpack(self, buffer):
        """Unpack a header into a header object.

        Overwrites any existing header field values with new values
        obtained from the buffer.

        Returns:
            The header object.
        """
        try:
            values = self._structure.unpack(buffer)
        except struct.error as e:
                raise ValueError("Buffer of length {} too short"
                                 .format(len(buffer),
                                         str(e).capitalize())) from e
        else:
            return self._unpack(values) 
Example 18
Project: jbox   Author: jpush   File: ipaddress.py    License: MIT License 6 votes vote down vote up
def v4_int_to_packed(address):
    """Represent an address as 4 packed bytes in network (big-endian) order.

    Args:
        address: An integer representation of an IPv4 IP address.

    Returns:
        The integer address packed as 4 bytes in network (big-endian) order.

    Raises:
        ValueError: If the integer is negative or too large to be an
          IPv4 IP address.

    """
    try:
        return _compat_to_bytes(address, 4, 'big')
    except (struct.error, OverflowError):
        raise ValueError("Address negative or too large for IPv4") 
Example 19
Project: jbox   Author: jpush   File: ipaddress.py    License: MIT License 6 votes vote down vote up
def _parse_hextet(cls, hextet_str):
        """Convert an IPv6 hextet string into an integer.

        Args:
            hextet_str: A string, the number to parse.

        Returns:
            The hextet as an integer.

        Raises:
            ValueError: if the input isn't strictly a hex number from
              [0..FFFF].

        """
        # Whitelist the characters, since int() allows a lot of bizarre stuff.
        if not cls._HEX_DIGITS.issuperset(hextet_str):
            raise ValueError("Only hex digits permitted in %r" % hextet_str)
        # We do the length check second, since the invalid character error
        # is likely to be more informative for the user
        if len(hextet_str) > 4:
            msg = "At most 4 characters permitted in %r"
            raise ValueError(msg % hextet_str)
        # Length check means we can skip checking the integer value
        return int(hextet_str, 16) 
Example 20
Project: pycomm3   Author: ottowayi   File: clx_legacy.py    License: MIT License 6 votes vote down vote up
def read_tag(self, *tags):
        """ read tag from a connected plc

        Possible combination can be passed to this method:
                - ('Counts') a single tag name
                - (['ControlWord']) a list with one tag or many
                - (['parts', 'ControlWord', 'Counts'])

        At the moment there is not a strong validation for the argument passed. The user should verify
        the correctness of the format passed.

        :return: None is returned in case of error otherwise the tag list is returned
        """

        if not self._forward_open():
            self.__log.warning("Target did not connected. read_tag will not be executed.")
            raise DataError("Target did not connected. read_tag will not be executed.")

        if len(tags) == 1:
            if isinstance(tags[0], (list, tuple, GeneratorType)):
                return self._read_tag_multi(tags[0])
            else:
                return self._read_tag_single(tags[0])
        else:
            return self._read_tag_multi(tags) 
Example 21
Project: pycomm3   Author: ottowayi   File: clx_legacy.py    License: MIT License 6 votes vote down vote up
def _parse_multiple_request_write(tags, reply):
        """ parse the message received from a multi request writ:

        For each tag parsed, the information extracted includes the tag name and the status of the writing.
        Those information are appended to the tag list as tuple

        :return: the tag list
        """
        offset = 50
        position = 50

        try:
            number_of_service_replies = unpack_uint(reply[offset:offset + 2])
            tag_list = []
            for index in range(number_of_service_replies):
                position += 2
                start = offset + unpack_uint(reply[position:position + 2])
                general_status = unpack_usint(reply[start + 2:start + 3])
                error = None if general_status == SUCCESS else get_service_status(general_status)
                tag_list.append(Tag(*tags[index], error))
            return tag_list
        except Exception as e:
            raise DataError(e) 
Example 22
Project: spotlight_parser   Author: ydkhatri   File: spotlight_parser_python2.py    License: GNU General Public License v3.0 6 votes vote down vote up
def ParseIndexes(self, block, dictionary):
        data = block.data
        pos = 32
        size = block.logical_size
        while pos < size:
            index = struct.unpack("<I", data[pos : pos+4])[0]
            pos += 4
            index_size, bytes_moved = SpotlightStore.ReadVarSizeNum(data[pos:])
            pos += bytes_moved
            
            padding = index_size % 4
            pos += padding

            index_size = 4*int(index_size//4)
            ids = struct.unpack("<" + str(index_size//4) + "I", data[pos:pos + index_size])
            pos += index_size
            
            # sanity check
            temp = dictionary.get(index, None)
            if temp != None:
                log.error("Error, category {} already exists!!".format(temp))
            # end check
            dictionary[index] = ids 
Example 23
Project: spotlight_parser   Author: ydkhatri   File: spotlight_parser.py    License: GNU General Public License v3.0 6 votes vote down vote up
def ParseIndexes(self, block, dictionary):
        data = block.data
        pos = 32
        size = block.logical_size
        while pos < size:
            index = struct.unpack("<I", data[pos : pos+4])[0]
            pos += 4
            index_size, bytes_moved = SpotlightStore.ReadVarSizeNum(data[pos:])
            pos += bytes_moved
            
            padding = index_size % 4
            pos += padding

            index_size = 4*int(index_size//4)
            ids = struct.unpack("<" + str(index_size//4) + "i", data[pos:pos + index_size])
            pos += index_size
            
            # sanity check
            temp = dictionary.get(index, None)
            if temp != None:
                log.error("Error, category {} already exists!!".format(temp))
            # end check
            dictionary[index] = ids 
Example 24
Project: Faraday-Software   Author: FaradayRF   File: proxy.py    License: GNU General Public License v3.0 6 votes vote down vote up
def saveProxyLog(name, config):
    '''
    Save proxy log database into a new file

    :param name: Name of file to save data into (should be .db)
    :param config: Proxy ConfigParser object from proxy.ini
    :return: None
    '''

    log = config.get("DATABASE", "filename")
    oldpath = os.path.join(faradayHelper.userPath, 'lib', log)
    newpath = os.path.join(faradayHelper.userPath, 'lib', name)

    try:
        shutil.move(oldpath, newpath)
        sys.exit(0)

    except shutil.Error as e:
        logger.error(e)
    except IOError as e:
        logger.error(e) 
Example 25
Project: macops   Author: google   File: systemconfig.py    License: Apache License 2.0 5 votes vote down vote up
def ConfigureSystemProxy(proxy=CORP_PROXY, enable=True):
  """Sets the system proxy to the specified value."""
  scd_prefs = SCDynamicPreferences()
  if not scd_prefs.SetProxy(enable=enable, pac=proxy):
    logging.error('Could not change proxy settings.') 
Example 26
Project: pywren-ibm-cloud   Author: pywren   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def readline(self):
        try:
            retval = self.sb.readline()
        except struct.error:
            raise EOFError()
        self.pos += len(retval)
        return retval 
Example 27
Project: jawfish   Author: war-and-code   File: platform.py    License: MIT License 5 votes vote down vote up
def _node(default=''):

    """ Helper to determine the node name of this machine.
    """
    try:
        import socket
    except ImportError:
        # No sockets...
        return default
    try:
        return socket.gethostname()
    except socket.error:
        # Still not working...
        return default 
Example 28
Project: jawfish   Author: war-and-code   File: platform.py    License: MIT License 5 votes vote down vote up
def _syscmd_file(target,default=''):

    """ Interface to the system's file command.

        The function uses the -b option of the file command to have it
        omit the filename in its output. Follow the symlinks. It returns
        default in case the command should fail.

    """
    if sys.platform in ('dos','win32','win16','os2'):
        # XXX Others too ?
        return default
    target = _follow_symlinks(target)
    try:
        proc = subprocess.Popen(['file', target],
                stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    except (AttributeError,os.error):
        return default
    output = proc.communicate()[0].decode('latin-1')
    rc = proc.wait()
    if not output or rc:
        return default
    else:
        return output

### Information about the used architecture

# Default values for architecture; non-empty strings override the
# defaults given as parameters 
Example 29
Project: Telethon   Author: LonamiWebs   File: mtprotosender.py    License: MIT License 5 votes vote down vote up
def disconnected(self):
        """
        Future that resolves when the connection to Telegram
        ends, either by user action or in the background.

        Note that it may resolve in either a ``ConnectionError``
        or any other unexpected error that could not be handled.
        """
        return asyncio.shield(self._disconnected, loop=self._loop)

    # Private methods 
Example 30
Project: Telethon   Author: LonamiWebs   File: mtprotosender.py    License: MIT License 5 votes vote down vote up
def _disconnect(self, error=None):
        if self._connection is None:
            self._log.info('Not disconnecting (already have no connection)')
            return

        self._log.info('Disconnecting from %s...', self._connection)
        self._user_connected = False
        try:
            self._log.debug('Closing current connection...')
            await self._connection.disconnect()
        finally:
            self._log.debug('Cancelling %d pending message(s)...', len(self._pending_state))
            for state in self._pending_state.values():
                if error and not state.future.done():
                    state.future.set_exception(error)
                else:
                    state.future.cancel()

            self._pending_state.clear()
            await helpers._cancel(
                self._log,
                send_loop_handle=self._send_loop_handle,
                recv_loop_handle=self._recv_loop_handle
            )

            self._log.info('Disconnection from %s complete!', self._connection)
            self._connection = None

        if self._disconnected and not self._disconnected.done():
            if error:
                self._disconnected.set_exception(error)
            else:
                self._disconnected.set_result(None) 
Example 31
Project: Telethon   Author: LonamiWebs   File: mtprotosender.py    License: MIT License 5 votes vote down vote up
def _handle_rpc_result(self, message):
        """
        Handles the result for Remote Procedure Calls:

            rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;

        This is where the future results for sent requests are set.
        """
        rpc_result = message.obj
        state = self._pending_state.pop(rpc_result.req_msg_id, None)
        self._log.debug('Handling RPC result for message %d',
                        rpc_result.req_msg_id)

        if not state:
            # TODO We should not get responses to things we never sent
            # However receiving a File() with empty bytes is "common".
            # See #658, #759 and #958. They seem to happen in a container
            # which contain the real response right after.
            try:
                with BinaryReader(rpc_result.body) as reader:
                    if not isinstance(reader.tgread_object(), upload.File):
                        raise ValueError('Not an upload.File')
            except (TypeNotFoundError, ValueError):
                self._log.info('Received response without parent request: %s', rpc_result.body)
            return

        if rpc_result.error:
            error = rpc_message_to_error(rpc_result.error, state.request)
            self._send_queue.append(
                RequestState(MsgsAck([state.msg_id]), loop=self._loop))

            if not state.future.cancelled():
                state.future.set_exception(error)
        else:
            with BinaryReader(rpc_result.body) as reader:
                result = state.request.read_result(reader)

            if not state.future.cancelled():
                state.future.set_result(result) 
Example 32
Project: Telethon   Author: LonamiWebs   File: utils.py    License: MIT License 5 votes vote down vote up
def resolve_invite_link(link):
    """
    Resolves the given invite link. Returns a tuple of
    ``(link creator user id, global chat id, random int)``.

    Note that for broadcast channels, the link creator
    user ID will be zero to protect their identity.
    Normal chats and megagroup channels will have such ID.

    Note that the chat ID may not be accurate for chats
    with a link that were upgraded to megagroup, since
    the link can remain the same, but the chat ID will
    be correct once a new link is generated.
    """
    link_hash, is_link = parse_username(link)
    if not is_link:
        # Perhaps the user passed the link hash directly
        link_hash = link

    # Little known fact, but invite links with a
    # hex-string of bytes instead of base64 also works.
    if re.match(r'[a-fA-F\d]{32}', link_hash):
        payload = bytes.fromhex(link_hash)
    else:
        payload = _decode_telegram_base64(link_hash)

    try:
        return struct.unpack('>LLQ', payload)
    except (struct.error, TypeError):
        return None, None, None 
Example 33
Project: asn1tools   Author: eerimoq   File: oer.py    License: MIT License 5 votes vote down vote up
def encode(self, data, encoder):
        if self.fmt is None:
            encoded = der.encode_real(data)
            encoder.append_length_determinant(len(encoded))
            encoder.append_bytes(encoded)
        else:
            try:
                encoder.append_bytes(struct.pack(self.fmt, data))
            except (struct.error, OverflowError):
                raise EncodeError(
                    'Expected an IEEE 754 {} bits floating point number, but '
                    'got {}.'.format(8 * self.length,
                                     data)) 
Example 34
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 5 votes vote down vote up
def __ubx_NAV_SOL(self, dev):
        payload = dev.read(size=54)
        payload_cpy = payload

        if(self.__validate_checksum(1, 6, payload, dev)):
            try:
                payload_cpy = payload_cpy[2:]
                self.iTOW, self.fTOW, self.week, self.gpsFix, self.flags, self.ecefX, self.ecefY, self.ecefZ, self.pAcc, self.ecefVX, self.ecefVY, self.ecefVZ, self.sAcc, self.pDOP, reserved1, self.numSV, reserved21, reserved22, reserved23, reserved24 = struct.unpack('=LlhBB3lL3lLH6B', payload_cpy)
                self.ubx_class = '01'
                self.ubx_id = '06'

            except struct.error:
                print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))



    # Time of week in ms / Year(UTC) / Month (UTC 1..12) / Day (1..31)
    # Hour (0..23) / Minute (0..59) / Seconds (0..60) / Validity Flags
    # Time Accuracy Estimate in ns / Fraction of second (-1e9..1e9)
    # GNSS Fix Type / Fix Status Flags / Other Flags / Number of Sattelites
    # Longitude in deg (1e-7) / Latitude in deg (1e-7) / Height Ellipsoid in mm
    # Height Sea Level in mm / Horizontal Accuracy in mm / Vertical Accuracy in mm
    # North Velocity mm s^-1 / East Velocity mm s^-1 / Down Velocity mm s^-1
    # Ground speed in mm s^-1 / Heading of Motion in deg (1e-5) / Speed accuracy mm s^-1
    # Heading accuracy estimate deg (1e-5) / Position DOP (0.01) / Reserved space
    # Heading of Vehicle in deg (1e-5) / Magnetic Declination in deg (1e-2) <-+ Accuracy in deg 
Example 35
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 5 votes vote down vote up
def __ubx_CFG_MSG(self,  msgClass, msgId, ioPorts):
        header, ubx_class, ubx_id, length = 46434, 6, 1, 8
        payload = [length, 0, msgClass, msgId] + ioPorts
        checksum = self.__calc_checksum(ubx_class, ubx_id, payload)
        try:
            self.msg = struct.pack('>H14B', header, ubx_class, ubx_id, length, 0,  msgClass, msgId, ioPorts[0], ioPorts[1], ioPorts[2], ioPorts[3], ioPorts[4], ioPorts[5], checksum[0], checksum[1])
            self.ubx_class = '06'
            self.ubx_id = '01'

        except struct.error:
            print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))



    ## UBX-CFG-CFG (0x06 0x09) 
Example 36
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 5 votes vote down vote up
def __ubx_CFG_CFG(self, clearMask, saveMask, loadMask, deviceMask):
        header, ubx_class, ubx_id, length = 46434, 6, 9, 13
        payload = [length, 0] + clearMask + saveMask + loadMask + deviceMask
        checksum = self.__calc_checksum(ubx_class, ubx_id, payload)
        payload = payload + checksum
        try:
            self.msg = struct.pack('>H19B', header, ubx_class, ubx_id, *payload)
            self.ubx_class = '06'
            self.ubx_id = '09'
        except struct.error:
            print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))


    ## UBX-CFG-NAV5 (0x06 0x24)
    #  ! only currently configures dynModel ! <- Dynmodel = 6/7/8  Needed for high altitude 50km 
Example 37
Project: ublox   Author: Korving-F   File: ubx.py    License: MIT License 5 votes vote down vote up
def __ubx_CFG_NAV5(self, dynModel):
        header, ubx_class, ubx_id, length = 46434, 6, 36, 36
        body = [3, 0, 0, 0, 0, 16, 39, 0, 0, 5, 0, 250, 0, 250, 0, 100, 0, 44, 1, 0, 60, 0, 0, 0, 0, 200, 0, 0, 0, 0, 0, 0, 0]
        payload = [length, 0] + [255, 255] + [dynModel] + body
        checksum = self.__calc_checksum(ubx_class, ubx_id, payload)
        payload = payload + checksum
        try:
            self.msg = struct.pack('>H42B', header, ubx_class, ubx_id, *payload)
            self.ubx_class = '06'
            self.ubx_id = '24'
        except struct.error:
            print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1])) 
Example 38
Project: recruit   Author: Frank-qlu   File: terminal.py    License: Apache License 2.0 5 votes vote down vote up
def _get_terminal_size_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl
            import termios
            import struct
            cr = struct.unpack(
                'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
        except (struct.error, IOError):
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except OSError:
            pass
    if not cr or cr == (0, 0):
        try:
            from os import environ as env
            cr = (env['LINES'], env['COLUMNS'])
        except (ValueError, KeyError):
            return None
    return int(cr[1]), int(cr[0]) 
Example 39
Project: recruit   Author: Frank-qlu   File: ipaddress.py    License: Apache License 2.0 5 votes vote down vote up
def _compat_to_bytes(intval, length, endianess):
    assert isinstance(intval, _compat_int_types)
    assert endianess == 'big'
    if length == 4:
        if intval < 0 or intval >= 2 ** 32:
            raise struct.error("integer out of range for 'I' format code")
        return struct.pack(b'!I', intval)
    elif length == 16:
        if intval < 0 or intval >= 2 ** 128:
            raise struct.error("integer out of range for 'QQ' format code")
        return struct.pack(b'!QQ', intval >> 64, intval & 0xffffffffffffffff)
    else:
        raise NotImplementedError() 
Example 40
Project: recruit   Author: Frank-qlu   File: ipaddress.py    License: Apache License 2.0 5 votes vote down vote up
def v6_int_to_packed(address):
    """Represent an address as 16 packed bytes in network (big-endian) order.

    Args:
        address: An integer representation of an IPv6 IP address.

    Returns:
        The integer address packed as 16 bytes in network (big-endian) order.

    """
    try:
        return _compat_to_bytes(address, 16, 'big')
    except (struct.error, OverflowError):
        raise ValueError("Address negative or too large for IPv6")