示例#1
0
    def __init__(self, lib_location='Tobii.EyeX.Client.dll'):

        self.eyex_dll = c.cdll.LoadLibrary(lib_location)

        self.latest_sample = None

        self.interactor_snapshot = c.c_voidp()
        self.context = c.c_voidp()
        self.interactor_id = "3425g"

        event_handler_ticket = c.c_int(0)
        connection_state_changed_ticket = c.c_int(0)

        self._c_event_handler = tx.EVENT_HANDLER(self._event_handler)
        self._c_on_snapshot_committed = tx.ON_SNAPSHOT_COMMITTED(
            self._on_snapshot_committed)
        self._c_connection_handler = tx.CONNECTION_HANDLER(
            self._connection_handler)

        ret = self.eyex_dll.txInitializeEyeX(
            tx.TX_SYSTEMCOMPONENTOVERRIDEFLAGS.
            TX_SYSTEMCOMPONENTOVERRIDEFLAG_NONE, None, None, None)

        ret = self.eyex_dll.txCreateContext(c.byref(self.context), tx.TX_FALSE)
        self._initialize_interactor_snapshot()
        ret = self.eyex_dll.txRegisterConnectionStateChangedHandler(
            self.context, c.byref(connection_state_changed_ticket),
            self._c_connection_handler, None)

        ret = self.eyex_dll.txRegisterEventHandler(
            self.context, c.byref(event_handler_ticket), self._c_event_handler,
            None)
        ret = self.eyex_dll.txEnableConnection(self.context)
示例#2
0
        def test_get_non_code(self):
            f = self.get_func()

            self.assertRaises(SystemError, SetExtra, 42, FREE_INDEX,
                              ctypes.c_voidp(100))
            self.assertRaises(SystemError, GetExtra, 42, FREE_INDEX,
                              ctypes.c_voidp(100))
示例#3
0
文件: test_code.py 项目: 1st1/cpython
        def test_get_non_code(self):
            f = self.get_func()

            self.assertRaises(SystemError, SetExtra, 42, FREE_INDEX,
                              ctypes.c_voidp(100))
            self.assertRaises(SystemError, GetExtra, 42, FREE_INDEX,
                              ctypes.c_voidp(100))
示例#4
0
    def on_paint(self, event):

        # Technically, we would only need to set u_time on every draw,
        # because the program is enabled at the beginning and never disabled.
        # In vispy, the program is re-enabled at each draw though and we
        # want to keep the code similar.

        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        # Activate program  and texture
        gl.glUseProgram(self._prog_handle)
        gl.glBindTexture(gl.GL_TEXTURE_2D, self._tex_handle)

        # Update VBO
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._vbo_handle)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, vertex_data.nbytes, vertex_data,
                        gl.GL_DYNAMIC_DRAW)

        # Set attributes (again, the loc can be cached)
        loc = gl.glGetAttribLocation(self._prog_handle,
                                     'a_lifetime'.encode('utf-8'))
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 1, gl.GL_FLOAT, False, 7 * 4,
                                 ctypes.c_voidp(0))
        #
        loc = gl.glGetAttribLocation(self._prog_handle,
                                     'a_startPosition'.encode('utf-8'))
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, 7 * 4,
                                 ctypes.c_voidp(1 * 4))
        #
        loc = gl.glGetAttribLocation(self._prog_handle,
                                     'a_endPosition'.encode('utf-8'))
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, 7 * 4,
                                 ctypes.c_voidp(4 * 4))
        #
        loc = gl.glGetUniformLocation(self._prog_handle,
                                      'u_color'.encode('utf-8'))
        gl.glUniform4f(loc, *self._color)

        # Set unforms
        loc = gl.glGetUniformLocation(self._prog_handle,
                                      'u_time'.encode('utf-8'))
        gl.glUniform1f(loc, time.time() - self._starttime)
        #
        loc = gl.glGetUniformLocation(self._prog_handle,
                                      'u_centerPosition'.encode('utf-8'))
        gl.glUniform3f(loc, *self._centerpos)

        # Draw
        gl.glDrawArrays(gl.GL_POINTS, 0, N)

        # New explosion?
        if time.time() - self._starttime > 1.5:
            self._new_explosion()

        # Redraw as fast as we can
        self.update()
示例#5
0
 def test_get_set(self):
     f = self.get_func()
     extra = ctypes.c_voidp()
     SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200))
     SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300))
     self.assertEqual(LAST_FREED, 200)
     extra = ctypes.c_voidp()
     GetExtra(f.__code__, FREE_INDEX, extra)
     self.assertEqual(extra.value, 300)
     del f
示例#6
0
 def on_paint(self):
     
     # Technically, we would only need to set u_time on every draw,
     # because the program is enabled at the beginning and never disabled.
     # In vispy, the program is re-enabled at each draw though and we
     # want to keep the code similar.
     
     gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
     
     # Activate program  and texture
     gl.glUseProgram(self._prog_handle)
     gl.glBindTexture(gl.GL_TEXTURE_2D, self._tex_handle)
     
     # Update VBO
     gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._vbo_handle)
     gl.glBufferData(gl.GL_ARRAY_BUFFER, vertex_data.nbytes, vertex_data, gl.GL_DYNAMIC_DRAW)
     
     # Set attributes (again, the loc can be cached)
     loc = gl.glGetAttribLocation(self._prog_handle, 'a_lifetime')
     gl.glEnableVertexAttribArray(loc)
     gl.glVertexAttribPointer(loc, 1, gl.GL_FLOAT, False, 7*4, ctypes.c_voidp(0))
     #
     loc = gl.glGetAttribLocation(self._prog_handle, 'a_startPosition')
     gl.glEnableVertexAttribArray(loc)
     gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, 7*4, ctypes.c_voidp(1*4))
     #
     loc = gl.glGetAttribLocation(self._prog_handle, 'a_endPosition')
     gl.glEnableVertexAttribArray(loc)
     gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, 7*4, ctypes.c_voidp(4*4))
     #
     loc = gl.glGetUniformLocation(self._prog_handle, 'u_color')
     gl.glUniform4f(loc, *self._color)
     
     # Set unforms
     loc = gl.glGetUniformLocation(self._prog_handle, 'u_time')
     gl.glUniform1f(loc, time.time()-self._starttime)
     #
     loc = gl.glGetUniformLocation(self._prog_handle, 'u_centerPosition')
     gl.glUniform3f(loc, *self._centerpos)
     
     # Draw
     gl.glDrawArrays(gl.GL_POINTS, 0, N)
     
     # Swap buffers
     glut.glutSwapBuffers()
     
     # New explosion?
     if time.time() - self._starttime > 1.5:
         self._new_explosion()
         
     # Redraw 
     glut.glutPostRedisplay()
示例#7
0
 def set_val(self, nval):
     """
     @param nval: set to nval.
     @type nval: int
     """
     oldv = ctypes.c_int(0)
     sizeo = ctypes.c_int(ctypes.sizeof(oldv))
     newv = ctypes.c_int(nval)
     sizen = ctypes.c_int(ctypes.sizeof(newv))
     LIBC.sysctl(self._attr, 3, ctypes.c_voidp(ctypes.addressof(oldv)),
                 ctypes.addressof(sizeo),
                 ctypes.c_voidp(ctypes.addressof(newv)),
                 ctypes.addressof(sizen))
示例#8
0
文件: test_code.py 项目: 1st1/cpython
        def test_get_set(self):
            # Test basic get/set round tripping.
            f = self.get_func()

            extra = ctypes.c_voidp()

            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200))
            # reset should free...
            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300))
            self.assertEqual(LAST_FREED, 200)

            extra = ctypes.c_voidp()
            GetExtra(f.__code__, FREE_INDEX, extra)
            self.assertEqual(extra.value, 300)
            del f
示例#9
0
        def test_get_set(self):
            # Test basic get/set round tripping.
            f = self.get_func()

            extra = ctypes.c_voidp()

            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200))
            # reset should free...
            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300))
            self.assertEqual(LAST_FREED, 200)

            extra = ctypes.c_voidp()
            GetExtra(f.__code__, FREE_INDEX, extra)
            self.assertEqual(extra.value, 300)
            del f
示例#10
0
    def __init__(self, params):
        self.ref = ct.c_voidp()
        self.params = params
        assert(len(params.qoi_x0) >= params.qoi_dim), "x0 should have d dimension"
        #print("---------", d, a0, f0, nu, L, x0, sigma)
        example = 0
        if params.qoi_example == 'sf-matern':
            a, b = 0, 1
            example = 1
        elif params.qoi_example == 'sf-matern-full':
            a, b = 0, 1
            example = 0
        elif params.qoi_example == 'sf-kink':
            a, b = -1, 1
            example = 2
        else:
            raise ValueError('qoi_example is invalid')

        __lib__.SFieldCreate(ct.byref(self.ref),
                             example, a, b,
                             params.qoi_dim, params.qoi_a0,
                             params.qoi_f0, params.qoi_df_nu,
                             params.qoi_df_L, params.qoi_df_sig,
                             params.qoi_scale, params.qoi_x0,
                             params.qoi_sigma)
示例#11
0
def set_realtime(period, computation, constraint):
    if sys.platform != 'darwin':
        print('Warning: set_realtime not implemented on this platform')

    global lib
    lib = cdll.LoadLibrary('libSystem.B.dylib')
    lib.pthread_self.restype = c_voidp

    pthread_id = lib.pthread_self()
    thread_id = lib.pthread_mach_thread_np(c_voidp(pthread_id))

    print(pthread_id, thread_id)
    # TODO: conversion from float seconds to mach absolute time values (nanoseconds)

    ttcpolicy = thread_time_constraint_policy(period, computation, constraint,
                                              False)
    result = lib.thread_policy_set(c_uint(thread_id),
                                   THREAD_TIME_CONSTRAINT_POLICY,
                                   byref(ttcpolicy),
                                   THREAD_TIME_CONSTRAINT_POLICY_COUNT)

    assert result == 0

    tcpolicy = thread_precedence_policy(63)
    #result = lib.thread_policy_set(c_uint(thread_id), THREAD_PRECEDENCE_POLICY,
    #	byref(tcpolicy), THREAD_PRECEDENCE_POLICY_COUNT)

    assert result == 0
    import gc
    gc.disable()
示例#12
0
    def __init__(self):
        global camera_instance

        camera_instance = self
        self.continuous_acquire_run_flag = False
        self.img_list = []
        self.frameBuffer = None
        self.hcam = 0
        self.grabber = ctypes.c_voidp(0)
        self.dev = get_first_available_camera()  #tSdkCameraDevInfo()
        self.new_frame = False
        if self.dev:
            try:
                self.hcam = mvsdk.CameraInit(self.dev, -1, -1)
                self.cap = mvsdk.CameraGetCapability(self.hcam)
                self.monoCamera = (self.cap.sIspCapacity.bMonoSensor != 0)

                frameBufferSize = self.cap.sResolutionRange.iWidthMax * self.cap.sResolutionRange.iHeightMax * (
                    1 if self.monoCamera else 3)
                self.frameBuffer = mvsdk.CameraAlignMalloc(frameBufferSize, 16)
                mvsdk.CameraPlay(self.hcam)
                #mvsdk.CameraSetTriggerMode(self.hcam, 1)
                #mvsdk.CameraSetCallbackFunction(self.hcam, GrabImageCallback, 0)

            except mvsdk.CameraException as e:
                print("CameraInit Failed({}): {}".format(
                    e.error_code, e.message))
                return

        else:
            print(
                "mindvision_sdk.py - MindVisionCamera.__init__ - Error. No camera found!"
            )
示例#13
0
def imsavetoblob(img, filetype, flags=0):
    '''
    s = imsavetoblob(img, filetype, flags=0)

    Save `img` to a `str` object

    Parameters
    ----------
    img : ndarray
        input image
    filetype : str or integer
        A file name like string, used only to determine the file type.
        Alternatively, an integer flag (from FI_FORMAT).
    flags : integer, optional

    Returns
    -------
    s : str
        byte representation of `img` in format `filetype`
    '''
    if type(filetype) == str:
        ftype = _FI.FreeImage_GetFIFFromFilename(filetype)
    else:
        ftype = filetype
    try:
        bitmap, fi_type = _array_to_bitmap(img)
        mem = _FI.FreeImage_OpenMemory(0,0)
        if not _FI.FreeImage_SaveToMemory(ftype, bitmap, mem, flags):
            raise IOError('mahotas.freeimage.imsavetoblob: Cannot save to memory.')
        data = ctypes.c_voidp()
        size = ctypes.c_int()
        _FI.FreeImage_AcquireMemory(mem, ctypes.byref(data), ctypes.byref(size))
        return ctypes.string_at(data, size)
    finally:
        _FI.FreeImage_CloseMemory(mem)
示例#14
0
 def Run(self, sources, umix=None):
     if not isinstance(sources, np.ndarray):
         print "Sources must be an instance of numpy.ndarray"
         return None if umix is None else None,None
     if len(sources.shape) != 2:
         print "Sources must be a 2D array"
         return None if umix is None else None,None
     Dx = sources.astype(np.uint16)
     ns, nc = sources.shape
     if ns < nc:
         Dx = Dx.T.copy()
         nc, ns = ns, nc
     Mx = c_voidp(None)
     if umix is None:
         umix = False
     elif isinstance(umix, bool):
         pass
     elif not isinstance(umix, np.ndarray):
         umix = False
     elif umix.shape[0] == nc and umix.shape[1] == nc:
         Mx = umix
         umix = True
     else:
         print "Number of components and Mixing matrix are mismatch"
         return None, None
     if umix:
         Rx = self.Separate(Mx, Dx, nc, ns)
         return Rx, Dx
     return self.Estimate(Dx, nc, ns)
示例#15
0
    def __init__(self, nlp_init):
        """ 
        Class for solving a DAE initialization problem my means of optimization 
        using IPOPT.
        
        Parameters::
        
            nlp_init -- 
                The NLPInitialization object.
        """

        self._nlp_init = nlp_init
        self._ipopt_init = ct.c_voidp()

        self._set_initOpt_typedefs()

        try:
            assert self._nlp_init._jmi_model._dll.jmi_init_opt_ipopt_new(
                byref(self._ipopt_init), self._nlp_init._jmi_init_opt) == 0, \
                   "jmi_init_opt_ipopt_new returned non-zero"
        except AttributeError as e:
            raise JMIException(
                "Can not create InitializationOptimizer object. \ "
                "Please recompile model with target='ipopt")

        assert self._ipopt_init.value is not None, \
               "jmi struct not returned correctly"
示例#16
0
 def __repr__(self):
     p = ctypes.c_voidp()
     windll.ole32.StringFromCLSID(byref(self), byref(p))
     ret = ctypes.c_wchar_p(p.value).value
     windll.ole32.CoTaskMemFree.argtypes = [ctypes.c_voidp]
     windll.ole32.CoTaskMemFree(p.value)
     return ret
示例#17
0
def _main(display):
    root = xlib.XDefaultRootWindow(display)
    mousex = c_int()
    mousey = c_int()
    # pointer for unused return values 
    unused_int = c_int()
    # likewise, querypointer wants a window pointer to write to.  We don't
    # really want to create a new window, but this was the shortest way I
    # could think of to get the memory allocated.
    tmp_win = c_voidp(xlib.XCreateSimpleWindow(display, root, 0, 0, 1, 1,
                                               0, 0, 0))
    def resetMouse(x, y):
        xlib.XWarpPointer(display,None,root,0,0,0,0,x,y)

    def getMouse():
        xlib.XQueryPointer(display, root,
                           byref(tmp_win), byref(tmp_win),
                           byref(mousex), byref(mousey),
                           byref(unused_int),
                           byref(unused_int),
                           byref(unused_int))

    while 1:
        getMouse()
	time.sleep(1)
	resetMouse(x=10,y=10)
	getMouse()
	time.sleep(1)
	resetMouse(x=30,y=30)
	getMouse()
	time.sleep(1)
	resetMouse(x=60,y=60)
	
	"""
示例#18
0
    def recognize_async(self, multiple=False):
        cur_result = []

        def callback(text):
            cur_result.append(text)

        def alt_callback(text):
            if text == None:
                # send the event
                result = RecognitionResult(cur_result[0], cur_result[1:])
                event_args = RecognitionEventArgs(result)
                self.speech_recognized.fire(event_args)
                del cur_result[:]
            else:
                cur_result.append(text)

        stop_listening_handle = ctypes.c_voidp()

        # keep alive our function pointers on ourselves...
        self._async_callback = async_callback = _Recognize_Callback(callback)
        self._async_alt_callback = async_alt_callback = _Recognize_Callback(
            alt_callback)

        _RecognizeAsync(self._rec, multiple,
                        async_callback, async_alt_callback,
                        ctypes.byref(stop_listening_handle))
        self._async_handle = stop_listening_handle
示例#19
0
def nprocessors():
    try:
        try:
            try:
                try:
                    import multiprocessing
                    return multiprocessing.cpu_count()
                except:
                    # Mac OS
                    libc = ctypes.cdll.LoadLibrary(
                        ctypes.util.find_library('libc'))
                    v = ctypes.c_int(0)
                    size = ctypes.c_size_t(ctypes.sizeof(v))
                    libc.sysctlbyname('hw.ncpu',
                                      ctypes.c_voidp(ctypes.addressof(v)),
                                      ctypes.addressof(size), None, 0)
                    return v.value
            except:
                # Cygwin (Windows) and Linuxes
                # Could try sysconf(_SC_NPROCESSORS_ONLN) (LSB) next.  Instead, count processors in cpuinfo.
                s = open('/proc/cpuinfo', 'r').read()
                return s.replace(' ', '').replace('\t', '').count('processor:')
        except:
            # Native (Windows)
            return int(os.environ.get('NUMBER_OF_PROCESSORS'))
    except:
        return 1
 def PrepareMacNativeToolBar(self):
     """Extra toolbar setup for OS X native toolbar management."""
         
     # Load the frameworks
     import ctypes
     carbonLoc = '/System/Library/Carbon.framework/Carbon'
     coreLoc = '/System/Library/CoreFoundation.framework/CoreFoundation'
     self.carbon = ctypes.CDLL(carbonLoc)  # Also used in OnToolBarMacNative
     core = ctypes.CDLL(coreLoc)
     # Get a reference to the main window
     frame = self.MacGetTopLevelWindowRef()
     # Allocate a pointer to pass around
     p = ctypes.c_voidp()
     # Get a reference to the toolbar
     self.carbon.GetWindowToolbar(frame, ctypes.byref(p))
     toolbar = p.value
     # Get a reference to the array of toolbar items
     self.carbon.HIToolbarCopyItems(toolbar, ctypes.byref(p))
     # Get references to the toolbar items (note: separators count)
     self.macToolbarItems = [core.CFArrayGetValueAtIndex(p, i)
                             for i in xrange(self.toolbar.GetToolsCount())]
     # Set the native "selected" state on the first tab
     # 128 corresponds to kHIToolbarItemSelected (1 << 7)
     item = self.macToolbarItems[self.tabIndex]
     self.carbon.HIToolbarItemChangeAttributes(item, 128, 0)
示例#21
0
def set_realtime(period, computation, constraint):
	if sys.platform != 'darwin':
		print ('Warning: set_realtime not implemented on this platform')

	global lib
	lib = cdll.LoadLibrary('libSystem.B.dylib')
	lib.pthread_self.restype = c_voidp

	pthread_id = lib.pthread_self()
	thread_id = lib.pthread_mach_thread_np(c_voidp(pthread_id))

	print (pthread_id, thread_id)
	# TODO: conversion from float seconds to mach absolute time values (nanoseconds)


	ttcpolicy = thread_time_constraint_policy(period, computation, constraint, False)
	result = lib.thread_policy_set(c_uint(thread_id), THREAD_TIME_CONSTRAINT_POLICY,
		byref(ttcpolicy), THREAD_TIME_CONSTRAINT_POLICY_COUNT)

	assert result == 0

	tcpolicy = thread_precedence_policy(63)
	#result = lib.thread_policy_set(c_uint(thread_id), THREAD_PRECEDENCE_POLICY,
	#	byref(tcpolicy), THREAD_PRECEDENCE_POLICY_COUNT)

	assert result == 0
	import gc
	gc.disable()
示例#22
0
 def __init__(self, nlp_init):
     """ 
     Class for solving a DAE initialization problem my means of optimization 
     using IPOPT.
     
     Parameters::
     
         nlp_init -- 
             The NLPInitialization object.
     """
     
     self._nlp_init = nlp_init
     self._ipopt_init = ct.c_voidp()
     
     self._set_initOpt_typedefs()
     
     try:
         assert self._nlp_init._jmi_model._dll.jmi_init_opt_ipopt_new(
             byref(self._ipopt_init), self._nlp_init._jmi_init_opt) == 0, \
                "jmi_init_opt_ipopt_new returned non-zero"
     except AttributeError as e:
         raise JMIException(
             "Can not create InitializationOptimizer object. \ "
             "Please recompile model with target='ipopt")
     
     assert self._ipopt_init.value is not None, \
            "jmi struct not returned correctly"
示例#23
0
def get_image(width, height, cameraNum=0):
    
    #include full path or copy dll into same folder as .py script
    uEyeDll = ctypes.cdll.LoadLibrary("C:\Windows\SysWOW64\ueye_api.dll") 
    
    #connect camera
    cam = ctypes.c_uint32(cameraNum)
    hWnd = ctypes.c_voidp()
    msg = uEyeDll.is_InitCamera(ctypes.byref(cam),hWnd)
    ErrChk = uEyeDll.is_EnableAutoExit (cam, ctypes.c_uint(1))
    if ~ErrChk:
        print (' Camera Connected')
    IS_CM_SENSOR_RAW8  = ctypes.c_int(11)
    nRet = uEyeDll.is_SetColorMode(cam,IS_CM_SENSOR_RAW8)
    IS_SET_TRIGGER_SOFTWARE = ctypes.c_uint(0x1000)
    nRet = uEyeDll.is_SetExternalTrigger(cam, IS_SET_TRIGGER_SOFTWARE)
    
    
    #allocate memory
    width_py = width
    height_py = height
    pixels_py = 8
    
    width = ctypes.c_int(width_py) #convert python values into c++ integers
    height = ctypes.c_int(height_py) 
    bitspixel = ctypes.c_int(pixels_py)
    pcImgMem = ctypes.c_char_p() #create placeholder for image memory
    pid = ctypes.c_int()
    
    ErrChk = uEyeDll.is_AllocImageMem(cam, width, height,  bitspixel, 
                                    ctypes.byref(pcImgMem), ctypes.byref(pid))
    if ~ErrChk:
        print (' Success')
    else:
        print (' Memory allocation failed, no camera with value' + str(cam.value))
    
    
    # Get image data    
    uEyeDll.is_SetImageMem(cam, pcImgMem, pid)
#    nRed = uEyeDll.IS_GET_RED_GAIN(cam)
#    nGreen = uEyeDll.IS_GET_GREEN_GAIN(cam)
#    nBlue = uEyeDll.IS_GET_BLUE_GAIN(cam)
#    nMaster = uEyeDll.IS_GET_MASTER_GAIN(cam)
#    print nMaster, nRed, nGreen, nBlue
#    nMaster = ctypes.c_int(60)
#    ret = uEyeDll.is_SetHardwareGain(cam, nMaster, nRed, nGreen, nBlue)
#    print nMaster, nRed, nGreen, nBlue
    ImageData = np.ones((height_py,width_py),dtype=np.uint8)
    print ImageData

    #put these lines inside a while loop to return continous images to the array "ImageData"  
    print np.max(ImageData)
    uEyeDll.is_FreezeVideo (cam, ctypes.c_int(0x8000))  #IS_DONT_WAIT  = 0x0000, or IS_GET_LIVE = 0x8000
    uEyeDll.is_CopyImageMem (cam, pcImgMem, pid, ImageData.ctypes.data)
    print np.max(ImageData)

    uEyeDll.is_ExitCamera(cam)
    
    return ImageData
 def set_val(self, nval):
     """
     @param nval: set to nval.
     @type nval: int
     """
     oldv = ctypes.c_int(0)
     sizeo = ctypes.c_int(ctypes.sizeof(oldv))
     newv = ctypes.c_int(nval)
     sizen = ctypes.c_int(ctypes.sizeof(newv))
     LIBC.sysctl(
         self._attr,
         3,
         ctypes.c_voidp(ctypes.addressof(oldv)),
         ctypes.addressof(sizeo),
         ctypes.c_voidp(ctypes.addressof(newv)),
         ctypes.addressof(sizen),
     )
示例#25
0
文件: _interop.py 项目: Afelio/PTVS
    def GetUniqueDeviceName(self):        
        mem = ctypes.c_voidp()
        # Size is currently not used, and when we get the unique device name we need to free the memory.

        _NuiInstance._MSR_NuiGetPropsBlob(self, _PropsIndex.INDEX_UNIQUE_DEVICE_NAME, ctypes.byref(mem), None)
        res = ctypes.cast(mem, ctypes.c_wchar_p).value
        _SysFreeString(mem)
        return res
示例#26
0
 def set_heading(self, heading_deg):
     """
     Meant for use during initialization only
     """
     p = self.clib.state_ptr(ctypes.c_voidp(self.ptr)) 
     q = Quaternion.axis_angle(np.array([0, 0, 1.]), heading_deg*np.pi/180).as_ndarray()
     for n in range(4):
         p[n] = q[n]
示例#27
0
    def GetUniqueDeviceName(self):        
        mem = ctypes.c_voidp()
        # Size is currently not used, and when we get the unique device name we need to free the memory.

        _NuiInstance._MSR_NuiGetPropsBlob(self, _PropsIndex.INDEX_UNIQUE_DEVICE_NAME, ctypes.byref(mem), None)
        res = ctypes.cast(mem, ctypes.c_wchar_p).value
        _SysFreeString(mem)
        return res
示例#28
0
 def __init__(self):
     self.context = ctypes.c_voidp()
     self.guid = ctypes.c_uint()
     self.cameraInfo = Fc2CameraInfo()
     self.connected = False
     self.client = None
     self.lastImage = None
     self.imgRaw = None
示例#29
0
        def test_free_called(self):
            # Verify that the provided free function gets invoked
            # when the code object is cleaned up.
            f = self.get_func()

            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(100))
            del f
            self.assertEqual(LAST_FREED, 100)
示例#30
0
 def __init__(self):
     self.context = ctypes.c_voidp()
     self.guid = ctypes.c_uint()
     self.cameraInfo = Fc2CameraInfo()
     self.connected = False
     self.client = None
     self.lastImage = None
     self.imgRaw = None
示例#31
0
    def __init__(self, recognizer = None):
        self.speech_recognized = _event()
        self._async_handle = None

        if isinstance(recognizer, str):
            # TODO: Lookup by ID
            pass
        elif isinstance(recognizer, RecognizerInfo):
            rec = ctypes.c_voidp()
            _CreateRecognizer(recognizer._token, ctypes.byref(rec))
            self._rec = rec
        elif recognizer is None:
            rec = ctypes.c_voidp()
            _CreateRecognizer(None, ctypes.byref(rec))
            self._rec = rec
        else:
            raise TypeError('Bad type for recognizer: ' + repr(recognizer))
示例#32
0
文件: test_code.py 项目: 1st1/cpython
        def test_free_called(self):
            # Verify that the provided free function gets invoked
            # when the code object is cleaned up.
            f = self.get_func()

            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(100))
            del f
            self.assertEqual(LAST_FREED, 100)
示例#33
0
    def __init__(self, recognizer=None):
        self.speech_recognized = _event()
        self._async_handle = None

        if isinstance(recognizer, str):
            # TODO: Lookup by ID
            pass
        elif isinstance(recognizer, RecognizerInfo):
            rec = ctypes.c_voidp()
            _CreateRecognizer(recognizer._token, ctypes.byref(rec))
            self._rec = rec
        elif recognizer is None:
            rec = ctypes.c_voidp()
            _CreateRecognizer(None, ctypes.byref(rec))
            self._rec = rec
        else:
            raise TypeError('Bad type for recognizer: ' + repr(recognizer))
示例#34
0
    def __init__(self):
        self.uEyeDll = ctypes.cdll.LoadLibrary(
            "uEye_api.dll"
        )  # include full path or copy dll into same folder as .py script
        # connect camera
        self.cam = ctypes.c_uint32(0)
        self.hWnd = ctypes.c_voidp()
        # print(self.uEyeDll.is_ExitCamera(1))
        self.msg = self.uEyeDll.is_InitCamera(ctypes.byref(self.cam),
                                              self.hWnd)
        ErrChk = self.uEyeDll.is_EnableAutoExit(self.cam, ctypes.c_uint(1))
        print(ErrChk)
        if not ~ErrChk:
            print('Camera Not Connected')
            self.connected = False
        else:
            self.connected = True
        if self.connected:
            # color and display mode config
            # set to bitmap mode
            self.uEyeDll.is_SetDisplayMode(ctypes.c_uint32(0))
            # set colormap to 16 bit grey (probably)
            nRet = self.uEyeDll.is_SetColorMode(self.cam, ctypes.c_int(25))

            print(nRet)
            IS_SET_TRIGGER_SOFTWARE = ctypes.c_uint(0x1000)
            nRet = self.uEyeDll.is_SetExternalTrigger(self.cam,
                                                      IS_SET_TRIGGER_SOFTWARE)

            # allocate memory
            width_py = 2048
            height_py = 1088
            pixels_py = 32

            width = ctypes.c_int(
                width_py)  # convert python values into c++ integers
            height = ctypes.c_int(height_py)
            bitspixel = ctypes.c_int(pixels_py)
            self.pcImgMem = ctypes.c_char_p(
            )  # create placeholder for image memory
            self.pid = ctypes.c_int()

            ErrChk = self.uEyeDll.is_AllocImageMem(
                self.cam,
                width,
                height,
                bitspixel,
                ctypes.byref(self.pcImgMem),
                ctypes.byref(self.pid),
            )

            # Get image data
            ErrChk = self.uEyeDll.is_SetImageMem(self.cam, self.pcImgMem,
                                                 self.pid)
            self.ImageData = np.ones((height_py, width_py), dtype=np.uint32)
            self.fig = plt.figure()
            self.ax = self.fig.gca()
示例#35
0
 def CreateIPhreeqc(self):
     """
     Create a new IPhreeqc instance
     """
     error_code = self._CreateIPhreeqc(ctypes.c_voidp())
     if error_code < 0:
         self._RaisePhreeqcError(error_code)
     id = error_code
     return id
示例#36
0
 def __init__(self, **kwargs):
     dll_extension = os.name == 'nt' and 'dll' or 'so'
     self.dll = ctypes.CDLL('_mongoose.%s' % dll_extension)
     start = self.dll.mg_start
     self.ctx = ctypes.c_voidp(self.dll.mg_start()).value
     self.version = ctypes.c_char_p(self.dll.mg_version()).value
     self.callbacks = []
     for name, value in kwargs.iteritems():
         self.__setattr__(name, value)
示例#37
0
 def __init__(self):
     self.jpegtable_size = ctypes.c_uint16()
     self.buf = ctypes.c_voidp()
     self.jpegtables = None
     self.dir = 0
     self.levels = {}
     self.isBigTIFF = False
     self.barcode = ""
     self.tif = None
 def get_val(self):
     """
     @return: stored value.
     @rtype: int
     """
     oldv = ctypes.c_int(0)
     size = ctypes.c_int(ctypes.sizeof(oldv))
     LIBC.sysctl(self._attr, 3, ctypes.c_voidp(ctypes.addressof(oldv)), ctypes.addressof(size), None, 0)
     return oldv.value
示例#39
0
	def __init__(self, **kwargs):
		dll_extension = os.name == 'nt' and 'dll' or 'so'
		self.dll = ctypes.CDLL('_mongoose.%s' % dll_extension)
		start = self.dll.mg_start
		self.ctx = ctypes.c_voidp(self.dll.mg_start()).value
		self.version = ctypes.c_char_p(self.dll.mg_version()).value
		self.callbacks = []
		for name, value in kwargs.iteritems():
			self.__setattr__(name, value)
示例#40
0
    def testJMIInitDest(self):
        """Simple inititialization and destruction tests."""

        jmip = ctypes.c_voidp()
        assert self.dll.jmi_new(byref(jmip)) == 0, \
               "jmi_new returned non-zero"
        assert jmip.value is not None, \
               "jmi struct not returned correctly"
        assert self.dll.jmi_delete(jmip) == 0, \
               "jmi_delete failed"
示例#41
0
    def load_grammar(self, grammar):
        if isinstance(grammar, str):
            grammar_obj = Grammar(grammar)
        else:
            grammar_obj = grammar

        comGrammar = ctypes.c_voidp()
        _LoadGrammar(grammar_obj.filename, self._rec, ctypes.byref(comGrammar))
        grammar_obj._grammar = comGrammar
        return grammar_obj
示例#42
0
    def load_grammar(self, grammar):
        if isinstance(grammar, str):
            grammar_obj = Grammar(grammar)
        else:
            grammar_obj = grammar

        comGrammar = ctypes.c_voidp()
        _LoadGrammar(grammar_obj.filename, self._rec, ctypes.byref(comGrammar))
        grammar_obj._grammar = comGrammar
        return grammar_obj
示例#43
0
    def ecc256_open_context(self):
        self.log.debug( "ecc256_open_context" )

        context = c_voidp()
        result  = self.implementation.sgx_ecc256_open_context( byref( context ) )

        self.VerifyResult( result )
        self.log.debug( "ecc256_open_context: context = 0x%x" % context.value )

        return context
示例#44
0
 def add(self, *polynomials):
     handler = self._lib.additionCtor()
     for polynomial in polynomials:
         self._lib.additionAddSummand(
             ctypes.c_voidp(handler),
             ctypes.c_uint32(len(polynomial.coefficients())),
             polynomial.coefficients().ctypes.data_as(
                 ctypes.POINTER(ctypes.c_double)),
             polynomial.powers().ctypes.data_as(
                 ctypes.POINTER(ctypes.c_uint32)))
     terms = self._lib.additionTerms(ctypes.c_voidp(handler))
     out_coeffs = np.zeros(terms, dtype=np.float64)
     out_powers = np.zeros((terms, 3), dtype=np.uint32)
     self._lib.additionResult(
         ctypes.c_voidp(handler),
         out_coeffs.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
         out_powers.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
     self._lib.additionDtor(ctypes.c_voidp(handler))
     return self.polynomial_from_numpy(out_coeffs, out_powers)
示例#45
0
 def get_val(self):
     """
     @return: stored value.
     @rtype: int
     """
     oldv = ctypes.c_int(0)
     size = ctypes.c_int(ctypes.sizeof(oldv))
     LIBC.sysctl(self._attr, 3, ctypes.c_voidp(ctypes.addressof(oldv)),
                 ctypes.addressof(size), None, 0)
     return oldv.value
示例#46
0
 def __init__(self, params):
     self.ref = ct.c_voidp()
     self.params = params
     assert (len(params.qoi_x0) >=
             params.qoi_dim), "x0 should have d dimension"
     #print("---------", d, a0, f0, nu, L, x0, sigma)
     __lib__.SFieldCreate(ct.byref(self.ref), params.qoi_problem,
                          params.qoi_dim, params.qoi_a0, params.qoi_f0,
                          params.qoi_df_nu, params.qoi_df_L,
                          params.qoi_df_sig, params.qoi_scale,
                          params.qoi_x0, params.qoi_sigma)
示例#47
0
    def _event_handler(self, async_data, userParam):
        event = c.c_voidp()
        behavior = c.c_voidp()

        self.eyex_dll.txGetAsyncDataContent(async_data, c.byref(event))

        if self.eyex_dll.txGetEventBehavior(event, c.byref(behavior),
                                            1) == tx.TX_RESULT_OK:
            event_params = tx.TX_GAZEPOINTDATAEVENTPARAMS()
            if self.eyex_dll.txGetGazePointDataEventParams(
                    behavior, c.byref(event_params)) == tx.TX_RESULT_OK:
                sample = Sample(int(event_params.GazePointDataMode),
                                float(event_params.timestamp),
                                float(event_params.x), float(event_params.y))
                self.latest_sample = sample
                for callback in self.on_event:
                    callback(sample)
            self.eyex_dll.txReleaseObject(c.byref(behavior))

        self.eyex_dll.txReleaseObject(c.byref(event))
示例#48
0
 def sub(self, minuend, subtrahend):
     handler = self._lib.subtractionCtor(
         ctypes.c_uint32(len(minuend.coefficients())),
         minuend.coefficients().ctypes.data_as(
             ctypes.POINTER(ctypes.c_double)),
         minuend.powers().ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)),
         ctypes.c_uint32(len(subtrahend.coefficients())),
         subtrahend.coefficients().ctypes.data_as(
             ctypes.POINTER(ctypes.c_double)),
         subtrahend.powers().ctypes.data_as(ctypes.POINTER(
             ctypes.c_uint32)))
     terms = self._lib.subtractionTerms(ctypes.c_voidp(handler))
     out_coeffs = np.zeros(terms, dtype=np.float64)
     out_powers = np.zeros((terms, 3), dtype=np.uint32)
     self._lib.subtractionResult(
         ctypes.c_voidp(handler),
         out_coeffs.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
         out_powers.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
     self._lib.subtractionDtor(ctypes.c_voidp(handler))
     return self.polynomial_from_numpy(out_coeffs, out_powers)
示例#49
0
 def __init__(self, device = None):
     self._dmo = None
     dmo = ctypes.c_voidp()
     if device is None:
         from pykinect import nui
         
         device = nui.Runtime(nui.RuntimeOptions.uses_audio)
             
     _OpenKinectAudio(device._nui, ctypes.byref(dmo))
     self._dmo = dmo
     self._file = None
     self._device = device
示例#50
0
def glBufferData(target, data, usage):
    """ Data can be numpy array or the size of data to allocate.
    """
    if isinstance(data, int):
        size = data
        data = ctypes.c_voidp(0)
    else:
        if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
            data = data.copy('C')
        data_ = data
        size = data_.nbytes
        data = data_.ctypes.data
    res = _lib.glBufferData(target, size, data, usage)
示例#51
0
    def start(self, readStaleThreshold = 500):
        """Starts capturing audio from the Kinect sensor's microphone array into a buffer.   Returns a file-like object that represents the audio stream, which is in 16khz, 16 bit PCM format. 
        
readStaleThreshold: Specifies how long to retain data in the buffer (in milliseconds). If you do not read from the stream for longer than this "stale data" threshold value the DMO discards any buffered audio.

        """
        if self._file is not None:
            raise Exception('Capture already started')

        audio_stream = ctypes.c_voidp()
        _OpenAudioStream(self._dmo, ctypes.byref(audio_stream), readStaleThreshold)

        self._file = _AudioFile(audio_stream)
        return self._file
示例#52
0
 def __init__(self, params):
     self.ref = ct.c_voidp()
     self.params = params
     assert(len(params.qoi_x0) >= params.qoi_dim), "x0 should have d dimension"
     #print("---------", d, a0, f0, nu, L, x0, sigma)
     __lib__.SFieldCreate(ct.byref(self.ref), params.qoi_problem,
                          params.qoi_dim, params.qoi_a0,
                          params.qoi_f0,
                          params.qoi_df_nu,
                          params.qoi_df_L,
                          params.qoi_df_sig,
                          params.qoi_scale,
                          params.qoi_x0,
                          params.qoi_sigma)
def foo():
    # open
    libc.syscall(2, "/", 0) == 6

    # openat
    libc.syscall(257, 6, "tmp", 0, 0) == 7

    # malloc, if needed
    libc.malloc.restype = ctypes.c_voidp
    libc.malloc(2 ** 20) == 139650421612560

    fd = os.open("/", os.O_RDONLY)
    buf = 139650421612560

    # getdents64
    libc.syscall(217, fd, ctypes.c_voidp(buf), 2 ** 20) == 616  # bytes, eventually == 0, the end
示例#54
0
def nprocessors():
  try:
    try:
      # Mac OS
      libc=ctypes.cdll.LoadLibrary(ctypes.util.find_library('libc'))
      v=ctypes.c_int(0)
      size=ctypes.c_size_t(ctypes.sizeof(v))
      libc.sysctlbyname('hw.ncpu', ctypes.c_voidp(ctypes.addressof(v)), ctypes.addressof(size), None, 0)
      return v.value
    except:
      # Cygwin (Windows) and Linuxes
      # Could try sysconf(_SC_NPROCESSORS_ONLN) (LSB) next.  Instead, count processors in cpuinfo.
      s = open('/proc/cpuinfo', 'r').read()
      return s.replace(' ', '').replace('\t', '').count('processor:')
  except:
    return 1
示例#55
0
文件: thread.py 项目: X-N2O/pwntools
def _async_raise(tid, exc):
    if type(exc) != types.TypeType:
        raise TypeError('exception must be a type (vs. instance)')
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        ctypes.c_long(tid),
        ctypes.py_object(exc)
        )
    if res == 0:
        raise ValueError('invalid thread id')
    if res > 1:
        # must reset exception in affected threads
        ctypes.pythonapi.PyThreadState_SetAsyncExc(
            ctypes.c_long(tid),
            ctypes.c_voidp(0)
            )
        raise SystemError('PyThreadState_SetAsyncExc failed')
    def __init__(self, display, window_title=None):
        super(Cursor, self).__init__()
        self.display = display
        self.window_title = window_title

        self.root = xlib.XDefaultRootWindow(self.display)
        self.mousex = c_int()
        self.mousey = c_int()
        # pointer for unused return values
        self.unused_int = c_int()
        # likewise, querypointer wants a window pointer to write to.  We don't
        # really want to create a new window, but this was the shortest way I
        # could think of to get the memory allocated.
        self.tmp_win = c_voidp(xlib.XCreateSimpleWindow(
            self.display, self.root, 0, 0, 1, 1, 0, 0, 0
        ))
示例#57
0
    def _getJpegTables(self):
        """
        Get the common JPEG Huffman-coding and quantization tables.

        See http://www.awaresystems.be/imaging/tiff/tifftags/jpegtables.html
        for more information.

        :return: All Huffman and quantization tables, with JPEG table start
        markers.
        :rtype: bytes
        :raises: Exception
        """
        # TODO: does this vary with Z?

        # TIFFTAG_JPEGTABLES uses (uint32*, void**) output arguments
        # http://www.remotesensing.org/libtiff/man/TIFFGetField.3tiff.html

        tableSize = ctypes.c_uint32()
        tableBuffer = ctypes.c_voidp()

        libtiff_ctypes.libtiff.TIFFGetField.argtypes = \
            libtiff_ctypes.libtiff.TIFFGetField.argtypes[:2] + \
            [ctypes.POINTER(ctypes.c_uint32), ctypes.POINTER(ctypes.c_void_p)]
        if libtiff_ctypes.libtiff.TIFFGetField(
                self._tiffFile,
                libtiff_ctypes.TIFFTAG_JPEGTABLES,
                ctypes.byref(tableSize),
                ctypes.byref(tableBuffer)) != 1:
            raise IOTiffException('Could not get JPEG Huffman /'
                                  ' quantization tables')

        tableSize = tableSize.value
        tableBuffer = ctypes.cast(tableBuffer, ctypes.POINTER(ctypes.c_char))

        if tableBuffer[:2] != b'\xff\xd8':
            raise IOTiffException('Missing JPEG Start Of Image marker in'
                                  ' tables')
        if tableBuffer[tableSize - 2:tableSize] != b'\xff\xd9':
            raise IOTiffException('Missing JPEG End Of Image marker in tables')
        if tableBuffer[2:4] not in (b'\xff\xc4', b'\xff\xdb'):
            raise IOTiffException('Missing JPEG Huffman or Quantization Table'
                                  ' marker')

        # Strip the Start / End Of Image markers
        tableData = tableBuffer[2:tableSize - 2]
        return tableData
示例#58
0
文件: test_code.py 项目: 1st1/cpython
        def test_free_different_thread(self):
            # Freeing a code object on a different thread then
            # where the co_extra was set should be safe.
            f = self.get_func()
            class ThreadTest(threading.Thread):
                def __init__(self, f, test):
                    super().__init__()
                    self.f = f
                    self.test = test
                def run(self):
                    del self.f
                    self.test.assertEqual(LAST_FREED, 500)

            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(500))
            tt = ThreadTest(f, self)
            del f
            tt.start()
            tt.join()
            self.assertEqual(LAST_FREED, 500)
示例#59
0
文件: threadmap.py 项目: dlobue/nara
def nprocessors():
    try:
        try:
            try:
                # Mac OS
                libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("libc"))
                v = ctypes.c_int(0)
                size = ctypes.c_size_t(ctypes.sizeof(v))
                libc.sysctlbyname("hw.ncpu", ctypes.c_voidp(ctypes.addressof(v)), ctypes.addressof(size), None, 0)
                return v.value
            except:
                # Cygwin (Windows) and Linuxes
                # Could try sysconf(_SC_NPROCESSORS_ONLN) (LSB) next.  Instead, count processors in cpuinfo.
                s = open("/proc/cpuinfo", "r").read()
                return s.replace(" ", "").replace("\t", "").count("processor:")
        except:
            # Native (Windows)
            return int(os.environ.get("NUMBER_OF_PROCESSORS"))
    except:
        return 1
示例#60
0
def bufferData(target, data, usage):
    """ Data can be numpy array or the size of data to allocate.
    """
    # --- desktop angle
    if isinstance(data, int):
        size = data
        data = ctypes.c_voidp(0)
    else:
        if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
            data = data.copy('C')
        data_ = data
        size = data_.nbytes
        data = data_.ctypes.data
    ()
    # --- pyopengl
    if isinstance(data, int):
        size = data
        data = None
    else:
        size = data.nbytes
    GL.glBufferData(target, size, data, usage)