def _dgemm(trans_a, trans_b, m, n, k, a, b, c, alpha=1, beta=0, offseta=0, offsetb=0, offsetc=0): if a.size == 0 or b.size == 0: if beta == 0: c[:] = 0 else: c[:] *= beta return c assert(a.flags.c_contiguous) assert(b.flags.c_contiguous) assert(c.flags.c_contiguous) _np_helper.NPdgemm(ctypes.c_char(trans_b.encode('ascii')), ctypes.c_char(trans_a.encode('ascii')), ctypes.c_int(n), ctypes.c_int(m), ctypes.c_int(k), ctypes.c_int(b.shape[1]), ctypes.c_int(a.shape[1]), ctypes.c_int(c.shape[1]), ctypes.c_int(offsetb), ctypes.c_int(offseta), ctypes.c_int(offsetc), b.ctypes.data_as(ctypes.c_void_p), a.ctypes.data_as(ctypes.c_void_p), c.ctypes.data_as(ctypes.c_void_p), ctypes.c_double(alpha), ctypes.c_double(beta)) return c
def main(): file = open("/home/thany/QtCreator/build-HGE-Desktop-Debug/hge-sample.hge", "wb") scene = HgeScene() for obj in bpy.data.objects: if obj.type == OBJECT_TYPE_STRING_MESH: if prefix_check(obj.name, PREFIX_OCCLUSION_TEST): continue elif prefix_check(obj.name, PREFIX_SKIN): continue else: if obj.parent is not None: print("Error: Your static mesh must not have parent.") exit(0) geo = HgeGeometry(obj) scene.add_object(geo) elif obj.type == OBJECT_TYPE_STRING_ARMATURE: if prefix_check(obj.name, PREFIX_SKELETON): print("Skeleton Armature is not supported yet") exit(1) else: scene.add_object(HgeArmature(obj)) # Endian if sys.byteorder == 'little': file.write(ctypes.c_char(1)) else: file.write(ctypes.c_char(0)) scene.save(file) file.close() scene = None
def mds_command(self, mds_spec, args, input_data): """ :return 3-tuple of output status int, output status string, output data """ cmdarr = (c_char_p * len(args))(*args) outbufp = pointer(pointer(c_char())) outbuflen = c_long() outsp = pointer(pointer(c_char())) outslen = c_long() ret = self.libcephfs.ceph_mds_command(self.cluster, c_char_p(mds_spec), cmdarr, len(args), c_char_p(input_data), len(input_data), outbufp, byref(outbuflen), outsp, byref(outslen)) my_outbuf = outbufp.contents[:(outbuflen.value)] my_outs = outsp.contents[:(outslen.value)] if outbuflen.value: self.libcephfs.ceph_buffer_free(outbufp.contents) if outslen.value: self.libcephfs.ceph_buffer_free(outsp.contents) return (ret, my_outbuf, my_outs)
def _zgemm(trans_a, trans_b, m, n, k, a, b, c, alpha=1, beta=0, offseta=0, offsetb=0, offsetc=0): if a.size == 0 or b.size == 0: if beta == 0: c[:] = 0 else: c[:] *= beta return c assert(a.flags.c_contiguous) assert(b.flags.c_contiguous) assert(c.flags.c_contiguous) assert(a.dtype == numpy.complex128) assert(b.dtype == numpy.complex128) assert(c.dtype == numpy.complex128) _np_helper.NPzgemm(ctypes.c_char(trans_b.encode('ascii')), ctypes.c_char(trans_a.encode('ascii')), ctypes.c_int(n), ctypes.c_int(m), ctypes.c_int(k), ctypes.c_int(b.shape[1]), ctypes.c_int(a.shape[1]), ctypes.c_int(c.shape[1]), ctypes.c_int(offsetb), ctypes.c_int(offseta), ctypes.c_int(offsetc), b.ctypes.data_as(ctypes.c_void_p), a.ctypes.data_as(ctypes.c_void_p), c.ctypes.data_as(ctypes.c_void_p), (ctypes.c_double*2)(alpha.real, alpha.imag), (ctypes.c_double*2)(beta.real, beta.imag)) return c
def _dgemm(trans_a, trans_b, m, n, k, a, b, c, alpha=1, beta=0, offseta=0, offsetb=0, offsetc=0): assert a.flags.c_contiguous assert b.flags.c_contiguous assert c.flags.c_contiguous assert 0 < m < 2147483648 assert 0 < n < 2147483648 assert 0 < k < 2147483648 _np_helper.NPdgemm( ctypes.c_char(trans_b.encode("ascii")), ctypes.c_char(trans_a.encode("ascii")), ctypes.c_int(n), ctypes.c_int(m), ctypes.c_int(k), ctypes.c_int(b.shape[1]), ctypes.c_int(a.shape[1]), ctypes.c_int(c.shape[1]), ctypes.c_int(offsetb), ctypes.c_int(offseta), ctypes.c_int(offsetc), b.ctypes.data_as(ctypes.c_void_p), a.ctypes.data_as(ctypes.c_void_p), c.ctypes.data_as(ctypes.c_void_p), ctypes.c_double(alpha), ctypes.c_double(beta), ) return c
def gram_matrix(vecs): """Compute the dot product of each pair of vectors: G = V^T * V.""" vcount, vsize = vecs.shape if vecs.strides[1] != 8: raise ValueError('not contiguous') if akxconfig.use_mkl: gram = numpy.zeros((vcount, vcount)) mkl.cblas_dsyrk( c_int(102), c_int(121), c_int(112), c_int(vcount), c_int(vsize), c_double(1), vecs.ctypes.data_as(POINTER(c_double)), c_int(vecs.strides[0] / 8), c_double(0), gram.ctypes.data_as(POINTER(c_double)), c_int(vcount)) for i in xrange(vcount - 1): gram[i][i+1:] = gram.transpose()[i][i+1:] return gram elif akxconfig.use_acml: gram = numpy.zeros((vcount, vcount)) acml.dsyrk( c_char('U'), c_char('T'), c_int(vcount), c_int(vsize), c_double(1), vecs.ctypes.data_as(POINTER(c_double)), c_int(vecs.strides[0] / 8), c_double(0), gram.ctypes.data_as(POINTER(c_double)), c_int(vcount)) for i in xrange(vcount - 1): gram[i][i+1:] = gram.transpose()[i][i+1:] return gram else: return numpy.dot(vecs, vecs.transpose())
def _get_opengl_vendor_renderer_version_tuple(self): """ returns a vendor, renderer, version tuple """ from ctypes import cdll, c_char, c_char_p, c_int, byref # load stuff x11 = cdll.LoadLibrary("libX11.so.6") glx = cdll.LoadLibrary(self._find_opengl_lib_path()) # get display display = x11.XOpenDisplay("") if not display: return None, None, None # get extenstion dummy1 = c_char() dummy2 = c_char() res = glx.glXQueryExtension(display, byref(dummy1), byref(dummy2)) if not res: return None, None, None # get screen and window screen = x11.XDefaultScreen(display) root = x11.XRootWindow(display, screen) # create a window to make glGetString work attribSingleType = c_int * 8 attribSingle = attribSingleType( self.GLX_RGBA, self.GLX_RED_SIZE, 1, self.GLX_GREEN_SIZE, 1, self.GLX_BLUE_SIZE, 1, 0 ) visinfo = glx.glXChooseVisual(display, 0, attribSingle) if not visinfo: attribDoubleType = c_int * 9 attribDouble = attribDoubleType( self.GLX_RGBA, self.GLX_RED_SIZE, 1, self.GLX_GREEN_SIZE, 1, self.GLX_BLUE_SIZE, 1, self.GLX_DOUBLEBUFFER, 0, ) visinfo = glx.glXChooseVisual(display, 0, attribDouble) if not visinfo: raise OpenGLError("Can not get visinfo") # create context etc context = glx.glXCreateContext(display, visinfo, None, self.direct) if not context: raise OpenGLError("Can not create glx context") # make root current glx.glXMakeCurrent(display, root, context) # and get the actual useful gl data glx.glGetString.restype = c_char_p vendor = glx.glGetString(self.GL_VENDOR) renderer = glx.glGetString(self.GL_RENDERER) version = glx.glGetString(self.GL_VERSION) extensions = glx.glGetString(self.GL_EXTENSIONS) LOG.info("gl vendor: %s" % vendor) LOG.info("gl renderer: %s" % renderer) LOG.info("gl version: %s" % version) LOG.debug("gl extenstions: %s" % extensions) return vendor, renderer, version
def test_convert(self): # Test my helper conversion function self.assertTrue(ovr.toOvrBool(True)) self.assertTrue(ovr.toOvrBool(chr(1))) self.assertTrue(ovr.toOvrBool(ctypes.c_char(chr(1)))) self.assertFalse(ovr.toOvrBool(False)) self.assertFalse(ovr.toOvrBool(chr(0))) # Tricky one! self.assertFalse(ovr.toOvrBool(ctypes.c_char(chr(0))))
def get_names_variable(instance_exodus): var_char = ctypes.c_char('e') num_vars = ctypes.c_int() EXODUS_LIB.ex_get_var_param( instance_exodus.fileId, ctypes.byref(var_char), ctypes.byref(num_vars)) var_name_ptrs = (ctypes.POINTER(ctypes.c_char * (exodus.MAX_NAME_LENGTH + 1)) * num_vars.value)() for i in range(num_vars.value): var_name_ptrs[i] = ctypes.pointer(ctypes.create_string_buffer(exodus.MAX_NAME_LENGTH + 1)) EXODUS_LIB.ex_get_var_names( instance_exodus.fileId, ctypes.byref(var_char), num_vars, ctypes.byref(var_name_ptrs)) names_variable = [vnp.contents.value for vnp in var_name_ptrs] return names_variable
def __init__(self,params): self.sensl = ctypes.WinDLL('HRMTimeAPI.dll') self.params = params self.q = Queue.Queue() # variables for processing self.nCh = 4 self.last_tt = numpy.zeros((self.nCh,2),dtype=ctypes.c_ulong) self.first_cycle = numpy.zeros((self.nCh,)) self.times = numpy.zeros((self.nCh,), dtype=ctypes.c_double) self.last_gate = numpy.zeros((self.nCh,),dtype=ctypes.c_double) self.num_gates_global = numpy.zeros((self.nCh,),dtype=ctypes.c_ulong) self.num_cycles = numpy.zeros((self.nCh,),dtype=ctypes.c_ulong) self.num_gates_cycle = numpy.zeros((self.nCh,),dtype=ctypes.c_ulong) self.num_gates_arr = [ [], [], [], [] ] self.ch_buf = ctypes.c_char() self.gap_buf = ctypes.c_double() # this will be a list of (ch, time, gate, cycle) tuples self.proc_output = [] self.busy = False
def f(self, array, warp): """ A sampling function, responsible for returning a sampled set of values from the given array. Parameters ---------- array: nd-array Input array for sampling. warp: nd-array Deformation coordinates. Returns ------- sample: nd-array Sampled array data. """ if self.coordinates is None: raise ValueError("Appropriately defined coordinates not provided.") result = np.zeros_like(warp[0]) arg0 = c_ndarray(warp, dtype=np.double, ndim=3) arg1 = c_ndarray(array, dtype=np.double, ndim=2) arg2 = c_ndarray(result, dtype=np.double, ndim=2) libsampler.nearest( arg0, arg1, arg2, ctypes.c_char(EXTRAPOLATION_MODE[0]), ctypes.c_double(EXTRAPOLATION_CVALUE) ) return result.flatten()
def get_consensus(align, quals=[], cons_thres=-1.0, qual_thres=' ', gapped=False): cons_thres_c = ctypes.c_double(cons_thres) qual_thres_c = ctypes.c_char(qual_thres) n_seqs = len(align) if gapped: gapped_c = 1 else: gapped_c = 0 assert not quals or len(quals) == n_seqs, 'Different number of sequences and quals.' seq_len = None for seq in (align + quals): if seq_len is None: seq_len = len(seq) else: assert seq_len == len(seq), 'All sequences in the alignment must be the same length.' align_c = (ctypes.c_char_p * n_seqs)() for i, seq in enumerate(align): align_c[i] = ctypes.c_char_p(seq) quals_c = (ctypes.c_char_p * n_seqs)() for i, qual in enumerate(quals): quals_c[i] = ctypes.c_char_p(qual) if not quals: quals_c = 0 return consensus.get_consensus(align_c, quals_c, n_seqs, seq_len, cons_thres_c, qual_thres_c, gapped_c)
def get_consensus_duplex(align1, align2, quals1=[], quals2=[], cons_thres=-1.0, qual_thres=' ', method='iupac'): assert method in ('iupac', 'freq') cons_thres_c = ctypes.c_double(cons_thres) qual_thres_c = ctypes.c_char(qual_thres) n_seqs1 = len(align1) n_seqs2 = len(align2) assert (not quals1 and not quals2) or (quals1 and quals2) assert not quals1 or len(quals1) == n_seqs1 assert not quals2 or len(quals2) == n_seqs2 seq_len = None for seq in (align1 + align2 + quals1 + quals2): if seq_len is None: seq_len = len(seq) else: assert seq_len == len(seq), 'All sequences in the alignment must be the same length.' align1_c = (ctypes.c_char_p * n_seqs1)() for i, seq in enumerate(align1): align1_c[i] = ctypes.c_char_p(seq) align2_c = (ctypes.c_char_p * n_seqs1)() for i, seq in enumerate(align2): align2_c[i] = ctypes.c_char_p(seq) quals1_c = (ctypes.c_char_p * n_seqs1)() for i, seq in enumerate(quals1): quals1_c[i] = ctypes.c_char_p(seq) quals2_c = (ctypes.c_char_p * n_seqs1)() for i, seq in enumerate(quals2): quals2_c[i] = ctypes.c_char_p(seq) if not quals1: quals1_c = 0 if not quals2: quals2_c = 0 return consensus.get_consensus_duplex(align1_c, align2_c, quals1_c, quals2_c, n_seqs1, n_seqs2, seq_len, cons_thres_c, qual_thres_c, method)
def restart(self,c): #self.params = params #self.q = Queue.Queue() # variables for processing self.nCh = 4 self.last_tt = numpy.zeros((self.nCh,2),dtype=ctypes.c_ulong) self.first_cycle = numpy.zeros((self.nCh,)) self.times = numpy.zeros((self.nCh,), dtype=ctypes.c_double) self.last_gate = numpy.zeros((self.nCh,),dtype=ctypes.c_double) self.num_gates_global = numpy.zeros((self.nCh,),dtype=ctypes.c_ulong) self.num_cycles = numpy.zeros((self.nCh,),dtype=ctypes.c_ulong) self.num_gates_cycle = numpy.zeros((self.nCh,),dtype=ctypes.c_ulong) self.num_gates_arr = [ [], [], [], [] ] self.ch_buf = ctypes.c_char() self.gap_buf = ctypes.c_double() # this will be a list of (ch, time, gate, cycle) tuples self.proc_output = [] self.busy = False self.params = {} self.params['cycle_time_ms'] = 300 self.params['gate_time_us'] = 40 self.params['min_gates'] = 10
def get_consensus(align, quals=[], cons_thres=-1.0, min_reads=0, qual_thres=' ', gapped=False): cons_thres_c = ctypes.c_double(cons_thres) qual_thres_c = ctypes.c_char(qual_thres) n_seqs = len(align) if gapped: gapped_c = 1 else: gapped_c = 0 assert not quals or len(quals) == n_seqs, 'Different number of sequences and quals.' seq_len = None for seq in (align + quals): if seq_len is None: seq_len = len(seq) else: if seq_len != len(seq): raise AssertionError('All sequences in the alignment must be the same length: {}bp != {}bp.' '\nAlignment:\n{}'.format(seq_len, len(seq), '\n'.join(align))) align_c = (ctypes.c_char_p * n_seqs)() for i, seq in enumerate(align): align_c[i] = ctypes.c_char_p(seq) quals_c = (ctypes.c_char_p * n_seqs)() for i, qual in enumerate(quals): quals_c[i] = ctypes.c_char_p(qual) if not quals: quals_c = 0 return consensus.get_consensus(align_c, quals_c, n_seqs, seq_len, cons_thres_c, min_reads, qual_thres_c, gapped_c)
def GetMode(hDevice): c=ctypes.c_char('\0') if(dll.GT_GetMode(hDevice,ctypes.byref(c))): t=ord(c.value) return mode[t] else: print "Fail to get mode" return 0
def playlist_folder_name(self, index): buf = (ctypes.c_char() * 255)() handle_sp_error( self.__container_interface.playlist_folder_name( self.__container_struct, index, ctypes.byref(buf), 255 ) ) return buf.value
def get_data(self): data = ctypes.pointer(ctypes.c_char()) size = ctypes.c_ulong() _check_result(gp.gp_file_get_data_and_size( self._cf, ctypes.byref(data), ctypes.byref(size))) return ctypes.string_at(data, size.value)
def transfer_gaps_multi(seqs, aligned, gap_char_in='-', gap_char_out='-'): gap_char_in_c = ctypes.c_char(gap_char_in) gap_char_out_c = ctypes.c_char(gap_char_out) n_seqs = len(seqs) assert n_seqs == len(aligned), 'Error: Unequal number of gapped and ungapped sequences.' seqs_c = (ctypes.c_char_p * n_seqs)() for i, seq in enumerate(seqs): seqs_c[i] = ctypes.c_char_p(seq) aligned_c = (ctypes.c_char_p * n_seqs)() for i, seq in enumerate(aligned): aligned_c[i] = ctypes.c_char_p(seq) seqtools.transfer_gaps_multi.restype = ctypes.POINTER(ctypes.c_char_p * n_seqs) output_c = seqtools.transfer_gaps_multi(n_seqs, aligned_c, seqs_c, gap_char_in_c, gap_char_out_c) output = [] for seq in output_c.contents: output.append(seq) return output
def test_something(self): """Crash the Python interpreter""" i = ctypes.c_char('a') j = ctypes.pointer(i) c = 0 while True: j[c] = 'a' c += 1 j
def FillConsoleOutputCharacter(stream_id, char, length, start): handle = handles[stream_id] char = c_char(char.encode()) length = wintypes.DWORD(length) num_written = wintypes.DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. success = _FillConsoleOutputCharacterA( handle, char, length, start, byref(num_written)) return num_written.value
def circulate_vertex(self,v,mode='v'): """ Circulate a vertex. Passed a vertex index, v, and second argument, mode='f', this function will return an iterable with all faces incident on v arranged in counter clockwise order. Similarly, if mode is 'h', incident halfedges (outgoing) are returned, and for mode = 'v', all neighboring vertices are returned. """ nbrs = IntVector() n = lib_py_gel.Manifold_circulate_vertex(self.obj, v, ct.c_char(mode.encode('ascii')), nbrs.obj) return nbrs
def crash(): import ctypes i = ctypes.c_char('a') j = ctypes.pointer(i) c = 0 while True: j[c] = 'a' c += 1 j
def __init__(self): ''' Loads and initializes the hardware driver. Initializes local parameters Input: name (string) : The name of the device ''' # Check operating system and load library if platform.system() == "Linux": dllname = "/usr/local/lib/libandor.so" self._dll = cdll.LoadLibrary(dllname) elif platform.system() == "Windows": dllname = "C:\\Program Files\\Andor iDus\\ATMCD32D" self._dll = windll.LoadLibrary(dllname) else: print "Cannot detect operating system, wil now stop" raise # Initialize the device tekst = c_char() error = self._dll.Initialize(byref(tekst)) print "Initializing: %s" % ( ERROR_CODE[error]) cw = c_int() ch = c_int() self._dll.GetDetector(byref(cw), byref(ch)) # Initiate parameters self._width = cw.value self._height = ch.value self._temperature = None self._set_T = None self._gain = None self._gainRange = None self._status = ERROR_CODE[error] self._verbosity = True self._preampgain = None self._channel = None self._outamp = None self._hsspeed = None self._vsspeed = None self._serial = None self._exposure = None self._accumulate = None self._kinetic = None self._bitDepths = [] self._preAmpGain = [] self._VSSpeeds = [] self._noGains = None self._imageArray = [] self._noVSSpeeds = None self._HSSpeeds = [] self._noADChannels = None self._noHSSpeeds = None self._ReadMode = None
def CONFD_GET_BUF (self, index=0): self._raiseIfNullOrBadIndex(index) bufPtr=ctypes.pointer(ctypes.c_char()) pyconfdlib.dll.py_CONFD_GET_BUFPTR(self._myValuePtr, index, ctypes.cast(ctypes.byref(bufPtr), ctypes.POINTER(ctypes.c_char_p)) ) bufSize=pyconfdlib.Int64Type() pyconfdlib.dll.py_CONFD_GET_BUFSIZE(self._myValuePtr, index, ctypes.byref(bufSize)) ret=bufPtr[:bufSize.value] for logFunc in pyconfdlib._log("get-buf").debug4Func(): logFunc("ConfdValues.CONFD_GET_BUF(index=%s) returning %s.",index, ret) return ret
def cause_segmentation_fault(): """Crashes the Python interpreter by segfaulting.""" i = ctypes.c_char('a') j = ctypes.pointer(i) c = 0 while True: j[c] = 'a' c += 1 return j
def numpy_pil_to_buf(arr, w, h): ig = (ctypes.c_char * (w * h * 3))() idx = 0 for row in arr: for RGB_object in row: for RGB_val in RGB_object: ig[idx] = ctypes.c_char( chr(RGB_val) ) idx += 1 return img
def circulate_face(self,f,mode='v'): """ Circulate a face. Passed a face index, f, and second argument, mode='f', this function will return an iterable with all faces that share an edge with f (in counter clockwise order). If the argument is mode='h', the halfedges themselves are returned. For mode='v', the incident vertices of the face are returned. """ nbrs = IntVector() n = lib_py_gel.Manifold_circulate_face(self.obj, f, ct.c_char(mode.encode('ascii')), nbrs.obj) return nbrs
def Mul(m1, m2, i, r): no_trans = c_char(b"n") n = c_int(i) one = c_float(1.0) zero = c_float(0.0) _blaslib.sgemm_(byref(no_trans), byref(no_trans), byref(n), byref(n), byref(n), byref(one), m1.ctypes.data_as(ctypes.c_void_p), byref(n), m2.ctypes.data_as(ctypes.c_void_p), byref(n), byref(zero), r.ctypes.data_as(ctypes.c_void_p), byref(n))
def crash(): '''\ crash the Python interpreter... ''' i = ctypes.c_char('a') j = ctypes.pointer(i) c = 0 while True: j[c] = 'a' c += 1
def capture(): KinectSensor.dumped = False # prep args & define to call tPoseStart = c_char('\1'.encode()) # always say true ForM = c_char('F'.encode()) KinectSensor.DLL[OPEN_SENSOR].argtypes = (c_char, c_char) hresult = KinectSensor.DLL[OPEN_SENSOR](tPoseStart, ForM) if not KinectSensor.SUCCEEDED(hresult): return # initialize temporary stores for returned data KinectSensor.frame_buffer = [] KinectSensor.trackedBodies = [] # call to start tracking callback_type = CFUNCTYPE(c_void_p, c_char_p) KinectSensor.callback_func = callback_type(KinectSensor.bodyReaderCallback) KinectSensor.DLL[BEGIN_BODY_TRACKING].argtypes = [c_void_p, c_char_p] hresult = KinectSensor.DLL[BEGIN_BODY_TRACKING](KinectSensor.callback_func) KinectSensor.recording = KinectSensor.SUCCEEDED(hresult)
def _zgemm(trans_a, trans_b, m, n, k, a, b, c, alpha=1, beta=0, offseta=0, offsetb=0, offsetc=0): if a.size == 0 or b.size == 0: if beta == 0: c[:] = 0 else: c[:] *= beta return c assert (a.flags.c_contiguous) assert (b.flags.c_contiguous) assert (c.flags.c_contiguous) assert (a.dtype == numpy.complex128) assert (b.dtype == numpy.complex128) assert (c.dtype == numpy.complex128) _np_helper.NPzgemm(ctypes.c_char(trans_b.encode('ascii')), ctypes.c_char(trans_a.encode('ascii')), ctypes.c_int(n), ctypes.c_int(m), ctypes.c_int(k), ctypes.c_int(b.shape[1]), ctypes.c_int(a.shape[1]), ctypes.c_int(c.shape[1]), ctypes.c_int(offsetb), ctypes.c_int(offseta), ctypes.c_int(offsetc), b.ctypes.data_as(ctypes.c_void_p), a.ctypes.data_as(ctypes.c_void_p), c.ctypes.data_as(ctypes.c_void_p), (ctypes.c_double * 2)(alpha.real, alpha.imag), (ctypes.c_double * 2)(beta.real, beta.imag)) return c
def loadLibrary(): # This is only performed once. Subsequent calls just echo first test, so can be used in UI polling if Kinect2Sensor.LOAD_EXCEPTION is not None: return Kinect2Sensor.LOAD_EXCEPTION if Kinect2Sensor.DLL is not None: return None # Sensor only works on windows. Keep Linux, others from erroring if platform != "win32" and platform != "win64": LOAD_EXCEPTION = 'Kinect2 only works on a Windows operating system.' return LOAD_EXCEPTION # actually try to load the dll, inside try block, in case they failed do to install Kinect runtime re-distributable try: is64Bit = calcsize("P") * 8 == 64 # using sys.platform is NOT reliable fileName = 'KinectToJSON_' + ('x64' if is64Bit else 'x86') + '.dll' moduleDirectory = path.dirname(__file__) filepath = path.join(moduleDirectory, fileName) Kinect2Sensor.DLL = cdll.LoadLibrary(filepath) print('DLL: ' + fileName + ', loaded from: ' + moduleDirectory) except: LOAD_EXCEPTION = 'DLL: ' + fileName + ', on path: ' + moduleDirectory +', failed to load.\nIs Kinect re-distributable installed?' return LOAD_EXCEPTION # the only way to be sure is to open the sensor & check the result Kinect2Sensor.DLL[OPEN_SENSOR].argtypes = (c_char, c_char, c_char) hresult = Kinect2Sensor.DLL[OPEN_SENSOR](c_char('\1'.encode()), c_char('F'.encode()), c_char('W'.encode())) testWorked = Kinect2Sensor.SUCCEEDED(hresult) #when successful, have the side effect of sensor being open. Reverse that if testWorked: Kinect2Sensor.DLL[CLOSE_SENSOR]() return None else: LOAD_EXCEPTION = 'Kinect open sensor failed. Is it plugged in & connected?' return LOAD_EXCEPTION
def Put(data, format): if format == CF_UNICODETEXT: hCd = ga(GHND, len(bytes(data)) + sizeof(c_char())) else: hCd = ga(GHND, len(bytes(data)) + sizeof(c_wchar())) pchData = gl(hCd) if format == CF_UNICODETEXT: wcscpy(c_wchar_p(pchData), bytes(data)) else: strcpy(c_char_p(pchData), bytes(data)) gul(hCd) scd(c_int(format), hCd, 0, False)
def minimax(board, player): # Convert board to c b = c_board(board) # Conver player to c p = ct.c_char(player.encode()) # Call minimax from c j = mlib.minimax_bridge(b, p) # Return py position return position[j] # main()
def MKL_mult(A, x, y): """ MKL sparse matrix-vector multiplication """ # https://stackoverflow.com/questions/17158893/does-scipy-support-multithreading-for-sparse-matrix-multiplication-when-using-mk#23294826 (m, n) = A.shape # The data of the matrix data = A.data.ctypes.data_as(POINTER(c_double)) indptr = A.indptr.ctypes.data_as(POINTER(c_int)) indices = A.indices.ctypes.data_as(POINTER(c_int)) np_x = x.ctypes.data_as(POINTER(c_double)) np_y = y.ctypes.data_as(POINTER(c_double)) SpMV(byref(c_char(b"N")), byref(c_int(m)), data, indptr, indices, np_x, np_y)
def clrscr(): hConOut = _getconout() csbi = _getscreeninfo() coord = ctypes.wintypes._COORD() coord.X = 0 coord.Y = 0 kernel32.FillConsoleOutputCharacterA(hConOut, ctypes.c_char(b' '), csbi.dwSize.X * csbi.dwSize.Y, coord, LPDWORD(ctypes.c_ulong(0))) kernel32.FillConsoleOutputAttribute(hConOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, LPDWORD(ctypes.c_ulong(0))) kernel32.SetConsoleCursorPosition(hConOut, coord) _releaseconout(hConOut)
def CONFD_GET_BUF(self, index=0): self._raiseIfNullOrBadIndex(index) bufPtr = ctypes.pointer(ctypes.c_char()) pyconfdlib.dll.py_CONFD_GET_BUFPTR( self._myValuePtr, index, ctypes.cast(ctypes.byref(bufPtr), ctypes.POINTER(ctypes.c_char_p))) bufSize = pyconfdlib.Int64Type() pyconfdlib.dll.py_CONFD_GET_BUFSIZE(self._myValuePtr, index, ctypes.byref(bufSize)) ret = bufPtr[:bufSize.value] for logFunc in pyconfdlib._log("get-buf").debug4Func(): logFunc("ConfdValues.CONFD_GET_BUF(index=%s) returning %s.", index, ret) return ret
def setAttr(self, attr_name, obj): """ to set proprietary attribute items for graph, for the backend device to run :param attr_name:<str> the attribute name :param obj: <int> or <float> or <str> attribute value :return: 0: success, -1: fail. """ if type(obj) == type(0): i_inp = (ctypes.c_int*1)(obj) self.attr[attr_name] = {'type': type(obj), 'len': ctypes.sizeof(i_inp)} return _LIB.set_graph_attr(ctypes.c_void_p(self.graph), c_str(attr_name), ctypes.cast(i_inp,ctypes.POINTER(ctypes.c_int)), ctypes.sizeof(i_inp)) elif type(obj) == type(0.1): f_inp = (ctypes.c_float*1)(obj) self.attr[attr_name] = {'type': type(obj), 'len': ctypes.sizeof(f_inp)} return _LIB.set_graph_attr(ctypes.c_void_p(self.graph), c_str(attr_name), ctypes.cast(f_inp,ctypes.POINTER(ctypes.c_float)), ctypes.sizeof(f_inp)) elif type(obj) == type(""): self.attr[attr_name] = {'type': type(obj), 'len': ctypes.sizeof(ctypes.c_char('a')) * len(obj)} buf = ctypes.create_string_buffer(obj) return _LIB.set_graph_attr(ctypes.c_void_p(self.graph), c_str(attr_name), buf, ctypes.sizeof(ctypes.c_char('a')) * len(obj)) pass
def xget_virtual_keycode(cls, char): if isinstance(char, str): code = windll.user32.VkKeyScanA(c_char(char)) else: code = windll.user32.VkKeyScanW(c_wchar(char)) if code == -1: raise ValueError("Unknown char: %r" % char) # Construct a list of the virtual key code and modifiers. codes = [code & 0x00ff] if code & 0x0100: codes.append(cls.shift_code) elif code & 0x0200: codes.append(cls.ctrl_code) elif code & 0x0400: codes.append(cls.alt_code) return codes
def test_prop__bst_insert(gen): ixys, mode, ixy_map = gen['ixys'], gen['mode'], gen['ixy_map'] xORy = c_char(mode.encode()) ixy_arr = sparse_array(ixys) n_node = 0 # empty tree = (NODE * MAX_LEN)() for n_inserted, (i,x,y) in enumerate(ixys, start=1): n_node = bst.insert( n_node, tree, xORy, i, ixy_arr) assert_valid_bst( mode, ixy_map, ixy_arr, tree, n_inserted, n_node)
def tdot_blas(mat, out=None): """returns np.dot(mat, mat.T), but faster for large 2D arrays of doubles.""" if (mat.dtype != 'float64') or (len(mat.shape) != 2): return np.dot(mat, mat.T) nn = mat.shape[0] if out is None: out = np.zeros((nn, nn)) else: assert (out.dtype == 'float64') assert (out.shape == (nn, nn)) # FIXME: should allow non-contiguous out, and copy output into it: assert (8 in out.strides) # zeroing needed because of dumb way I copy across triangular answer out[:] = 0.0 # # Call to DSYRK from BLAS # If already in Fortran order (rare), and has the right sorts of strides I # could avoid the copy. I also thought swapping to cblas API would allow use # of C order. However, I tried that and had errors with large matrices: # http://homepages.inf.ed.ac.uk/imurray2/code/tdot/tdot_broken.py mat = np.asfortranarray(mat) TRANS = c_char('n') N = c_int(mat.shape[0]) K = c_int(mat.shape[1]) LDA = c_int(mat.shape[0]) UPLO = c_char('l') ALPHA = c_double(1.0) A = mat.ctypes.data_as(ctypes.c_void_p) BETA = c_double(0.0) C = out.ctypes.data_as(ctypes.c_void_p) LDC = c_int(np.max(out.strides) / 8) _blaslib.dsyrk_(byref(UPLO), byref(TRANS), byref(N), byref(K), byref(ALPHA), A, byref(LDA), byref(BETA), C, byref(LDC)) symmetrify(out, upper=True) return out
def merge_files(svm_files, offsets, is_training, output): if not isinstance(offsets, list) or len(svm_files) != len(offsets): raise ValueError( 'offsets should be a list where the length is the number of merged files' ) util = CDLL( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'classifier', 'learner', 'util.so.1')) util.merge_problems.restype = None util.merge_problems.argtypes = [ POINTER(c_char_p), c_int, POINTER(c_int64), c_char_p, c_char, POINTER(c_int64) ] size = len(svm_files) c_svm_files = (c_char_p * size)() for i, f in enumerate(svm_files): c_svm_files[i] = c_char_p(f.encode()) c_offsets = (c_int64 * size)() if not is_training: for i, v in enumerate(offsets): c_offsets[i] = c_int64(v) c_is_training = c_char(chr(is_training).encode('ascii')) c_error_code = c_int64() output = c_char_p(bytes( output, 'utf-8')) if sys.version_info[0] >= 3 else c_char_p(output) util.merge_problems(c_svm_files, c_int(size), c_offsets, output, c_is_training, c_error_code) error_code = c_error_code.value if error_code > 0: raise ValueError('wrong file format in line ' + str(error_code)) elif error_code == -1: raise IOError('cannot open file') elif error_code == -2: raise MemoryError("Memory Exhausted. Try to restart python.") elif error_code == -3: raise ValueError('merging svm files of different sizes') elif error_code == -4: raise ValueError('at least one file should be given to merge') if is_training: for i in range(size): offsets[i] = c_offsets[i]
def sgdLong(self, input, output, batches, optimization_method=OPT_SGD): bufferCount = len(input) inputSize = len(input[0]) outputSize = len(output[0]) flat_input = [item for sublist in input for item in sublist] c_inputs = ctypes.c_float * len(flat_input) input_array = c_inputs(*flat_input) flat_output = [item for sublist in output for item in sublist] c_output = ctypes.c_float * len(flat_output) output_array = c_output(*flat_output) return self.fun.nn_TrainBigBuffer(self.neuralNet, input_array, inputSize, output_array, outputSize, ctypes.c_int(bufferCount), ctypes.c_char(optimization_method), ctypes.c_int(batches))
def clear_screen(self, char=' '): coord_screen = _COORD(0, 0) chars_written = ctypes.c_ulong(0) csbi = _CONSOLE_SCREEN_BUFFER_INFO() console_size = ctypes.c_ulong(0) _GetConsoleScreenBufferInfo(self.handle, ctypes.byref(csbi)) console_size = csbi.dwSize.X * csbi.dwSize.Y _FillConsoleOutputCharacterA(self.handle, ctypes.c_char( ord(char)), console_size, coord_screen, ctypes.byref(chars_written)) _GetConsoleScreenBufferInfo(self.handle, ctypes.byref(csbi)) _FillConsoleOutputAttribute( self.handle, csbi.wAttributes, console_size, coord_screen, ctypes.byref(chars_written)) _SetConsoleCursorPosition(self.handle, coord_screen)
def clear_line(self,param): mode=param and int(param)or 0 sbinfo=self.screen_buffer_info() if mode==1: line_start=COORD(0,sbinfo.CursorPosition.Y) line_length=sbinfo.Size.X elif mode==2: line_start=COORD(sbinfo.CursorPosition.X,sbinfo.CursorPosition.Y) line_length=sbinfo.Size.X-sbinfo.CursorPosition.X else: line_start=sbinfo.CursorPosition line_length=sbinfo.Size.X-sbinfo.CursorPosition.X chars_written=c_ulong() windll.kernel32.FillConsoleOutputCharacterA(self.hconsole,c_char(' '),line_length,line_start,byref(chars_written)) windll.kernel32.FillConsoleOutputAttribute(self.hconsole,sbinfo.Attributes,line_length,line_start,byref(chars_written))
def test_bool(self): # Create various values for testing # A) Built in python booleans bt1 = True bf1 = False # B) OVR wrapped booleans bt2 = ctypes.c_char(chr(1).encode('utf-8')) bf2 = ctypes.c_char(chr(0).encode('utf-8')) # C) chr's, which might accidently get used sometimes # This is the most dangerous situation, because bool(chr(0)) == False bt3 = chr(1) bf3 = chr(0) # DANGER! # D) ovr macros bt4 = ovr.ovrTrue bf4 = ovr.ovrFalse # Make sure we understand who is true and false in boolean context self.assertTrue(bool(bt1)) self.assertTrue(bool(bt2)) self.assertTrue(bool(bt3)) self.assertTrue(bool(bt4)) self.assertFalse(bool(bf1)) self.assertFalse(bool(bf2)) self.assertTrue(bool(bf3)) # Danger! self.assertFalse(bool(bf4))
def display(self, m, mode='w', smooth=True, bg_col=[0.3, 0.3, 0.3], data=None, reset_view=False, once=False): """ Display a mesh Args: --- - m : the Manifold mesh we are visualizing. - mode : a single character that determines how the mesh is visualized: 'w' - wireframe, 'i' - isophote, 'g' - glazed (try it and see), 's' - scalar field, 'l' - line field, 'n' - normal. - smooth : if True we use vertex normals. Otherwise, face normals. - bg_col : background color. - data : per vertex data for visualization. scalar or vector field. - reset_view : if False view is as left in the previous display call. If True, the view is reset to the default. - once : if True we immediately exit the event loop and return. However, the window stays and if the event loop is called from this or any other viewer, the window will still be responsive. Interactive controls: --- When a viewer window is displayed on the screen, you can naviagate with the mouse: Left mouse button rotates, right mouse button is used for zooming and (if shift is pressed) for panning. If you hold control, any mouse button will pick a point on the 3D model. Up to 19 of these points have unique colors. If you pick an already placed annotation point it will be removed and can now be placed elsewhere. Hit space bar to clear the annotation points. Hitting ESC exits the event loop causing control to return to the script. """ data_ct = np.array(data, dtype=ct.c_double).ctypes data_a = data_ct.data_as(ct.POINTER(ct.c_double)) bg_col_ct = np.array(bg_col, dtype=ct.c_float).ctypes bg_col_a = bg_col_ct.data_as(ct.POINTER(ct.c_float * 3)) lib_py_gel.GLManifoldViewer_display(self.obj, m.obj, ct.c_char(mode.encode('ascii')), smooth, bg_col_a, data_a, reset_view, once)
def mkl_zspmm_old(A, B, alpha=1.0, beta = 0.0): """ sparse matrix * dense matrix using MKL dcsrmm """ (m,k) = A.shape (bk,n) = B.shape if k != bk: raise Exception('A and B dims are incompatible') # Allocate output, using same conventions as input C = np.zeros((m,n),dtype=np.complex,order='C') np_B = B.ctypes.data_as(ctypeslib.ndpointer(np.complex, ndim=2, flags='C')) np_C = C.ctypes.data_as(ctypeslib.ndpointer(np.complex, ndim=2, flags='C')) # Pointers to data of the matrix data = A.data.ctypes.data_as(ctypeslib.ndpointer(np.complex, ndim=1, flags='C')) pointerB = A.indptr[:-1] pointerE = A.indptr[1:] np_pointerB = pointerB.ctypes.data_as(POINTER(c_int)) np_pointerE = pointerE.ctypes.data_as(POINTER(c_int)) indices = A.indices.ctypes.data_as(POINTER(c_int)) matdescra = np.chararray(6) matdescra[0] = 'G'#G-general, S-symmetric, H-hermitian matdescra[1] = 'L' matdescra[2] = 'N' matdescra[3] = 'C' np_matdescra = matdescra.ctypes.data_as(POINTER(c_char)) # now call MKL zcsrmm(byref(c_char(bytes(b'N'))), byref(c_int(m)), byref(c_int(n)), byref(c_int(k)), byref(c_double(alpha)), np_matdescra, data, indices, np_pointerB, np_pointerE, np_B, byref(c_int(n)), byref(c_double(beta)), np_C, byref(c_int(n))) return C
def clreol(): hConOut = _getconout() csbi = _getscreeninfo() kernel32.FillConsoleOutputCharacterA(hConOut, ctypes.c_char(b' '), csbi.dwSize.X - csbi.dwCursorPosition.X, csbi.dwCursorPosition, LPDWORD(ctypes.c_ulong(0)) ) kernel32.FillConsoleOutputAttribute(hConOut, csbi.wAttributes, csbi.dwSize.X - csbi.dwCursorPosition.X, csbi.dwCursorPosition, LPDWORD(ctypes.c_ulong(0)) ) _releaseconout(hConOut)
def clear_screen(self,param): mode=to_int(param,0) sbinfo=self.screen_buffer_info() if mode==1: clear_start=COORD(0,0) clear_length=sbinfo.CursorPosition.X*sbinfo.CursorPosition.Y elif mode==2: clear_start=COORD(0,0) clear_length=sbinfo.Size.X*sbinfo.Size.Y windll.kernel32.SetConsoleCursorPosition(self.hconsole,clear_start) else: clear_start=sbinfo.CursorPosition clear_length=((sbinfo.Size.X-sbinfo.CursorPosition.X)+sbinfo.Size.X*(sbinfo.Size.Y-sbinfo.CursorPosition.Y)) chars_written=c_ulong() windll.kernel32.FillConsoleOutputCharacterA(self.hconsole,c_char(' '),clear_length,clear_start,byref(chars_written)) windll.kernel32.FillConsoleOutputAttribute(self.hconsole,sbinfo.Attributes,clear_length,clear_start,byref(chars_written))
def value(self): logger = lldb.formatters.Logger.Logger() # in spite of the plenty of types made available by the public NSNumber API # only a bunch of these are actually used in the internal implementation # unfortunately, the original type information appears to be lost # so we try to at least recover the proper magnitude of the data if self.info_bits == 0: return '(char)' + str(ord(ctypes.c_char(chr(self.data % 256)).value)) if self.info_bits == 4: return '(short)' + str(ctypes.c_short(self.data % (256*256)).value) if self.info_bits == 8: return '(int)' + str(ctypes.c_int(self.data % (256*256*256*256)).value) if self.info_bits == 12: return '(long)' + str(ctypes.c_long(self.data).value) else: return 'absurd value:(info=' + str(self.info_bits) + ", value = " + str(self.data) + ')'
def get_keycode_and_modifiers(cls, char): layout = windll.user32.GetKeyboardLayout(0) if isinstance(char, str): code = windll.user32.VkKeyScanExA(c_char(char), layout) else: code = windll.user32.VkKeyScanExW(c_wchar(char), layout) if code == -1: raise ValueError("Unknown char: %r" % char) # Construct a list of the virtual key code and modifiers. modifiers = [] if code & 0x0100: modifiers.append(cls.shift_code) if code & 0x0200: modifiers.append(cls.ctrl_code) if code & 0x0400: modifiers.append(cls.alt_code) code &= 0x00ff return code, modifiers
def PeekNamedPipe(handle, desired_bytes): c_avail = DWORD() c_message = DWORD() if desired_bytes > 0: c_read = DWORD() buffer = ctypes.create_string_buffer(desired_bytes + 1) success = ctypes.windll.kernel32.PeekNamedPipe( handle, buffer, desired_bytes, ctypes.byref(c_read), ctypes.byref(c_avail), ctypes.byref(c_message)) buffer[c_read.value] = ctypes.c_char(0) return decode(buffer.value), c_avail.value, c_message.value else: success = ctypes.windll.kernel32.PeekNamedPipe( handle, None, desired_bytes, None, ctypes.byref(c_avail), ctypes.byref(c_message)) return "", c_avail.value, c_message.value
def FillConsoleOutputCharacter(stream_id, char, length, start): handle = _GetStdHandle(stream_id) char = c_char(char.encode()) length = wintypes.DWORD(length) num_written = wintypes.DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. success = _FillConsoleOutputCharacterA(handle, char, length, start, byref(num_written)) return num_written.value
def SpMV_viaMKL(A, x): ''' Wrapper to Intel's SpMV (Sparse Matrix-Vector multiply) For medium-sized matrices, this is 4x faster than scipy's default implementation Stephen Becker, April 24 2014 [email protected] ''' import numpy as np import scipy.sparse as sparse from ctypes import POINTER, c_void_p, c_int, c_char, c_double, byref, cdll, c_char_p mkl = cdll.LoadLibrary("libmkl_rt.so") SpMV = mkl.mkl_dcsrmv # Dissecting the "cspblas_dcsrgemv" name: # "c" - for "c-blas" like interface (as opposed to fortran) # Also means expects sparse arrays to use 0-based indexing, which python does # "sp" for sparse # "d" for double-precision # "csr" for compressed row format # "ge" for "general", e.g., the matrix has no special structure such as symmetry # "mv" for "matrix-vector" multiply m, k = A.shape # The data of the matrix data = A.data.ctypes.data_as(POINTER(c_double)) indptb = A.indptr.ctypes.data_as(POINTER(c_int)) indpte = (A.indptr + 3).ctypes.data_as(POINTER(c_int)) indices = A.indices.ctypes.data_as(POINTER(c_int)) # Allocate output, using same conventions as input matdescra = 'GUNC' y = np.empty((m, 1), dtype=np.double, order='F') np_x = x.ctypes.data_as(POINTER(c_double)) np_y = y.ctypes.data_as(POINTER(c_double)) # now call MKL. This returns the answer in np_y, which links to y SpMV(byref(c_char("N")), byref(c_int(m)), byref(c_int(k)), byref(c_double(1.0)), byref(c_char_p(matdescra)), data, indices, indptb, indpte, np_x, byref(c_double(0.0)), np_y) return y
def test_ctypes_in_variant(self): v = VARIANT() objs = [(c_ubyte(3), VT_UI1), (c_char("x"), VT_UI1), (c_byte(3), VT_I1), (c_ushort(3), VT_UI2), (c_short(3), VT_I2), (c_uint(3), VT_UI4), (c_uint64(2**64), VT_UI8), (c_int(3), VT_I4), (c_int64(2**32), VT_I8), (c_double(3.14), VT_R8), (c_float(3.14), VT_R4), ] for value, vt in objs: v.value = value self.failUnlessEqual(v.vt, vt)
def media_read_cb(opaque, buffer, length): print("READ", opaque, buffer, length) stream_provider = ctypes.cast(opaque, ctypes.POINTER( ctypes.py_object)).contents.value new_data = stream_provider.get_data() bytes_read = len(new_data) if bytes_read > 0: buffer_array = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_char * bytes_read)) for index, b in enumerate(new_data): buffer_array.contents[index] = ctypes.c_char(b) print(f"just read f{bytes_read}B") return bytes_read
def serial_poll(handle): """Read status byte by calling ibrsp. Args: handle (int): device handle Returns: int: serial poll status byte """ status = ctypes.c_char() sta = _lib.ibrsp(handle, ctypes.byref(status)) if sta & ERR: raise GpibError("serial_poll") return int(status.value[0])
def MGRSToUTM(self, MGRS, encoding='utf-8'): if type(MGRS) is str: mgrs = MGRS.encode(encoding) else: mgrs = MGRS mgrs = ctypes.string_at(mgrs) zone = ctypes.pointer(ctypes.c_long()) hemisphere = ctypes.pointer(ctypes.c_char()) easting = ctypes.pointer(ctypes.c_double()) northing = ctypes.pointer(ctypes.c_double()) core.rt.Convert_MGRS_To_UTM(mgrs, zone, hemisphere, easting, northing) return (zone.contents.value, hemisphere.contents.value.decode('utf-8'), easting.contents.value, northing.contents.value)