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

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

项目:pi_gcs    作者:lbusoni    | 项目源码 | 文件源码
def testFromParamWithUInt16Array(self):
        class UInt16ArrayArg():
            def __init__(self, value):
                self._ret= (ctypes.c_uint16 * len(value))()
                for i in range(len(value)):
                    self._ret[i]= value[i]

            def from_param(self):
                return self._ret

            def array(self):
                return np.array([x for x in self._ret])


        xsubi1= UInt16ArrayArg([1, 2, 4092])
        self.assertTrue(np.allclose(np.array([1, 2, 4092]),
                                    xsubi1.array()))
        xsubi2= UInt16ArrayArg([1, 2, 4092])
        self.libc.nrand48.argtypes= [UInt16ArrayArg]
        ret1= self.libc.nrand48(xsubi1)
        ret2= self.libc.nrand48(xsubi2)
        self.assertEqual(ret1, ret2)
        self.assertFalse(np.allclose(np.array([1, 2, 4092]),
                                     xsubi1.array()))
项目:nifpga-python    作者:ni    | 项目源码 | 文件源码
def _return_ctype(self):
        """ Returns the associated ctype of a given datatype. """
        _datatype_ctype = {
            DataType.Bool: ctypes.c_uint8,
            DataType.I8: ctypes.c_int8,
            DataType.U8: ctypes.c_uint8,
            DataType.I16: ctypes.c_int16,
            DataType.U16: ctypes.c_uint16,
            DataType.I32: ctypes.c_int32,
            DataType.U32: ctypes.c_uint32,
            DataType.I64: ctypes.c_int64,
            DataType.U64: ctypes.c_uint64,
            DataType.Sgl: ctypes.c_float,
            DataType.Dbl: ctypes.c_double,
        }
        return _datatype_ctype[self]
项目: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).')
项目:nsf2x    作者:adb014    | 项目源码 | 文件源码
def __SetDLLReturnTypes(self):
        self.nnotesdll.NotesInitExtended.restype = ctypes.c_uint16
        self.nnotesdll.NotesTerm.restype = ctypes.c_uint16
        self.nnotesdll.NSFDbOpen.restype = ctypes.c_uint16
        self.nnotesdll.NSFDbClose.restype = ctypes.c_uint16
        self.nnotesdll.NSFNoteOpenExt.restype = ctypes.c_uint16
        self.nnotesdll.NSFNoteOpenByUNID.restype = ctypes.c_uint16
        self.nnotesdll.NSFNoteClose.restype = ctypes.c_uint16
        self.nnotesdll.NSFNoteCopy.restype = ctypes.c_uint16
        self.nnotesdll.NSFNoteGetInfo.restype = None
        self.nnotesdll.NSFNoteIsSignedOrSealed.restype = ctypes.c_bool
        self.nnotesdll.NSFNoteDecrypt.restype = ctypes.c_uint16
        self.nnotesdll.NSFItemDelete.restype = ctypes.c_uint16
        self.nnotesdll.NSFNoteHasMIMEPart.restype = ctypes.c_bool
        self.nnotesdll.NSFNoteHasMIME.restype = ctypes.c_bool
        self.nnotesdll.NSFNoteHasComposite.restype = ctypes.c_bool
        self.nnotesdll.MMCreateConvControls.restype = ctypes.c_uint16
        self.nnotesdll.MMDestroyConvControls.restype = ctypes.c_uint16
        self.nnotesdll.MMSetMessageContentEncoding.restype = None
        self.nnotesdll.MIMEConvertCDParts.restype = ctypes.c_uint16
        self.nnotesdll.MIMEConvertMIMEPartCC.restype = ctypes.c_uint16
        self.nnotesdll.NSFNoteUpdate.restype = ctypes.c_uint16
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_color():
    """Returns the color measurement as a tuple.

    The Color Click measures the intensity of the light by component and also
    the general intensity. The Color Click must be enabled before calling this
    function.

    Note: An exception is thrown if it fails to measure the color intensity.
    """
    clear = ctypes.c_uint16(0)
    red = ctypes.c_uint16(0)
    green = ctypes.c_uint16(0)
    blue = ctypes.c_uint16(0)
    ret = _LIB.color_click_get_color(ctypes.byref(clear),
                                     ctypes.byref(red),
                                     ctypes.byref(green),
                                     ctypes.byref(blue))
    if ret < 0:
        raise Exception("color click get color failed")

    return (clear.value, red.value, green.value, blue.value)
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_measure(mikrobus_index, use_spi):
    """Get a measure from Light Click.

    mikrobus_index: must be 0 (MIKROBUS_1) or 1 (MIKROBUS_2)

    use_spi: 1 if you use SPI (on board ADC) or 0 if you use ADC output
    directly.

    Note: An exception is thrown if it fails to get a measure from the Light
    Click.
    """
    measure = ctypes.c_uint16(0)
    ret = _LIB.light_click_get_measure(mikrobus_index,
                                       ctypes.byref(measure),
                                       use_spi)
    if ret < 0:
        raise Exception("light click get measure failed")
    return measure.value
项目: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).')
项目:pi_gcs    作者:lbusoni    | 项目源码 | 文件源码
def testArgsUInt16Array(self):
        xsubi1= (ctypes.c_uint16 * 3)(1, 2, 3)
        xsubi2= (ctypes.c_uint16 * 3)(1, 2, 3)
        ret1= self.libc.nrand48(xsubi1)
        ret2= self.libc.nrand48(xsubi2)
        self.assertEqual(ret1, ret2)
项目:openni-python    作者:severin-lemaignan    | 项目源码 | 文件源码
def get_buffer_as_uint16(self):
        return self.get_buffer_as(ctypes.c_uint16)
项目:sc-controller    作者:kozec    | 项目源码 | 文件源码
def keyEvent(self, key, val):
        """
        Generate a key or btn event

        @param int axis      key or btn event (KEY_* or BTN_*)
        @param int val        event value
        """
        self._lib.uinput_key(self._fd,
                             ctypes.c_uint16(key),
                             ctypes.c_int32(val))
项目:sc-controller    作者:kozec    | 项目源码 | 文件源码
def axisEvent(self, axis, val):
        """
        Generate a abs event (joystick/pad axes)

        @param int axis      abs event (ABS_*)
        @param int val        event value
        """
        self._lib.uinput_abs(self._fd,
                             ctypes.c_uint16(axis),
                             ctypes.c_int32(val))
项目:sc-controller    作者:kozec    | 项目源码 | 文件源码
def relEvent(self, rel, val):
        """
        Generate a rel event (move move)

        @param int rel        rel event (REL_*)
        @param int val        event value
        """
        self._lib.uinput_rel(self._fd,
                             ctypes.c_uint16(rel),
                             ctypes.c_int32(val))
项目:android3dblendermouse    作者:sketchpunk    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:microperi    作者:c0d3st0rm    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:microbit-gateway    作者:whaleygeek    | 项目源码 | 文件源码
def get_int_property(device_t, property):
    """ Search the given device for the specified string property

    @param device_t Device to search
    @param property String to search for.
    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
        kCFAllocatorDefault,
        property.encode("mac_roman"),
        kCFStringEncodingMacRoman
    )

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
        device_t,
        key,
        kCFAllocatorDefault,
        0
    );

    number = ctypes.c_uint16()

    if CFContainer:
        output = cf.CFNumberGetValue(CFContainer, 2, ctypes.byref(number))

    return number.value
项目:mb_remote    作者:whaleygeek    | 项目源码 | 文件源码
def get_int_property(device_t, property):
    """ Search the given device for the specified string property

    @param device_t Device to search
    @param property String to search for.
    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
        kCFAllocatorDefault,
        property.encode("mac_roman"),
        kCFStringEncodingMacRoman
    )

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
        device_t,
        key,
        kCFAllocatorDefault,
        0
    );

    number = ctypes.c_uint16()

    if CFContainer:
        output = cf.CFNumberGetValue(CFContainer, 2, ctypes.byref(number))

    return number.value
项目:gcodeplot    作者:arpruss    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:gcodeplot    作者:arpruss    | 项目源码 | 文件源码
def get_int_property(device_t, property):
    """ Search the given device for the specified string property

    @param device_t Device to search
    @param property String to search for.
    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
        kCFAllocatorDefault,
        property.encode("mac_roman"),
        kCFStringEncodingMacRoman
    )

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
        device_t,
        key,
        kCFAllocatorDefault,
        0
    );

    number = ctypes.c_uint16()

    if CFContainer:
        output = cf.CFNumberGetValue(CFContainer, 2, ctypes.byref(number))

    return number.value
项目:CalPack    作者:KronoSKoderS    | 项目源码 | 文件源码
def test_intfield_with_variable_bit_lenth(self):
        """
        This test verifies that setting an integer value of variable size is correctly exported to the to_bytes 
        function.  This also tests the ability to set a value for the packet upon instantiation.  
        """
        class int_packet_with_varied_sized_int_fields(models.Packet):
            int_field = models.IntField()
            int_field_signed = models.IntField(signed=True)
            int_field_4_bits = models.IntField(bit_len=4)
            int_field_12_bits = models.IntField(bit_len=12)

        pkt = int_packet_with_varied_sized_int_fields(
            int_field = 0xbeef,
            int_field_signed = 0xdead,
            int_field_4_bits = 0xa,
            int_field_12_bits = 0xbc
        )

        class c_pkt_struct(ctypes.Structure):
            _fields_ = (
                ('int_field', ctypes.c_uint16),
                ('int_field_signed', ctypes.c_int16),
                ('int_field_4_bits', ctypes.c_uint16, 4),
                ('int_field_12_bits', ctypes.c_uint16, 12),
            )

        c_pkt = c_pkt_struct()
        c_pkt.int_field = 0xbeef
        c_pkt.int_field_signed = 0xdead
        c_pkt.int_field_4_bits = 0xa
        c_pkt.int_field_12_bits = 0xbc

        b_str = ctypes.string_at(ctypes.addressof(c_pkt), ctypes.sizeof(c_pkt))

        self.assertEquals(b_str, pkt.to_bytes())
项目:bitio    作者:whaleygeek    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:flask-docjson    作者:elemepi    | 项目源码 | 文件源码
def validate_u16(val, p, key=None):
    if isinstance(val, int) and ctypes.c_uint16(val).value == val:
        return
    raise_validation_error(ErrInvalidU16, val, p, key=key)
项目:microbit-serial    作者:martinohanlon    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:idascripts    作者:ctfhacker    | 项目源码 | 文件源码
def struct(cls, ea, **sid):
        """Return the structure_t at address ``ea`` as a dict of ctypes.
        If the structure ``sid`` is specified, then use that specific structure type.
        """
        ea = interface.address.within(ea)

        if any(n in sid for n in ('sid','struc','structure','id')):
            res = sid['sid'] if 'sid' in sid else sid['struc'] if 'struc' in sid else sid['structure'] if 'structure' in sid else sid['id'] if 'id' in sid else None
            sid = res.id if isinstance(res, structure.structure_t) else res
        else:
            sid = type.structure.id(ea)

        st = structure.instance(sid, offset=ea)
        typelookup = {
            (int,-1) : ctypes.c_int8, (int,1) : ctypes.c_uint8,
            (int,-2) : ctypes.c_int16, (int,2) : ctypes.c_uint16,
            (int,-4) : ctypes.c_int32, (int,4) : ctypes.c_uint32,
            (int,-8) : ctypes.c_int64, (int,8) : ctypes.c_uint64,
            (float,4) : ctypes.c_float, (float,8) : ctypes.c_double,
        }

        res = {}
        for m in st.members:
            t, val = m.type, read(m.offset, m.size) or ''
            try:
                ct = typelookup[t]
            except KeyError:
                ty, sz = t if isinstance(t, __builtin__.tuple) else (m.type, 0)
                if isinstance(t, __builtin__.list):
                    t = typelookup[tuple(ty)]
                    ct = t*sz
                elif ty in (chr,str):
                    ct = ctypes.c_char*sz
                else:
                    ct = None
            finally:
                res[m.name] = val if any(_ is None for _ in (ct,val)) else ctypes.cast(ctypes.pointer(ctypes.c_buffer(val)),ctypes.POINTER(ct)).contents
        return res
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def get_int_property(device_t, property):
    """ Search the given device for the specified string property

    @param device_t Device to search
    @param property String to search for.
    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
        kCFAllocatorDefault,
        property.encode("mac_roman"),
        kCFStringEncodingMacRoman
    )

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
        device_t,
        key,
        kCFAllocatorDefault,
        0
    );

    number = ctypes.c_uint16()

    if CFContainer:
        output = cf.CFNumberGetValue(CFContainer, 2, ctypes.byref(number))

    return number.value
项目:xyppy    作者:theinternetftw    | 项目源码 | 文件源码
def write_char_with_color(char, fg_col, bg_col):
    set_color(fg_col, bg_col)
    if char == '\n':
        fill_to_eol_with_bg_color() # insure bg_col covers rest of line
    if is_windows and char != '\n':
        cbuf = CONSOLE_SCREEN_BUFFER_INFO()
        stdout_handle = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-11))
        ctypes.windll.kernel32.GetConsoleScreenBufferInfo(stdout_handle, ctypes.byref(cbuf))

        cursor = cbuf.dwCursorPosition
        # we only write on the left for status, so not touching cursor is fine
        written = ctypes.c_uint(0)
        char_attr = ctypes.c_uint16(cbuf.wAttributes)
        ctypes.windll.kernel32.WriteConsoleOutputAttribute(stdout_handle,
                                                           ctypes.byref(char_attr),
                                                           1,
                                                           cursor,
                                                           ctypes.byref(written))
        ctypes.windll.kernel32.WriteConsoleOutputCharacterA(stdout_handle,
                                                            ctypes.c_char_p(char),
                                                            1,
                                                            cursor,
                                                            ctypes.byref(written))
        if cursor.X < cbuf.srWindow.Right - 1:
            cursor.X += 1
            ctypes.windll.kernel32.SetConsoleCursorPosition(stdout_handle, cursor)
    else:
        sys.stdout.write(char)
项目:xyppy    作者:theinternetftw    | 项目源码 | 文件源码
def fill_to_eol_with_bg_color():
    if is_windows:
        cbuf = CONSOLE_SCREEN_BUFFER_INFO()
        stdout_handle = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-11))
        ctypes.windll.kernel32.GetConsoleScreenBufferInfo(stdout_handle, ctypes.byref(cbuf))

        cursor = cbuf.dwCursorPosition
        distance = cbuf.srWindow.Right - cursor.X
        # distance > 0 skips x == right to avoid default windows scroll-on-last-col-write behavior
        if distance > 0:
            cbuf = CONSOLE_SCREEN_BUFFER_INFO()
            stdout_handle = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-11))
            ctypes.windll.kernel32.GetConsoleScreenBufferInfo(stdout_handle, ctypes.byref(cbuf))

            cursor = cbuf.dwCursorPosition
            temp_cursor = COORD()

            written = ctypes.c_uint(0)
            char_attr = ctypes.c_uint16(cbuf.wAttributes)
            space = ctypes.c_char_p(' ')
            for i in range(distance):
                temp_cursor.X = cursor.X + i
                temp_cursor.Y = cursor.Y
                ctypes.windll.kernel32.WriteConsoleOutputAttribute(stdout_handle,
                                                                   ctypes.byref(char_attr),
                                                                   1,
                                                                   temp_cursor,
                                                                   ctypes.byref(written))
                ctypes.windll.kernel32.WriteConsoleOutputCharacterA(stdout_handle,
                                                                    space,
                                                                    1,
                                                                    temp_cursor,
                                                                    ctypes.byref(written))
    else:
        sys.stdout.write('\x1b[K') # insure bg_col covers rest of line
项目:pyikev2    作者:alejandro-perez    | 项目源码 | 文件源码
def _attribute_factory(code, data):
        class _Internal(NetlinkStructure):
            _fields_ = (
                ('len', c_uint16),
                ('code', c_uint16),
                ('data', type(data)),
            )

        return _Internal(code=code, len=sizeof(_Internal), data=data)
项目:mb_sdcard    作者:whaleygeek    | 项目源码 | 文件源码
def get_int_property(device_t, property):
    """ Search the given device for the specified string property

    @param device_t Device to search
    @param property String to search for.
    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
        kCFAllocatorDefault,
        property.encode("mac_roman"),
        kCFStringEncodingMacRoman
    )

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
        device_t,
        key,
        kCFAllocatorDefault,
        0
    );

    number = ctypes.c_uint16()

    if CFContainer:
        output = cf.CFNumberGetValue(CFContainer, 2, ctypes.byref(number))

    return number.value
项目:ddt4all    作者:cedricp    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:mt7687-serial-uploader    作者:will127534    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:crypto    作者:erose1337    | 项目源码 | 文件源码
def nonlinear_function2(state_and_constant):
    state, constant = state_and_constant
    state ^= constant        
    state += 1    
    state ^= word(state >> 8).value        
    state ^= word(state << 8).value
    state = word(~state).value
  #  state ^= word(state << 5).value
  #  state ^= word(state >> 3).value


    return (eight_bit_integer(state).value, state)
项目:crypto    作者:erose1337    | 项目源码 | 文件源码
def pbox(word):
    binary_word = cast(word, "binary")
    return int(''.join(binary_word[offset::8] for offset in range(8)), 2)
项目:RTT-Console    作者:dudulung    | 项目源码 | 文件源码
def read_16(self, addr):
        addr = ctypes.c_uint32(addr)
        data = ctypes.c_uint16()
        status = ctypes.c_byte()
        self.jlink.JLINKARM_ReadMemU16(addr, 1, ctypes.byref(data), ctypes.byref(status))
        return data.value
项目:RTT-Console    作者:dudulung    | 项目源码 | 文件源码
def write_16(self, addr, data):
        addr = ctypes.c_uint32(addr)
        data = ctypes.c_uint16(data)
        self.jlink.JLINKARM_WriteU16(addr, data)
项目:PPPLCalibrationFramework    作者:timothyhollabaugh    | 项目源码 | 文件源码
def init(self):
        """
        Does one time initing of the dll
        """
        self._background = np.zeros(dtype=ctypes.c_uint16, shape=(512, 640))
        self._clib = ctypes.cdll.LoadLibrary('pdvlib.dll')
        self._pdv = self._clib.pdv_open(b'pdv', 0)
        self._clib.pdv_multibuf(self._pdv, 4)

        self._clib.pdv_wait_image.restype = np.ctypeslib.ndpointer(
            dtype=ctypes.c_uint16, shape=(512, 1280))
        self._clib.pdv_image.restype = np.ctypeslib.ndpointer(
            dtype=ctypes.c_uint16, shape=(512, 1280))
项目:milisia-tox    作者:milisarge    | 项目源码 | 文件源码
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()
        print(address)
        result = Tox.libtoxcore.tox_bootstrap(self._tox_pointer, c_char_p(str.encode(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 callback_video_receive_frame(self, callback, user_data):
        """
        Set the callback for the `video_receive_frame` event. Pass None to unset.

        :param callback: Python function.
        The function type for the video_receive_frame callback.

        Should take
        toxAV           pointer (c_void_p) to ToxAV object,
        friend_number   The friend number (c_uint32) of the friend who sent a video frame.
        width           Width (c_uint16) of the frame in pixels.
        height          Height (c_uint16) of the frame in pixels.
        y
        u
        v               Plane data (POINTER(c_uint8)).
                            The size of plane data is derived from width and height where
                            Y = MAX(width, abs(ystride)) * height,
                            U = MAX(width/2, abs(ustride)) * (height/2) and
                            V = MAX(width/2, abs(vstride)) * (height/2).
        ystride
        ustride
        vstride         Strides data (c_int32). Strides represent padding for each plane that may or may not be present. You must
                        handle strides in your image processing code. Strides are negative if the image is bottom-up
                        hence why you MUST abs() it when calculating plane buffer size.
        user_data       pointer (c_void_p) to user_data
        :param user_data: pointer (c_void_p) to user data
        """
        c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_uint16, c_uint16, POINTER(c_uint8), POINTER(c_uint8),
                               POINTER(c_uint8), c_int32, c_int32, c_int32, c_void_p)
        self.video_receive_frame_cb = c_callback(callback)
        ToxAV.libtoxav.toxav_callback_video_receive_frame(self._toxav_pointer, self.video_receive_frame_cb, user_data)
项目:nsf2x    作者:adb014    | 项目源码 | 文件源码
def NSFNoteGetInfo(self, hNote, flags):
        self.__isLoaded()
        retval = ctypes.c_uint16(0)
        self.nnotesdll.NSFNoteGetInfo(hNote, flags, ctypes.byref(retval))
        return retval
项目:kotori    作者:daq-tools    | 项目源码 | 文件源码
def setup(self):

        # counter "ValueError: number of bits invalid for bit field"
        monkeypatch_pyclibrary_ctypes_struct()

        # register header- and library paths
        # https://pyclibrary.readthedocs.org/en/latest/get_started/configuration.html#specifying-headers-and-libraries-locations
        # TODO: this probably acts on a global basis; think about it
        if self.include_path:
            add_header_locations([self.include_path])
        if self.library_path:
            add_library_locations([self.library_path])

        # define extra types suitable for embedded use
        types = {
            'uint8_t': c_uint8,
            'uint16_t': c_uint16,
            'uint32_t': c_uint32,
            'int8_t': c_int8,
            'int16_t': c_int16,
            'int32_t': c_int32,
            }

        # TODO: this probably acts on a global basis; think about it
        if not (CParser._init or CLibrary._init):
            auto_init(extra_types=types)
项目:pyrealsense    作者:toinsson    | 项目源码 | 文件源码
def __init__(self, name='depth', width=640, height=480, fps=30):
        self.native = True
        self.stream = rs_stream.RS_STREAM_DEPTH
        self.format = rs_format.RS_FORMAT_Z16
        self.shape = (height, width)
        self.dtype = ctypes.c_uint16
        super(DepthStream, self).__init__(name, self.native, self.stream, width, height, self.format, fps)
项目:pyrealsense    作者:toinsson    | 项目源码 | 文件源码
def __init__(self, name='dac', width=640, height=480, fps=30):
        self.native = False
        self.stream = rs_stream.RS_STREAM_DEPTH_ALIGNED_TO_COLOR
        self.format = rs_format.RS_FORMAT_Z16
        self.shape = (height, width)
        self.dtype = ctypes.c_uint16
        super(DACStream, self).__init__(name, self.native, self.stream, width, height, self.format, fps)
项目:pyrealsense    作者:toinsson    | 项目源码 | 文件源码
def _get_pointcloud(self):
        ds = [s for s in self.streams if type(s) is DepthStream][0]

        e = ctypes.POINTER(rs_error)()
        lrs.rs_get_frame_data.restype = ndpointer(dtype=ctypes.c_uint16, shape=(ds.height, ds.width))
        depth = lrs.rs_get_frame_data(self.dev, rs_stream.RS_STREAM_DEPTH, ctypes.byref(e))

        pointcloud = np.zeros((ds.height * ds.width * 3), dtype=np.float32)

        # ugly fix for outliers
        depth[0, :2] = 0

        rsutilwrapper.deproject_depth(pointcloud, self.depth_intrinsics, depth, self.depth_scale)
        return pointcloud.reshape((ds.height, ds.width, 3))
项目:Jackal_Velodyne_Duke    作者:MengGuo    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:Jackal_Velodyne_Duke    作者:MengGuo    | 项目源码 | 文件源码
def get_int_property(device_type, property, cf_number_type):
    """
    Search the given device for the specified string property

    @param device_type Device to search
    @param property String to search for
    @param cf_number_type CFType number

    @return Python string containing the value, or None if not found.
    """
    key = cf.CFStringCreateWithCString(
            kCFAllocatorDefault,
            property.encode("mac_roman"),
            kCFStringEncodingMacRoman)

    CFContainer = iokit.IORegistryEntryCreateCFProperty(
            device_type,
            key,
            kCFAllocatorDefault,
            0)

    if CFContainer:
        if (cf_number_type == kCFNumberSInt32Type):
            number = ctypes.c_uint32()
        elif (cf_number_type == kCFNumberSInt16Type):
            number = ctypes.c_uint16()
        cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
        cf.CFRelease(CFContainer)
        return number.value
    return None
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_color():
    """Returns the rgb color measurement as a tuple.

    Note: An exception is thrown if it fails to get a measurement from
    the click.
    """
    red = ctypes.c_uint16(0)
    green = ctypes.c_uint16(0)
    blue = ctypes.c_uint16(0)
    ret = _LIB.color2_click_get_color(ctypes.byref(red),
                                      ctypes.byref(green),
                                      ctypes.byref(blue))
    if ret < 0:
        raise Exception("color2 click get color failed")
    return (red.value, green.value, blue.value)
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_measure(mikrobus_index):
    """Measure the CO concentration in the air using the CO click.

    mikrobus_index: must be 0 (MIKROBUS_1) or 1 (MIKROBUS_2)

    Note: An exception is thrown if it fails to communicate with the CO click.
    """
    value = ctypes.c_uint16(0)
    ret = _LIB.co_click_get_measure(mikrobus_index, ctypes.byref(value))
    if ret < 0:
        raise Exception("co click read ppm failed")
    return value.value
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_measure():
    """Read 12bit measurement from LIN Hall Click.

    Note: An exception is thrown if it fails.
    """
    measure = ctypes.c_uint16(0)
    ret = _LIB.lin_hall_click_get_measure(ctypes.byref(measure))
    if ret < 0:
        raise Exception("LIN HALL get measure failed")
    return measure.value
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_raw_value(channel):
    """Read raw value from ADC Click in range 0..4095

    channel: must be in range 0-3. Channel 2 is not available on Ci40.

    Note: An exception is thrown if it fails to communicate with the click.
    """
    value = ctypes.c_uint16(0)
    ret = _LIB.adc_click_get_raw_value(channel, ctypes.byref(value))
    if ret < 0:
        raise Exception("adc click get raw value failed")
    return value.value
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_measure(mikrobus_index):
    """Returns a 16-bit integer from the Accel Click.

    mikrobus_index: must be 0 (MIKROBUS_1) or 1 (MIKROBUS_2)

    Note: An exception is thrown if it fails to get a measure from the click.
    """
    measure = ctypes.c_uint16(0)
    ret = _LIB.alcohol_click_get_measure(mikrobus_index, ctypes.byref(measure))
    if ret < 0:
        raise Exception("alcohol click get measure failed")
    return measure.value