Python ctypes 模块,ArgumentError() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.ArgumentError()

项目:rice    作者:randy3k    | 项目源码 | 文件源码
def _winapi(self, func, *a, **kw):
        """
        Flush and call win API function.
        """
        self.flush()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
            self.LOG.flush()

        try:
            return func(*a, **kw)
        except ArgumentError as e:
            if _DEBUG_RENDER_OUTPUT:
                self.LOG.write(('    Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8'))
项目:py-sdl2    作者:marcusva    | 项目源码 | 文件源码
def test_SpriteFactory_create_software_sprite(self):
        factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)
        for w in range(0, 100):
            for h in range(0, 100):
                for bpp in (1, 4, 8, 12, 15, 16, 24, 32):
                    sprite = factory.create_software_sprite((w, h), bpp)
                    self.assertIsInstance(sprite, sdl2ext.SoftwareSprite)

        #self.assertRaises(ValueError, factory.create_software_sprite, (-1,-1))
        #self.assertRaises(ValueError, factory.create_software_sprite, (-10,5))
        #self.assertRaises(ValueError, factory.create_software_sprite, (10,-5))
        self.assertRaises(TypeError, factory.create_software_sprite, size=None)
        self.assertRaises(sdl2ext.SDLError, factory.create_software_sprite,
                          size=(10, 10), bpp=-1)
        self.assertRaises(TypeError, factory.create_software_sprite, masks=5)
        self.assertRaises((ArgumentError, TypeError),
                          factory.create_software_sprite, size=(10, 10),
                          masks=(None, None, None, None))
        self.assertRaises((ArgumentError, TypeError),
                          factory.create_software_sprite, size=(10, 10),
                          masks=("Test", 1, 2, 3))
        dogc()
项目:py-sdl2    作者:marcusva    | 项目源码 | 文件源码
def test_SpriteFactory_from_image(self):
        window = sdl2ext.Window("Test", size=(1, 1))
        renderer = sdl2ext.Renderer(window)
        tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
        sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)

        for suffix in ("tif", "png", "jpg"):
            imgname = RESOURCES.get_path("surfacetest.%s" % suffix)
            tsprite = tfactory.from_image(imgname)
            self.assertIsInstance(tsprite, sdl2ext.TextureSprite)
            ssprite = sfactory.from_image(imgname)
            self.assertIsInstance(ssprite, sdl2ext.SoftwareSprite)

        for factory in (tfactory, sfactory):
            self.assertRaises((ArgumentError, ValueError),
                              factory.from_image, None)
            #self.assertRaises((IOError, SDLError),
            #                  factory.from_image, "banana")
            if not _ISPYPY:
                self.assertRaises(ArgumentError, factory.from_image, 12345)
        dogc()
项目:py-sdl2    作者:marcusva    | 项目源码 | 文件源码
def test_SpriteFactory_from_surface(self):
        window = sdl2ext.Window("Test", size=(1, 1))
        renderer = sdl2ext.Renderer(window)
        tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
        sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)

        sf = SDL_CreateRGBSurface(0, 10, 10, 32, 0, 0, 0, 0)
        tsprite = tfactory.from_surface(sf.contents)
        self.assertIsInstance(tsprite, sdl2ext.TextureSprite)
        ssprite = sfactory.from_surface(sf.contents)
        self.assertIsInstance(ssprite, sdl2ext.SoftwareSprite)
        SDL_FreeSurface(sf)

        for factory in (tfactory, sfactory):
            self.assertRaises((sdl2ext.SDLError, AttributeError, ArgumentError,
                               TypeError), factory.from_surface, None)
            self.assertRaises((AttributeError, ArgumentError, TypeError),
                              factory.from_surface, "test")
            # TODO: crashes pypy 2.0
            #self.assertRaises((AttributeError, ArgumentError, TypeError),
            #                  factory.from_surface, 1234)
        dogc()
项目:py-sdl2    作者:marcusva    | 项目源码 | 文件源码
def test_SDL_GetAudioDriver(self):
        founddummy = False
        drivercount = audio.SDL_GetNumAudioDrivers()
        for index in range(drivercount):
            drivername = audio.SDL_GetAudioDriver(index)
            self.assertIsInstance(drivername, (str, bytes))
            if drivername == b"dummy":
                founddummy = True
        self.assertTrue(founddummy, "could not find dummy driver")
        # self.assertRaises(SDLError, audio.SDL_GetAudioDriver, -1)
        # self.assertRaises(SDLError, audio.get_audio_driver,
        #                  drivercount + 1)
        self.assertRaises((ctypes.ArgumentError, TypeError),
                          audio.SDL_GetAudioDriver, "Test")
        self.assertRaises((ctypes.ArgumentError, TypeError),
                          audio.SDL_GetAudioDriver, None)
项目:py-sdl2    作者:marcusva    | 项目源码 | 文件源码
def test_SDL_AllocFreePalette(self):
        self.assertRaises((ArgumentError, TypeError), pixels.SDL_AllocPalette,
                          None)
        self.assertRaises((ArgumentError, TypeError), pixels.SDL_AllocPalette,
                          "Test")
        # self.assertRaises(ValueError, pixels.SDL_AllocPalette, -5)

        palette = pixels.SDL_AllocPalette(10)
        self.assertIsInstance(palette.contents, pixels.SDL_Palette)
        self.assertEqual(palette.contents.ncolors, 10)
        colors = palette.contents.colors
        for x in range(palette.contents.ncolors):
            self.assertIsInstance(colors[x], SDL_Color)
        colors[3].r = 70
        self.assertEqual(colors[3].r, 70)
        color = colors[4]
        self.assertEqual(colors[4].g, 255)
        self.assertEqual(color.g, 255)
        color.g = 33
        self.assertEqual(color.g, 33)
        self.assertEqual(colors[4].g, 33)
        pixels.SDL_FreePalette(palette)
项目:pyttsx3    作者:nateshmbhat    | 项目源码 | 文件源码
def setProperty(self, name, value):
        if name == 'voice':
            if value is None: return
            try:
                utf8Value = toUtf8(value)
                _espeak.SetVoiceByName(utf8Value)
            except ctypes.ArgumentError as e:
                raise ValueError(str(e))
        elif name == 'rate':
            try:
                _espeak.SetParameter(_espeak.RATE, value, 0)
            except ctypes.ArgumentError as e:
                raise ValueError(str(e))
        elif name == 'volume':
            try:
                _espeak.SetParameter(_espeak.VOLUME, int(round(value*100, 2)), 0)
            except TypeError as e:
                raise ValueError(str(e))
        else:
            raise KeyError('unknown property %s' % name)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _coord_byval(coord):
    """
    Turns a COORD object into a c_long.
    This will cause it to be passed by value instead of by reference. (That is what I think at least.)

    When runing ``ptipython`` is run (only with IPython), we often got the following error::

         Error in 'SetConsoleCursorPosition'.
         ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
     argument 2: <class 'TypeError'>: wrong type

    It was solved by turning ``COORD`` parameters into a ``c_long`` like this.

    More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
    """
    return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)


#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _winapi(self, func, *a, **kw):
        """
        Flush and call win API function.
        """
        self.flush()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
            self.LOG.flush()

        try:
            return func(*a, **kw)
        except ArgumentError as e:
            if _DEBUG_RENDER_OUTPUT:
                self.LOG.write(('    Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8'))
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def add_tcp_relay(self, address, port, public_key):
        """
        Adds additional host:port pair as TCP relay.

        This function can be used to initiate TCP connections to different ports on the same bootstrap node, or to add
         TCP relays without using them as bootstrap nodes.

        :param address: The hostname or IP address (IPv4 or IPv6) of the TCP relay.
        :param port: The port on the host on which the TCP relay is listening.
        :param public_key: The long term public key of the TCP relay (TOX_PUBLIC_KEY_SIZE bytes).
        :return: True on success.
        """
        tox_err_bootstrap = c_int()
        result = Tox.libtoxcore.tox_add_tcp_relay(self._tox_pointer, c_char_p(address), c_uint16(port),
                                                  string_to_bin(public_key), byref(tox_err_bootstrap))
        tox_err_bootstrap = tox_err_bootstrap.value
        if tox_err_bootstrap == TOX_ERR_BOOTSTRAP['OK']:
            return bool(result)
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['BAD_HOST']:
            raise ArgumentError('The address could not be resolved to an IP '
                                'address, or the IP address passed was invalid.')
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['BAD_PORT']:
            raise ArgumentError('The port passed was invalid. The valid port range is (1, 65535).')
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def self_set_name(self, name):
        """
        Set the nickname for the Tox client.

        Nickname length cannot exceed TOX_MAX_NAME_LENGTH. If length is 0, the name parameter is ignored
        (it can be None), and the nickname is set back to empty.
        :param name: New nickname.
        :return: True on success.
        """
        tox_err_set_info = c_int()
        result = Tox.libtoxcore.tox_self_set_name(self._tox_pointer, c_char_p(str.encode(name)),
                                                  c_size_t(len(name)), byref(tox_err_set_info))
        tox_err_set_info = tox_err_set_info.value
        if tox_err_set_info == TOX_ERR_SET_INFO['OK']:
            return bool(result)
        elif tox_err_set_info == TOX_ERR_SET_INFO['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif tox_err_set_info == TOX_ERR_SET_INFO['TOO_LONG']:
            raise ArgumentError('Information length exceeded maximum permissible size.')
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def friend_delete(self, friend_number):
        """
        Remove a friend from the friend list.

        This does not notify the friend of their deletion. After calling this function, this client will appear offline
        to the friend and no communication can occur between the two.

        :param friend_number: Friend number for the friend to be deleted.
        :return: True on success.
        """
        tox_err_friend_delete = c_int()
        result = Tox.libtoxcore.tox_friend_delete(self._tox_pointer, c_uint32(friend_number),
                                                  byref(tox_err_friend_delete))
        tox_err_friend_delete = tox_err_friend_delete.value
        if tox_err_friend_delete == TOX_ERR_FRIEND_DELETE['OK']:
            return bool(result)
        elif tox_err_friend_delete == TOX_ERR_FRIEND_DELETE['FRIEND_NOT_FOUND']:
            raise ArgumentError('There was no friend with the given friend number. No friends were deleted.')

    # -----------------------------------------------------------------------------------------------------------------
    # Friend list queries
    # -----------------------------------------------------------------------------------------------------------------
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def friend_by_public_key(self, public_key):
        """
        Return the friend number associated with that Public Key.

        :param public_key: A byte array containing the Public Key.
        :return: friend number
        """
        tox_err_friend_by_public_key = c_int()
        result = Tox.libtoxcore.tox_friend_by_public_key(self._tox_pointer, string_to_bin(public_key),
                                                         byref(tox_err_friend_by_public_key))
        tox_err_friend_by_public_key = tox_err_friend_by_public_key.value
        if tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['OK']:
            return result
        elif tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['NOT_FOUND']:
            raise ArgumentError('No friend with the given Public Key exists on the friend list.')
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def friend_get_public_key(self, friend_number, public_key=None):
        """
        Copies the Public Key associated with a given friend number to a byte array.

        :param friend_number: The friend number you want the Public Key of.
        :param public_key: pointer (c_char_p) to a memory region of at least TOX_PUBLIC_KEY_SIZE bytes. If this
        parameter is None, this function allocates memory for Tox Public Key.
        :return: Tox Public Key
        """
        if public_key is None:
            public_key = create_string_buffer(TOX_PUBLIC_KEY_SIZE)
        tox_err_friend_get_public_key = c_int()
        Tox.libtoxcore.tox_friend_get_public_key(self._tox_pointer, c_uint32(friend_number), public_key,
                                                 byref(tox_err_friend_get_public_key))
        tox_err_friend_get_public_key = tox_err_friend_get_public_key.value
        if tox_err_friend_get_public_key == TOX_ERR_FRIEND_GET_PUBLIC_KEY['OK']:
            return bin_to_string(public_key, TOX_PUBLIC_KEY_SIZE)
        elif tox_err_friend_get_public_key == TOX_ERR_FRIEND_GET_PUBLIC_KEY['FRIEND_NOT_FOUND']:
            raise ArgumentError('No friend with the given number exists on the friend list.')
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def friend_get_last_online(self, friend_number):
        """
        Return a unix-time timestamp of the last time the friend associated with a given friend number was seen online.
        This function will return UINT64_MAX on error.

        :param friend_number: The friend number you want to query.
        :return: unix-time timestamp
        """
        tox_err_last_online = c_int()
        result = Tox.libtoxcore.tox_friend_get_last_online(self._tox_pointer, c_uint32(friend_number),
                                                           byref(tox_err_last_online))
        tox_err_last_online = tox_err_last_online.value
        if tox_err_last_online == TOX_ERR_FRIEND_GET_LAST_ONLINE['OK']:
            return result
        elif tox_err_last_online == TOX_ERR_FRIEND_GET_LAST_ONLINE['FRIEND_NOT_FOUND']:
            raise ArgumentError('No friend with the given number exists on the friend list.')

    # -----------------------------------------------------------------------------------------------------------------
    # Friend-specific state queries (can also be received through callbacks)
    # -----------------------------------------------------------------------------------------------------------------
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def friend_get_status_message_size(self, friend_number):
        """
        Return the length of the friend's status message. If the friend number is invalid, the return value is SIZE_MAX.

        :return: length of the friend's status message
        """
        tox_err_friend_query = c_int()
        result = Tox.libtoxcore.tox_friend_get_status_message_size(self._tox_pointer, c_uint32(friend_number),
                                                                   byref(tox_err_friend_query))
        tox_err_friend_query = tox_err_friend_query.value
        if tox_err_friend_query == TOX_ERR_FRIEND_QUERY['OK']:
            return result
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['NULL']:
            raise ArgumentError('The pointer parameter for storing the query result (name, message) was NULL. Unlike'
                                ' the `_self_` variants of these functions, which have no effect when a parameter is'
                                ' NULL, these functions return an error in that case.')
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend_number did not designate a valid friend.')
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def friend_get_status(self, friend_number):
        """
        Return the friend's user status (away/busy/...). If the friend number is invalid, the return value is
        unspecified.

        The status returned is equal to the last status received through the `friend_status` callback.

        :return: TOX_USER_STATUS
        """
        tox_err_friend_query = c_int()
        result = Tox.libtoxcore.tox_friend_get_status(self._tox_pointer, c_uint32(friend_number),
                                                      byref(tox_err_friend_query))
        tox_err_friend_query = tox_err_friend_query.value
        if tox_err_friend_query == TOX_ERR_FRIEND_QUERY['OK']:
            return result
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['NULL']:
            raise ArgumentError('The pointer parameter for storing the query result (name, message) was NULL. Unlike'
                                ' the `_self_` variants of these functions, which have no effect when a parameter is'
                                ' NULL, these functions return an error in that case.')
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend_number did not designate a valid friend.')
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def friend_get_connection_status(self, friend_number):
        """
        Check whether a friend is currently connected to this client.

        The result of this function is equal to the last value received by the `friend_connection_status` callback.

        :param friend_number: The friend number for which to query the connection status.
        :return: the friend's connection status (TOX_CONNECTION) as it was received through the
        `friend_connection_status` event.
        """
        tox_err_friend_query = c_int()
        result = Tox.libtoxcore.tox_friend_get_connection_status(self._tox_pointer, c_uint32(friend_number),
                                                                 byref(tox_err_friend_query))
        tox_err_friend_query = tox_err_friend_query.value
        if tox_err_friend_query == TOX_ERR_FRIEND_QUERY['OK']:
            return result
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['NULL']:
            raise ArgumentError('The pointer parameter for storing the query result (name, message) was NULL. Unlike'
                                ' the `_self_` variants of these functions, which have no effect when a parameter is'
                                ' NULL, these functions return an error in that case.')
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend_number did not designate a valid friend.')
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def self_set_typing(self, friend_number, typing):
        """
        Set the client's typing status for a friend.

        The client is responsible for turning it on or off.

        :param friend_number: The friend to which the client is typing a message.
        :param typing: The typing status. True means the client is typing.
        :return: True on success.
        """
        tox_err_set_typing = c_int()
        result = Tox.libtoxcore.tox_self_set_typing(self._tox_pointer, c_uint32(friend_number),
                                                    c_bool(typing), byref(tox_err_set_typing))
        tox_err_set_typing = tox_err_set_typing.value
        if tox_err_set_typing == TOX_ERR_SET_TYPING['OK']:
            return bool(result)
        elif tox_err_set_typing == TOX_ERR_SET_TYPING['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend number did not designate a valid friend.')
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
def __init__(self, tox_pointer):
        """
        Start new A/V session. There can only be only one session per Tox instance.

        :param tox_pointer: pointer to Tox instance
        """
        toxav_err_new = c_int()
        ToxAV.libtoxav.toxav_new.restype = POINTER(c_void_p)
        self._toxav_pointer = ToxAV.libtoxav.toxav_new(tox_pointer, byref(toxav_err_new))
        toxav_err_new = toxav_err_new.value
        if toxav_err_new == TOXAV_ERR_NEW['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif toxav_err_new == TOXAV_ERR_NEW['MALLOC']:
            raise MemoryError('Memory allocation failure while trying to allocate structures required for the A/V '
                              'session.')
        elif toxav_err_new == TOXAV_ERR_NEW['MULTIPLE']:
            raise RuntimeError('Attempted to create a second session for the same Tox instance.')

        self.call_state_cb = None
        self.audio_receive_frame_cb = None
        self.video_receive_frame_cb = None
        self.call_cb = None
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def _coord_byval(coord):
    """
    Turns a COORD object into a c_long.
    This will cause it to be passed by value instead of by reference. (That is what I think at least.)

    When runing ``ptipython`` is run (only with IPython), we often got the following error::

         Error in 'SetConsoleCursorPosition'.
         ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
     argument 2: <class 'TypeError'>: wrong type

    It was solved by turning ``COORD`` parameters into a ``c_long`` like this.

    More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
    """
    return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)


#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def _winapi(self, func, *a, **kw):
        """
        Flush and call win API function.
        """
        self.flush()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
            self.LOG.flush()

        try:
            return func(*a, **kw)
        except ArgumentError as e:
            if _DEBUG_RENDER_OUTPUT:
                self.LOG.write(('    Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8'))
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def bootstrap(self, address, port, public_key):
        """
        Sends a "get nodes" request to the given bootstrap node with IP, port, and public key to setup connections.

        This function will attempt to connect to the node using UDP. You must use this function even if
        Tox_Options.udp_enabled was set to false.

        :param address: The hostname or IP address (IPv4 or IPv6) of the node.
        :param port: The port on the host on which the bootstrap Tox instance is listening.
        :param public_key: The long term public key of the bootstrap node (TOX_PUBLIC_KEY_SIZE bytes).
        :return: True on success.
        """
        tox_err_bootstrap = c_int()
        result = Tox.libtoxcore.tox_bootstrap(self._tox_pointer, c_char_p(address), c_uint16(port),
                                              string_to_bin(public_key), byref(tox_err_bootstrap))
        tox_err_bootstrap = tox_err_bootstrap.value
        if tox_err_bootstrap == TOX_ERR_BOOTSTRAP['OK']:
            return bool(result)
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['BAD_HOST']:
            raise ArgumentError('The address could not be resolved to an IP '
                                'address, or the IP address passed was invalid.')
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['BAD_PORT']:
            raise ArgumentError('The port passed was invalid. The valid port range is (1, 65535).')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def add_tcp_relay(self, address, port, public_key):
        """
        Adds additional host:port pair as TCP relay.

        This function can be used to initiate TCP connections to different ports on the same bootstrap node, or to add
         TCP relays without using them as bootstrap nodes.

        :param address: The hostname or IP address (IPv4 or IPv6) of the TCP relay.
        :param port: The port on the host on which the TCP relay is listening.
        :param public_key: The long term public key of the TCP relay (TOX_PUBLIC_KEY_SIZE bytes).
        :return: True on success.
        """
        tox_err_bootstrap = c_int()
        result = Tox.libtoxcore.tox_add_tcp_relay(self._tox_pointer, c_char_p(address), c_uint16(port),
                                                  c_char_p(public_key), byref(tox_err_bootstrap))
        tox_err_bootstrap = tox_err_bootstrap.value
        if tox_err_bootstrap == TOX_ERR_BOOTSTRAP['OK']:
            return bool(result)
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['BAD_HOST']:
            raise ArgumentError('The address could not be resolved to an IP '
                                'address, or the IP address passed was invalid.')
        elif tox_err_bootstrap == TOX_ERR_BOOTSTRAP['BAD_PORT']:
            raise ArgumentError('The port passed was invalid. The valid port range is (1, 65535).')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def self_set_name(self, name):
        """
        Set the nickname for the Tox client.

        Nickname length cannot exceed TOX_MAX_NAME_LENGTH. If length is 0, the name parameter is ignored
        (it can be None), and the nickname is set back to empty.
        :param name: New nickname.
        :return: True on success.
        """
        tox_err_set_info = c_int()
        result = Tox.libtoxcore.tox_self_set_name(self._tox_pointer, c_char_p(name),
                                                  c_size_t(len(name)), byref(tox_err_set_info))
        tox_err_set_info = tox_err_set_info.value
        if tox_err_set_info == TOX_ERR_SET_INFO['OK']:
            return bool(result)
        elif tox_err_set_info == TOX_ERR_SET_INFO['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif tox_err_set_info == TOX_ERR_SET_INFO['TOO_LONG']:
            raise ArgumentError('Information length exceeded maximum permissible size.')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def self_set_status_message(self, status_message):
        """
        Set the client's status message.

        Status message length cannot exceed TOX_MAX_STATUS_MESSAGE_LENGTH. If length is 0, the status parameter is
        ignored, and the user status is set back to empty.

        :param status_message: new status message
        :return: True on success.
        """
        tox_err_set_info = c_int()
        result = Tox.libtoxcore.tox_self_set_status_message(self._tox_pointer, c_char_p(status_message),
                                                            c_size_t(len(status_message)), byref(tox_err_set_info))
        tox_err_set_info = tox_err_set_info.value
        if tox_err_set_info == TOX_ERR_SET_INFO['OK']:
            return bool(result)
        elif tox_err_set_info == TOX_ERR_SET_INFO['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif tox_err_set_info == TOX_ERR_SET_INFO['TOO_LONG']:
            raise ArgumentError('Information length exceeded maximum permissible size.')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def friend_delete(self, friend_number):
        """
        Remove a friend from the friend list.

        This does not notify the friend of their deletion. After calling this function, this client will appear offline
        to the friend and no communication can occur between the two.

        :param friend_number: Friend number for the friend to be deleted.
        :return: True on success.
        """
        tox_err_friend_delete = c_int()
        result = Tox.libtoxcore.tox_friend_delete(self._tox_pointer, c_uint32(friend_number),
                                                  byref(tox_err_friend_delete))
        tox_err_friend_delete = tox_err_friend_delete.value
        if tox_err_friend_delete == TOX_ERR_FRIEND_DELETE['OK']:
            return bool(result)
        elif tox_err_friend_delete == TOX_ERR_FRIEND_DELETE['FRIEND_NOT_FOUND']:
            raise ArgumentError('There was no friend with the given friend number. No friends were deleted.')

    # -----------------------------------------------------------------------------------------------------------------
    # Friend list queries
    # -----------------------------------------------------------------------------------------------------------------
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def friend_by_public_key(self, public_key):
        """
        Return the friend number associated with that Public Key.

        :param public_key: A byte array containing the Public Key.
        :return: friend number
        """
        tox_err_friend_by_public_key = c_int()
        result = Tox.libtoxcore.tox_friend_by_public_key(self._tox_pointer, string_to_bin(public_key),
                                                         byref(tox_err_friend_by_public_key))
        tox_err_friend_by_public_key = tox_err_friend_by_public_key.value
        if tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['OK']:
            return result
        elif tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['NULL']:
            raise ArgumentError('One of the arguments to the function was NULL when it was not expected.')
        elif tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['NOT_FOUND']:
            raise ArgumentError('No friend with the given Public Key exists on the friend list.')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def friend_get_public_key(self, friend_number, public_key=None):
        """
        Copies the Public Key associated with a given friend number to a byte array.

        :param friend_number: The friend number you want the Public Key of.
        :param public_key: pointer (c_char_p) to a memory region of at least TOX_PUBLIC_KEY_SIZE bytes. If this
        parameter is None, this function allocates memory for Tox Public Key.
        :return: Tox Public Key
        """
        if public_key is None:
            public_key = create_string_buffer(TOX_PUBLIC_KEY_SIZE)
        tox_err_friend_get_public_key = c_int()
        Tox.libtoxcore.tox_friend_get_public_key(self._tox_pointer, c_uint32(friend_number), public_key,
                                                 byref(tox_err_friend_get_public_key))
        tox_err_friend_get_public_key = tox_err_friend_get_public_key.value
        if tox_err_friend_get_public_key == TOX_ERR_FRIEND_GET_PUBLIC_KEY['OK']:
            return bin_to_string(public_key, TOX_PUBLIC_KEY_SIZE)
        elif tox_err_friend_get_public_key == TOX_ERR_FRIEND_GET_PUBLIC_KEY['FRIEND_NOT_FOUND']:
            raise ArgumentError('No friend with the given number exists on the friend list.')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def friend_get_last_online(self, friend_number):
        """
        Return a unix-time timestamp of the last time the friend associated with a given friend number was seen online.
        This function will return UINT64_MAX on error.

        :param friend_number: The friend number you want to query.
        :return: unix-time timestamp
        """
        tox_err_last_online = c_int()
        result = Tox.libtoxcore.tox_friend_get_last_online(self._tox_pointer, c_uint32(friend_number),
                                                           byref(tox_err_last_online))
        tox_err_last_online = tox_err_last_online.value
        if tox_err_last_online == TOX_ERR_FRIEND_GET_LAST_ONLINE['OK']:
            return result
        elif tox_err_last_online == TOX_ERR_FRIEND_GET_LAST_ONLINE['FRIEND_NOT_FOUND']:
            raise ArgumentError('No friend with the given number exists on the friend list.')

    # -----------------------------------------------------------------------------------------------------------------
    # Friend-specific state queries (can also be received through callbacks)
    # -----------------------------------------------------------------------------------------------------------------
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def friend_get_name(self, friend_number, name=None):
        """
        Write the name of the friend designated by the given friend number to a byte array.

        Call tox_friend_get_name_size to determine the allocation size for the `name` parameter.

        The data written to `name` is equal to the data received by the last `friend_name` callback.

        :param name: pointer (c_char_p) to a valid memory region large enough to store the friend's name.
        :return: name of the friend
        """
        if name is None:
            name = create_string_buffer(self.friend_get_name_size(friend_number))
        tox_err_friend_query = c_int()
        Tox.libtoxcore.tox_friend_get_name(self._tox_pointer, c_uint32(friend_number), name,
                                           byref(tox_err_friend_query))
        tox_err_friend_query = tox_err_friend_query.value
        if tox_err_friend_query == TOX_ERR_FRIEND_QUERY['OK']:
            return name.value.decode('utf8')
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['NULL']:
            raise ArgumentError('The pointer parameter for storing the query result (name, message) was NULL. Unlike'
                                ' the `_self_` variants of these functions, which have no effect when a parameter is'
                                ' NULL, these functions return an error in that case.')
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend_number did not designate a valid friend.')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def friend_get_status_message_size(self, friend_number):
        """
        Return the length of the friend's status message. If the friend number is invalid, the return value is SIZE_MAX.

        :return: length of the friend's status message
        """
        tox_err_friend_query = c_int()
        result = Tox.libtoxcore.tox_friend_get_status_message_size(self._tox_pointer, c_uint32(friend_number),
                                                                   byref(tox_err_friend_query))
        tox_err_friend_query = tox_err_friend_query.value
        if tox_err_friend_query == TOX_ERR_FRIEND_QUERY['OK']:
            return result
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['NULL']:
            raise ArgumentError('The pointer parameter for storing the query result (name, message) was NULL. Unlike'
                                ' the `_self_` variants of these functions, which have no effect when a parameter is'
                                ' NULL, these functions return an error in that case.')
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend_number did not designate a valid friend.')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def friend_get_status(self, friend_number):
        """
        Return the friend's user status (away/busy/...). If the friend number is invalid, the return value is
        unspecified.

        The status returned is equal to the last status received through the `friend_status` callback.

        :return: TOX_USER_STATUS
        """
        tox_err_friend_query = c_int()
        result = Tox.libtoxcore.tox_friend_get_status(self._tox_pointer, c_uint32(friend_number),
                                                      byref(tox_err_friend_query))
        tox_err_friend_query = tox_err_friend_query.value
        if tox_err_friend_query == TOX_ERR_FRIEND_QUERY['OK']:
            return result
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['NULL']:
            raise ArgumentError('The pointer parameter for storing the query result (name, message) was NULL. Unlike'
                                ' the `_self_` variants of these functions, which have no effect when a parameter is'
                                ' NULL, these functions return an error in that case.')
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend_number did not designate a valid friend.')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def friend_get_connection_status(self, friend_number):
        """
        Check whether a friend is currently connected to this client.

        The result of this function is equal to the last value received by the `friend_connection_status` callback.

        :param friend_number: The friend number for which to query the connection status.
        :return: the friend's connection status (TOX_CONNECTION) as it was received through the
        `friend_connection_status` event.
        """
        tox_err_friend_query = c_int()
        result = Tox.libtoxcore.tox_friend_get_connection_status(self._tox_pointer, c_uint32(friend_number),
                                                                 byref(tox_err_friend_query))
        tox_err_friend_query = tox_err_friend_query.value
        if tox_err_friend_query == TOX_ERR_FRIEND_QUERY['OK']:
            return result
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['NULL']:
            raise ArgumentError('The pointer parameter for storing the query result (name, message) was NULL. Unlike'
                                ' the `_self_` variants of these functions, which have no effect when a parameter is'
                                ' NULL, these functions return an error in that case.')
        elif tox_err_friend_query == TOX_ERR_FRIEND_QUERY['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend_number did not designate a valid friend.')
项目:filebot    作者:toxygen-project    | 项目源码 | 文件源码
def self_set_typing(self, friend_number, typing):
        """
        Set the client's typing status for a friend.

        The client is responsible for turning it on or off.

        :param friend_number: The friend to which the client is typing a message.
        :param typing: The typing status. True means the client is typing.
        :return: True on success.
        """
        tox_err_set_typing = c_int()
        result = Tox.libtoxcore.tox_self_set_typing(self._tox_pointer, c_uint32(friend_number),
                                                    c_bool(typing), byref(tox_err_set_typing))
        tox_err_set_typing = tox_err_set_typing.value
        if tox_err_set_typing == TOX_ERR_SET_TYPING['OK']:
            return bool(result)
        elif tox_err_set_typing == TOX_ERR_SET_TYPING['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend number did not designate a valid friend.')
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def _coord_byval(coord):
    """
    Turns a COORD object into a c_long.
    This will cause it to be passed by value instead of by reference. (That is what I think at least.)

    When runing ``ptipython`` is run (only with IPython), we often got the following error::

         Error in 'SetConsoleCursorPosition'.
         ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
     argument 2: <class 'TypeError'>: wrong type

    It was solved by turning ``COORD`` parameters into a ``c_long`` like this.

    More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
    """
    return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)


#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def _winapi(self, func, *a, **kw):
        """
        Flush and call win API function.
        """
        self.flush()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
            self.LOG.flush()

        try:
            return func(*a, **kw)
        except ArgumentError as e:
            if _DEBUG_RENDER_OUTPUT:
                self.LOG.write(('    Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8'))
项目:inventwithpython_pysdl2    作者:rswinkle    | 项目源码 | 文件源码
def test_SpriteFactory_create_software_sprite(self):
        factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)
        for w in range(0, 100):
            for h in range(0, 100):
                for bpp in (1, 4, 8, 12, 15, 16, 24, 32):
                    sprite = factory.create_software_sprite((w, h), bpp)
                    self.assertIsInstance(sprite, sdl2ext.SoftwareSprite)

        #self.assertRaises(ValueError, factory.create_software_sprite, (-1,-1))
        #self.assertRaises(ValueError, factory.create_software_sprite, (-10,5))
        #self.assertRaises(ValueError, factory.create_software_sprite, (10,-5))
        self.assertRaises(TypeError, factory.create_software_sprite, size=None)
        self.assertRaises(sdl2ext.SDLError, factory.create_software_sprite,
                          size=(10, 10), bpp=-1)
        self.assertRaises(TypeError, factory.create_software_sprite, masks=5)
        self.assertRaises((ArgumentError, TypeError),
                          factory.create_software_sprite, size=(10, 10),
                          masks=(None, None, None, None))
        self.assertRaises((ArgumentError, TypeError),
                          factory.create_software_sprite, size=(10, 10),
                          masks=("Test", 1, 2, 3))
        dogc()
项目:inventwithpython_pysdl2    作者:rswinkle    | 项目源码 | 文件源码
def test_SpriteFactory_from_image(self):
        window = sdl2ext.Window("Test", size=(1, 1))
        renderer = sdl2ext.Renderer(window)
        tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
        sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)

        for suffix in ("tif", "png", "jpg"):
            imgname = RESOURCES.get_path("surfacetest.%s" % suffix)
            tsprite = tfactory.from_image(imgname)
            self.assertIsInstance(tsprite, sdl2ext.TextureSprite)
            ssprite = sfactory.from_image(imgname)
            self.assertIsInstance(ssprite, sdl2ext.SoftwareSprite)

        for factory in (tfactory, sfactory):
            self.assertRaises((ArgumentError, ValueError),
                              factory.from_image, None)
            #self.assertRaises((IOError, SDLError),
            #                  factory.from_image, "banana")
            if not _ISPYPY:
                self.assertRaises(ArgumentError, factory.from_image, 12345)
        dogc()
项目:inventwithpython_pysdl2    作者:rswinkle    | 项目源码 | 文件源码
def test_SpriteFactory_from_surface(self):
        window = sdl2ext.Window("Test", size=(1, 1))
        renderer = sdl2ext.Renderer(window)
        tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
        sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)

        sf = SDL_CreateRGBSurface(0, 10, 10, 32, 0, 0, 0, 0)
        tsprite = tfactory.from_surface(sf.contents)
        self.assertIsInstance(tsprite, sdl2ext.TextureSprite)
        ssprite = sfactory.from_surface(sf.contents)
        self.assertIsInstance(ssprite, sdl2ext.SoftwareSprite)
        SDL_FreeSurface(sf)

        for factory in (tfactory, sfactory):
            self.assertRaises((sdl2ext.SDLError, AttributeError, ArgumentError,
                               TypeError), factory.from_surface, None)
            self.assertRaises((AttributeError, ArgumentError, TypeError),
                              factory.from_surface, "test")
            # TODO: crashes pypy 2.0
            #self.assertRaises((AttributeError, ArgumentError, TypeError),
            #                  factory.from_surface, 1234)
        dogc()
项目:inventwithpython_pysdl2    作者:rswinkle    | 项目源码 | 文件源码
def test_SDL_GetAudioDriver(self):
        founddummy = False
        drivercount = audio.SDL_GetNumAudioDrivers()
        for index in range(drivercount):
            drivername = audio.SDL_GetAudioDriver(index)
            self.assertIsInstance(drivername, (str, bytes))
            if drivername == b"dummy":
                founddummy = True
        self.assertTrue(founddummy, "could not find dummy driver")
        # self.assertRaises(SDLError, audio.SDL_GetAudioDriver, -1)
        # self.assertRaises(SDLError, audio.get_audio_driver,
        #                  drivercount + 1)
        self.assertRaises((ctypes.ArgumentError, TypeError),
                          audio.SDL_GetAudioDriver, "Test")
        self.assertRaises((ctypes.ArgumentError, TypeError),
                          audio.SDL_GetAudioDriver, None)
项目:inventwithpython_pysdl2    作者:rswinkle    | 项目源码 | 文件源码
def test_SDL_AllocFreePalette(self):
        self.assertRaises((ArgumentError, TypeError), pixels.SDL_AllocPalette,
                          None)
        self.assertRaises((ArgumentError, TypeError), pixels.SDL_AllocPalette,
                          "Test")
        # self.assertRaises(ValueError, pixels.SDL_AllocPalette, -5)

        palette = pixels.SDL_AllocPalette(10)
        self.assertIsInstance(palette.contents, pixels.SDL_Palette)
        self.assertEqual(palette.contents.ncolors, 10)
        colors = palette.contents.colors
        for x in range(palette.contents.ncolors):
            self.assertIsInstance(colors[x], SDL_Color)
        colors[3].r = 70
        self.assertEqual(colors[3].r, 70)
        color = colors[4]
        self.assertEqual(colors[4].g, 255)
        self.assertEqual(color.g, 255)
        color.g = 33
        self.assertEqual(color.g, 33)
        self.assertEqual(colors[4].g, 33)
        pixels.SDL_FreePalette(palette)
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def try_generate_stub_target(shellcode, argument_buffer, target, errcheck=None):
    if not windows.current_process.is_wow_64:
        raise ValueError("Calling execute_64bits_code_from_syswow from non-syswow process")
    native_caller = generate_64bits_execution_stub_from_syswow(shellcode)
    native_caller.errcheck = errcheck if errcheck is not None else target.errcheck
    # Generate the wrapper function that fill the argument_buffer
    expected_arguments_number = len(target.prototype._argtypes_)
    def wrapper(*args):
        if len(args) != expected_arguments_number:
            raise ValueError("{0} syswow accept {1} args ({2} given)".format(target.__name__, expected_arguments_number, len(args)))
        # Transform args (ctypes byref possibly) to int
        writable_args = []
        for i, value in enumerate(args):
            if not isinstance(value, (int, long)):
                try:
                    value = ctypes.cast(value, ctypes.c_void_p).value
                except ctypes.ArgumentError as e:
                    raise ctypes.ArgumentError("Argument {0}: wrong type <{1}>".format(i, type(value).__name__))
            writable_args.append(value)
        # Build buffer
        buffer = struct.pack("<" + "Q" * len(writable_args), *writable_args)
        ctypes.memmove(argument_buffer, buffer, len(buffer))
        # Copy origincal args in function, for errcheck if needed
        native_caller.current_original_args = args # TODO: THIS IS NOT THREAD SAFE
        return native_caller()
    wrapper.__name__ = "{0}<syswow64>".format(target.__name__,)
    wrapper.__doc__ = "This is a wrapper to {0} in 64b mode, it accept <{1}> args".format(target.__name__, expected_arguments_number)
    return wrapper
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def test_noctypes_argtype(self):
        import _ctypes_test
        from ctypes import CDLL, c_void_p, ArgumentError

        func = CDLL(_ctypes_test.__file__)._testfunc_p_p
        func.restype = c_void_p
        # TypeError: has no from_param method
        self.assertRaises(TypeError, setattr, func, "argtypes", (object,))

        class Adapter(object):
            def from_param(cls, obj):
                return None

        func.argtypes = (Adapter(),)
        self.assertEqual(func(None), None)
        self.assertEqual(func(object()), None)

        class Adapter(object):
            def from_param(cls, obj):
                return obj

        func.argtypes = (Adapter(),)
        # don't know how to convert parameter 1
        self.assertRaises(ArgumentError, func, object())
        self.assertEqual(func(c_void_p(42)), 42)

        class Adapter(object):
            def from_param(cls, obj):
                raise ValueError(obj)

        func.argtypes = (Adapter(),)
        # ArgumentError: argument 1: ValueError: 99
        self.assertRaises(ArgumentError, func, 99)


################################################################
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def test_ascii_strict(self):
        wcslen = self.wcslen
        ctypes.set_conversion_mode("ascii", "strict")
        # no conversions take place with unicode arguments
        self.assertEqual(wcslen(u"abc"), 3)
        self.assertEqual(wcslen(u"ab\u2070"), 3)
        # string args are converted
        self.assertEqual(wcslen("abc"), 3)
        self.assertRaises(ctypes.ArgumentError, wcslen, "ab")
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def test_ascii_replace(self):
        func = self.func
        ctypes.set_conversion_mode("ascii", "strict")
        self.assertEqual(func("abc"), "abc")
        self.assertEqual(func(u"abc"), "abc")
        self.assertRaises(ctypes.ArgumentError, func, u"ab")
项目:Liljimbo-Chatbot    作者:chrisjim316    | 项目源码 | 文件源码
def _coord_byval(coord):
    """
    Turns a COORD object into a c_long.
    This will cause it to be passed by value instead of by reference. (That is what I think at least.)

    When runing ``ptipython`` is run (only with IPython), we often got the following error::

         Error in 'SetConsoleCursorPosition'.
         ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
     argument 2: <class 'TypeError'>: wrong type

    It was solved by turning ``COORD`` parameters into a ``c_long`` like this.

    More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
    """
    return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)


#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
项目:Liljimbo-Chatbot    作者:chrisjim316    | 项目源码 | 文件源码
def _winapi(self, func, *a, **kw):
        """
        Flush and call win API function.
        """
        self.flush()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
            self.LOG.flush()

        try:
            return func(*a, **kw)
        except ArgumentError as e:
            if _DEBUG_RENDER_OUTPUT:
                self.LOG.write(('    Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8'))
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _coord_byval(coord):
    """
    Turns a COORD object into a c_long.
    This will cause it to be passed by value instead of by reference. (That is what I think at least.)

    When runing ``ptipython`` is run (only with IPython), we often got the following error::

         Error in 'SetConsoleCursorPosition'.
         ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
     argument 2: <class 'TypeError'>: wrong type

    It was solved by turning ``COORD`` parameters into a ``c_long`` like this.

    More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
    """
    return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)


#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _winapi(self, func, *a, **kw):
        """
        Flush and call win API function.
        """
        self.flush()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
            self.LOG.flush()

        try:
            return func(*a, **kw)
        except ArgumentError as e:
            if _DEBUG_RENDER_OUTPUT:
                self.LOG.write(('    Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8'))