<commit_before>import sys, os
if __name__ == '__main__':
    d = os.path.dirname(__file__)
    sys.path.append(os.path.join(d, '../../util'))
    
import acq4.util.ptime as ptime
from ctypes import *
from acq4.util.clibrary import *
from numpy import empty, uint16, ascontiguousarray, concatenate, newaxis
from acq4.pyqtgraph import graphicsWindows as gw
from PyQt4 import QtGui
from acq4.util.Mutex import Mutex, MutexLocker
from collections import OrderedDict
import atexit
import traceback
import time
modDir = os.path.dirname(__file__)
sdkDir = r"C:\Program Files\QImaging\SDK\Headers"

## check for installed SDK, fall back to local header copies
if os.path.isdir(sdkDir):
    headerDir = sdkDir
else:
    headerDir = modDir
print headerDir
p = CParser(os.path.join(headerDir, "QCamApi.h"), cache=os.path.join(modDir, 'QCamApi.h.cache'), macros={'_WIN32': '', '__int64': ('long long')})

if sys.platform == 'darwin':
    dll = cdll.LoadLibrary('/Library/Frameworks/QCam.framework/QCam')
else:
    dll = windll.QCamDriver
lib = CLibrary(dll, p, prefix = 'QCam_')        ##makes it so that functions in the header file can be accessed using lib.nameoffunction, ie: QCam_LoadDriver is lib.LoadDriver
                                                ##also interprets all the typedefs for you....very handy
                                                ##anything from the header needs to be accessed through lib.yourFunctionOrParameter


#modDir = os.path.dirname(__file__)
#headerFiles = [
#    #"C:\Program Files\Photometrics\PVCam32\SDK\inc\master.h",
#    #"C:\Program Files\Photometrics\PVCam32\SDK\inc\pvcam.h"
#    os.path.join(modDir, "QCamApi.h")
#    #os.path.join(modDir, "pvcam.h")
#]
#HEADERS = CParser(headerFiles, cache=os.path.join(modDir, 'pvcam_headers.cache'), copyFrom=winDefs())
#LIB = CLibrary(windll.Pvcam32, HEADERS, prefix='pl_')
#

###functions that are called from CameraDevice:
# setUpCamera(self) - """Prepare the camera at least so that get/setParams will function correctly"""
# listParams(self, params=None)
# setParams(self, params, autoRestart=True, autoCorrect=True)
# getParams(self, params=None)
# quit(self)

externalParams = ['triggerMode',
                  #'triggerType', ## Add this in when we figure out TriggerModes
                  'exposure',
                  'binningX',
                  'binningY',
                  'regionX',
                  'regionY',
                  'regionW',
                  'regionH',
                  'gain',
                  'qprmS32AbsoluteOffset',
                  'qprmReadoutSpeed',
                  'qprmCoolerActive',
                  'qprmS32RegulatedCoolingTemp',
                  'qprmBlackoutMode',
                  'qprmSyncb',
                  'ringSize'
                  ]
cameraDefaults = {
    'ALL':{
        'qprmImageFormat':'qfmtMono16',
    }}

#def init():
#    ## System-specific code
#    global QCam
#    QCam = _QCamDriverClass()
        
class QCamFunctionError(Exception):
    def __init__(self, value, message):
        self.value = value
        self.message = message
    
    def __str__(self):
        return repr(self.message)

class QCamDriverClass:
    def __init__(self):
        self.cams = {}
        self.paramTable = OrderedDict()
        
        self.loadDriver()
        
        global externalParams
        for p in externalParams:
            self.paramTable[p] = p        
    
    def call(self, function, *args):
        """"""
        a = function(*args)
        if a() == None:
            return a
        elif a() != 0:
            for x in lib('enums', 'QCam_Err'):
                if lib('enums', 'QCam_Err')[x] == a():
                    raise QCamFunctionError(a(), "There was an error running %s. Error code = %s" %(function.name,x))
        else:
            return a

    def loadDriver(self):
        self.call(lib.LoadDriver)
 
    #def releaseDriver(self):
    #    self.call(lib.ReleaseDriver)
        
    def listCameras(self):
        number = c_ulong(10)
        L = lib.CamListItem * 10
        l = L()
        self.call(lib.ListCameras, l, number)
        cams = {}
        for x in list(l)[:number.value]:
            cams[x.uniqueId] = x.cameraId
        return cams
    
    def getCamera(self, cam):
        #print "QIdriver: getting camera...."
        if not self.cams.has_key(cam):
            #print "    creating camera class..."
            self.cams[cam] = QCameraClass(cam, self)
            #print "    camera class created for cam: %s" %cam
        return self.cams[cam]
        
    def __del__(self):
        if len(self.cams) != 0:
            self.quit()
        else:
            self.call(lib.ReleaseDriver)

    def quit(self):
        #print "quit() called from QCamDriverClass."
        for c in self.cams:
            self.cams[c].quit()
        self.call(lib.ReleaseDriver) ###what if we don't open the camera?

        
class QCameraClass:
    def __init__(self, name, driver):
        #print "QCamera Class: setting self variables..."
        self.name = name
        self.driver = driver
        self.isOpen = False
        self.handle = self.open()
        self.ringSize = 10
        self.paramAttrs = OrderedDict()
        self.cameraInfo = {}
        self.frames = []
        self.arrays = []
        self.frameTimes = []
        self.i = 0
        self.stopSignal = True
        self.mutex = Mutex(Mutex.Recursive)
        self.lastImage = (None,0)
        self.fnp1 = lib.AsyncCallback(self.callBack1)
        self.fnpNull = lib.AsyncCallback(self.doNothing)
        self.counter = 0
        
        <commit_msg>Workaround for QImaging exit bug<commit_after>import sys, os
if __name__ == '__main__':
    d = os.path.dirname(__file__)
    sys.path.append(os.path.join(d, '../../util'))
    
import acq4.util.ptime as ptime
from ctypes import *
from acq4.util.clibrary import *
from numpy import empty, uint16, ascontiguousarray, concatenate, newaxis
from acq4.pyqtgraph import graphicsWindows as gw
from PyQt4 import QtGui
from acq4.util.Mutex import Mutex, MutexLocker
from collections import OrderedDict
import atexit
import traceback
import time
modDir = os.path.dirname(__file__)
sdkDir = r"C:\Program Files\QImaging\SDK\Headers"

## check for installed SDK, fall back to local header copies
if os.path.isdir(sdkDir):
    headerDir = sdkDir
else:
    headerDir = modDir
print headerDir
p = CParser(os.path.join(headerDir, "QCamApi.h"), cache=os.path.join(modDir, 'QCamApi.h.cache'), macros={'_WIN32': '', '__int64': ('long long')})

if sys.platform == 'darwin':
    dll = cdll.LoadLibrary('/Library/Frameworks/QCam.framework/QCam')
else:
    dll = windll.QCamDriver
lib = CLibrary(dll, p, prefix = 'QCam_')        ##makes it so that functions in the header file can be accessed using lib.nameoffunction, ie: QCam_LoadDriver is lib.LoadDriver
                                                ##also interprets all the typedefs for you....very handy
                                                ##anything from the header needs to be accessed through lib.yourFunctionOrParameter


#modDir = os.path.dirname(__file__)
#headerFiles = [
#    #"C:\Program Files\Photometrics\PVCam32\SDK\inc\master.h",
#    #"C:\Program Files\Photometrics\PVCam32\SDK\inc\pvcam.h"
#    os.path.join(modDir, "QCamApi.h")
#    #os.path.join(modDir, "pvcam.h")
#]
#HEADERS = CParser(headerFiles, cache=os.path.join(modDir, 'pvcam_headers.cache'), copyFrom=winDefs())
#LIB = CLibrary(windll.Pvcam32, HEADERS, prefix='pl_')
#

###functions that are called from CameraDevice:
# setUpCamera(self) - """Prepare the camera at least so that get/setParams will function correctly"""
# listParams(self, params=None)
# setParams(self, params, autoRestart=True, autoCorrect=True)
# getParams(self, params=None)
# quit(self)

externalParams = ['triggerMode',
                  #'triggerType', ## Add this in when we figure out TriggerModes
                  'exposure',
                  'binningX',
                  'binningY',
                  'regionX',
                  'regionY',
                  'regionW',
                  'regionH',
                  'gain',
                  'qprmS32AbsoluteOffset',
                  'qprmReadoutSpeed',
                  'qprmCoolerActive',
                  'qprmS32RegulatedCoolingTemp',
                  'qprmBlackoutMode',
                  'qprmSyncb',
                  'ringSize'
                  ]
cameraDefaults = {
    'ALL':{
        'qprmImageFormat':'qfmtMono16',
    }}

#def init():
#    ## System-specific code
#    global QCam
#    QCam = _QCamDriverClass()
        
class QCamFunctionError(Exception):
    def __init__(self, value, message):
        self.value = value
        self.message = message
    
    def __str__(self):
        return repr(self.message)

class QCamDriverClass:
    def __init__(self):
        self.cams = {}
        self.paramTable = OrderedDict()
        
        self.loadDriver()
        
        global externalParams
        for p in externalParams:
            self.paramTable[p] = p        
    
    def call(self, function, *args):
        """"""
        a = function(*args)
        if a() == None:
            return a
        elif a() != 0:
            for x in lib('enums', 'QCam_Err'):
                if lib('enums', 'QCam_Err')[x] == a():
                    raise QCamFunctionError(a(), "There was an error running %s. Error code = %s" %(function.name,x))
        else:
            return a

    def loadDriver(self):
        self.call(lib.LoadDriver)
 
    #def releaseDriver(self):
    #    self.call(lib.ReleaseDriver)
        
    def listCameras(self):
        number = c_ulong(10)
        L = lib.CamListItem * 10
        l = L()
        self.call(lib.ListCameras, l, number)
        cams = {}
        for x in list(l)[:number.value]:
            cams[x.uniqueId] = x.cameraId
        return cams
    
    def getCamera(self, cam):
        #print "QIdriver: getting camera...."
        if not self.cams.has_key(cam):
            #print "    creating camera class..."
            self.cams[cam] = QCameraClass(cam, self)
            #print "    camera class created for cam: %s" %cam
        return self.cams[cam]
        
    def __del__(self):
        if len(self.cams) != 0:
            self.quit()
        else:
            self.call(lib.ReleaseDriver)

    def quit(self):
        #print "quit() called from QCamDriverClass."
        for c in self.cams:
            self.cams[c].quit()
        self.call(lib.ReleaseDriver) ###what if we don't open the camera?

        try:
            sys.stdout.write('QImaging exit.\n')
        except:
            sys.stdout = sys.stderr
            print("Warning: Setting sys.stdout = sys.stderr as workaround for QImaging bug.")

        
class QCameraClass:
    def __init__(self, name, driver):
        #print "QCamera Class: setting self variables..."
        self.name = name
        self.driver = driver
        self.isOpen = False
        self.handle = self.open()
        self.ringSize = 10
        self.paramAttrs = OrderedDict()
        self.cameraInfo = {}
        self.frames = []
        self.arrays = []
        self.frameTimes = []
        self.i = 0
        self.stopSignal = True
        self.mutex = Mutex(Mutex.Recursive)
        self.lastImage = (None,0)
        self.fnp1 = lib.AsyncCallback(self.callBack1)
        self.fnpNull = lib.AsyncCallback(self.doNothing)
        self.counter = 0
        
        
{'fraction_non_alphanumeric': 0.11749301675977654, 'fraction_numerical': 0.006284916201117319, 'mean_word_length': 2.065008025682183, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '917318', 'n_tokens_mistral': 3612, 'n_tokens_neox': 3467, 'n_words': 841}