Beispiel #1
0
def check_bop_results(path, version='bop19'):
    """Checks if the format of BOP results is correct.

  :param result_filenames: Path to a file with pose estimates.
  :param version: Version of the results.
  :return: True if the format is correct, False if it is not correct.
  """
    check_passed = True
    check_msg = 'OK'
    try:
        results = load_bop_results(path, version)

        if version == 'bop19':
            # Check if the time for all estimates from the same image are the same.
            times = {}
            for result in results:
                result_key = '{:06d}_{:06d}'.format(result['scene_id'],
                                                    result['im_id'])
                if result_key in times:
                    if abs(times[result_key] - result['time']) > 0.001:
                        check_passed = False
                        check_msg = \
                          'The running time for scene {} and image {} is not the same for' \
                          ' all estimates.'.format(result['scene_id'], result['im_id'])
                        misc.log(check_msg)
                        break
                else:
                    times[result_key] = result['time']

    except Exception as e:
        check_passed = False
        check_msg = 'Error when loading BOP results: {}'.format(e)
        misc.log(check_msg)

    return check_passed, check_msg
    def __parseXMP(self, data, dataLen):
        if not self._file:
            assert False

        from XMPParser import XMPParser
        meta = XMPParser.parse(data)
        log('XMP = %s'%(str(meta)))
Beispiel #3
0
 def checkPromptMsg(self):
   if network.messageInBuffer('promptMsg'): #if a prompt message exists
     promptMessage = network.getMessageofType('promptMsg', False) #get the message
     misc.log('Relaying promptMessage \'' + promptMessage + '\'') #log the message
     for socketObj in socketList:
       #send the message to each socket in the socketList
       network.sendMessage('promtMsg', promptMessage, socketObj)
    def readSettings(self):
        log("Loading settings")
        addon = xbmcaddon.Addon()

        self.enable = addon.getSetting('hyperion_enable').lower() == 'true'
        self.enableScreensaver = addon.getSetting(
            'screensaver_enable').lower() == 'true'
        self.address = addon.getSetting("hyperion_ip")
        self.port = int(addon.getSetting("hyperion_port"))
        self.priority = int(addon.getSetting("hyperion_priority"))
        self.timeout = int(addon.getSetting("reconnect_timeout"))
        self.capture_width = int(addon.getSetting("capture_width"))
        self.capture_height = int(addon.getSetting("capture_height"))

        # Hack around Kodi's settings readout limitations
        self.useDefaultDelay = addon.getSetting(
            'use_default_delay').lower() == 'true'

        self.delay = int(addon.getSetting("delay"))
        self.delay24 = int(addon.getSetting("delay24"))
        self.delay25 = int(addon.getSetting("delay25"))
        self.delay50 = int(addon.getSetting("delay50"))
        self.delay59 = int(addon.getSetting("delay59"))
        self.delay60 = int(addon.getSetting("delay60"))

        self.rev += 1
Beispiel #5
0
def reconstruct(exportdir, filepaths, conn):
    global model
    global opt

    if model is None:
        opt = mlsim_lib.GetOptions_allRnd()
        model = mlsim_lib.LoadModel(opt)

    os.makedirs(exportdir, exist_ok=True)
    result_arr = []

    log('received filepaths %s' % filepaths)

    for idx, filepath in enumerate(filepaths):
        log('ITRERASTION %d %s' % (idx, filepath))
        # status reconstruction
        conn.send(("siReconstructing,%d,%d" % (idx, len(filepaths))).encode())
        ready = conn.recv(20).decode()

        outfile = '%s/%s' % (exportdir, datetime.datetime.utcnow().strftime(
            '%Y%m%d%H%M%S%f')[:-3])
        img = tiff.imread(filepath, key=range(9))
        sr, wf, out = mlsim_lib.EvaluateModel(model, opt, img, outfile)
        result_arr.append(sr)

    conn.send("sd".encode())  # status done
    ready = conn.recv(20).decode()

    return result_arr
Beispiel #6
0
def enableButton():
  global mainButton
  misc.log('enable button')
  for name, button in mainButton.items():
    #for each button in the list of buttons log the enabling of the buttons name and enable the button
    misc.log('enabled ' + name)
    button.config(state='normal')
Beispiel #7
0
def removeUsedType(type): #specify a type of message that you no longer want to listen for that is currently being listned for
  global usedTypes
  try:
    usedTypes.remove(type) #remove the type from the list
    misc.log('Removing type: ' + type + ' from usedType list') #log the removal
  except ValueError: #if the type is not in the list log the error and continue as normal
    misc.log('Type: \'' + type + '\' not in list - ignoring')
Beispiel #8
0
def disableButton():
  global mainButton
  misc.log('disable button')
  for name, button in mainButton.items():
    #for each button in the list of buttons log the disabling of the buttons name and disable the button
    misc.log('disabled ' + name)
    button.config(state='disabled')
Beispiel #9
0
    def __parseXMP(self, data, dataLen):
        if not self._file:
            assert False

        from XMPParser import XMPParser
        meta = XMPParser.parse(data)
        log('XMP = %s' % (str(meta)))
	def readSettings(self):
		'''(Re-)read all settings
		'''
		log("Reading settings")
		addon = xbmcaddon.Addon()
		self.enable = addon.getSetting('hyperion_enable').lower() == 'true'
		self.enableScreensaver = addon.getSetting('screensaver_enable').lower()  == 'true'
		self.address = addon.getSetting("hyperion_ip")
		self.port = int(addon.getSetting("hyperion_port"))
		self.priority = int(addon.getSetting("hyperion_priority"))
		self.timeout = int(addon.getSetting("reconnect_timeout"))
		self.capture_width = int(addon.getSetting("capture_width"))
		self.capture_height = int(addon.getSetting("capture_height"))

		# Hack around Kodi's settings readout limitations
		self.useDefaultDelay = addon.getSetting('use_default_delay').lower() == 'true'

		self.delay = int(addon.getSetting("delay"))
		self.delay24 = int(addon.getSetting("delay24"))
		self.delay25 = int(addon.getSetting("delay25"))
		self.delay50 = int(addon.getSetting("delay50"))
		self.delay59 = int(addon.getSetting("delay59"))
		self.delay60 = int(addon.getSetting("delay60"))

		self.showErrorMessage = True
		self.rev += 1
def removeUsedType(type):
    global usedTypes
    try:
        usedTypes.remove(type)
        misc.log('Removing type: ' + type + ' from usedType list')
    except ValueError:
        misc.log('Type: \'' + type + '\' not in list - ignoring')
 def unlockForPID(self, pid):
     lockF = self.lockfile + '.' + str(pid)
     try:
         os.rename(lockF, self.openfile)
         misc.log("Released lock from file " + lockF)
     except OSError as ex:
         if ex.errno == errno.ENOENT:
             misc.log("Lock already released from file " + lockF)
Beispiel #13
0
 def waitForGameStart(self):
   misc.log('Waiting for Game Start')
   if network.getMessageofType('startGUI'): #wait for a message of type startGUI with a blocking call
     self.startGame = True #allow the game to start
     misc.log('Relaying startGUI Command')
     for socketObj in socketList:
       #send a message to each socket in the socketList
       network.sendMessage('startGUI', [None], socketObj)
     network.removeUsedType('startGUI') #remove the startGUI message type from the list of used types
Beispiel #14
0
def getMessageofType(type=None, waitForMessage=True): #get a message of a specfic type
  global receivedMessages
  try:
    msg = receivedMessages.get(type, waitForMessage) #get a mesasge of the requsted type from the Queue
  except Empty:
    return None #if no messages of the requested type exist return an empty value
  else: #if a message of the requested type exists get and return it
    misc.log('Retreived Message: \'' + str(msg.getContent()) + '\' of type \'' + str(msg.type) + '\'') #log the message and its type
    return msg.getContent() 
def getMessageofType(type, waitForMessage=True):
    global receivedMessages
    try:
        msg = receivedMessages.get(type, waitForMessage)
    except Empty:
        return None
    else:
        misc.log('Retreived Message: \'' + str(msg.getContent()) + '\' of type \'' + str(msg.type) + '\'')
        return msg.getContent()
Beispiel #16
0
def load():
    from misc import log

    def _load_one(name):
        __import__(f"bot_modules.{name}", globals(), locals(), ["load"],
                   0).load()

    for _bm in __BML:
        log(f"Loading {_bm} module")
        _load_one(_bm)
Beispiel #17
0
    def dosbox_exec(cmd):
        commands = [f'mount W "{os.getcwd()}"', 'W:', cmd,
                    'exit']  # These run in DOS
        dosboxcmd = 'dosbox ' + ' '.join(
            '-c "{}"'.format(doscmd.replace('"', '\\"'))
            for doscmd in commands)

        log(2, cmd)
        log(3, "Final DOSBOX command is:\n" + dosboxcmd)
        os.system(dosboxcmd)
 def save_errors(_error_sign, _scene_errs):
     # Save the calculated errors to a JSON file.
     errors_path = p['out_errors_tpath'].format(
         eval_path=p['eval_path'],
         result_name=result_name,
         error_sign=_error_sign,
         scene_id=scene_id)
     misc.ensure_dir(os.path.dirname(errors_path))
     misc.log('Saving errors to: {}'.format(errors_path))
     inout.save_json(errors_path, _scene_errs)
Beispiel #19
0
 async def execute(msg):
     cmd_name = msg.content.split('!')[1].split(' ')[0].lower()
     log(f"Command [{cmd_name}] from [{str(msg.author)}]")
     try:
         cmd = next(x for x in Command.commands if x.name == cmd_name)
         await cmd.execute(msg)
     except StopIteration:
         await msg.channel.send("Bitte was soll ich machen? Den Command kenne ich nicht. Hast du dich vertippt?")
         await asyncio.sleep(1)
         await msg.channel.send("Wenn ich den kennen sollte, dann wende dich ans Klebi. Der hilft gerne.")
Beispiel #20
0
    def __init__(self, settings):
        '''
        State object.

        Args:
            settings (Settings): Settings structure
        '''
        misc.log('Entering %(name)s state',
                 name=self.__class__.__name__.lower())
        self._settings = settings
Beispiel #21
0
def statusUpdate(info):
  global displayStatus, status
  status_lines = config['Tk']['status_lines'] #get the max number of lines the status should be
  status.append(info) #append the latest status to the list
  misc.log(info) #log the status
  while len(status) > status_lines: #if the status is larger than it should be remove the earlier statuses
    status.pop(0) #remove the first status from the list
  displayStatus.set('') #clear the statu diaplyed to the user
  
  for info in status: #for all the 
    displayStatus.set(displayStatus.get()+info+'\n')
Beispiel #22
0
    def run(self, project):
        self.apply_preset(project.presets)

        # Compile objects first
        for obj in self.objects:
            obj.run(project)

        obj_files = flatten([o.get_files() for o in self.objects])
        log(1, 'compile {} -> {}'.format(str(obj_files), self.output))
        self.compiler.create_shlib(untempl(self.output, project.props),
                                   obj_files, self.linked_libs, self.params)
    def playerStateChangedCB(self, state):
        if state == HyperionPlayer.GRABBING_START:
            self.capture = xbmc.RenderCapture()
            self.capture.capture(settings.capture_width,
                                 settings.capture_height)
        elif state == HyperionPlayer.GRABBING_STOP:
            if not self.hyperion.isConnected():
                log("grabbing stopped but client was not connected")
                return

            self.hyperion.clear(settings.priority)
            log("clearing priority")
Beispiel #24
0
    def __init__(self):
        log("Constructing Bot")
        
        from bot import Bot

        self.ee = EventEmitter()

        self.config = object() # __postinit
        self.igp = []          # __postinit

        self.bot = Bot()

        self.__pi_done = False
Beispiel #25
0
    def run(self, project):
        # Apply preset
        if self._preset_name:
            preset = project.presets[self._preset_name]
            preset = update_preset(preset, self.params)
            self.params = preset

        if not self.file:
            for i in range(len(self.source)):
                log(1, 'compile {} -> {}'.format(self.source[i],
                                                 self.output[i]))
                self.compiler.create_object(self.output[i], self.source[i],
                                            self.params)
	def readSettings(self):
		'''(Re-)read all settings
		'''
		log("Reading settings")
		addon = xbmcaddon.Addon()
		self.enable = bool(addon.getSetting("hyperion_enable"))
		self.enableScreensaver = bool(addon.getSetting("screensaver_enable"))
		self.address = addon.getSetting("hyperion_ip")
		self.port = int(addon.getSetting("hyperion_port"))
		self.priority = int(addon.getSetting("hyperion_priority"))
		self.timeout = int(addon.getSetting("reconnect_timeout"))
		self.showErrorMessage = True
		self.rev += 1
    def process(self):
        if playerMonitor.getGrabbingState(
        ) != HyperionPlayer.GRABBING_START or not xbmc.getCondVisibility(
                "Player.Playing"):
            xbmc.sleep(100)
            return

        rawImgBuf = self.capture.getImage(
        )  # lets wait up to 250ms for an image, otherwise we are lagging behind heavily
        rawImgLen = len(rawImgBuf)
        expectedLen = settings.capture_width * settings.capture_height * 4
        if rawImgLen < expectedLen:
            # Check if we got a null image from the renderer.
            if rawImgLen == 0:
                return

            log("Faulty image! Size was: %d expected: %d" %
                (rawImgLen, expectedLen))
            return

        # Convert image to RGB from BGRA (default after 17)
        del rawImgBuf[3::4]
        rawImgBuf[0::3], rawImgBuf[2::3] = rawImgBuf[2::3], rawImgBuf[0::3]

        # If this call fails, it will make us reconnect.
        if not self.hyperion.sendImage(settings.capture_width,
                                       settings.capture_height, rawImgBuf, -1):
            notify(xbmcaddon.Addon().getLocalizedString(32101))
            return

        sleeptime = settings.delay

        if settings.useDefaultDelay == False:
            try:
                videofps = math.ceil(
                    float(xbmc.getInfoLabel('Player.Process(VideoFPS)')))
                if videofps == 24:
                    sleeptime = self.__settings.delay24
                if videofps == 25:
                    sleeptime = self.__settings.delay25
                if videofps == 50:
                    sleeptime = self.__settings.delay50
                if videofps == 59:
                    sleeptime = self.__settings.delay59
                if videofps == 60:
                    sleeptime = self.__settings.delay60
            except ValueError:
                pass

        # Minimum sleep of 1 millisecond otherwise the event processing dies.
        xbmc.sleep(max(1, sleeptime))
    def connect(self):
        try:
            self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            self.__socket.settimeout(2)
            self.__socket.connect((self.config.address, self.config.port))
            self.Register("HyperionKodiAddon v2", 1)

            self.connected = True
            return True
        except socket.error, e:
            log("connect failed: %s" % e)
            self.enterFailureState()
            return False
    def clear(self, priority):
        '''Clear the given priority channel
        - priority : the priority channel to clear
        '''

        log("Clear blocked, conflicting implementation")
        return

        builder = flatbuffers.Builder(0)

        ClearStart(builder)

        if priority != -1:
            ClearAddPriority(builder, priority)

        return self.__sendMessage(builder, Command.Clear, ClearEnd(builder))
Beispiel #30
0
def load_file(fp):
    """
    load_file reads the file at path `fp` and returns a save object for the data contained

    :param fp: Filepath to .sav file
    :return: save object for that data
    """
    try:
        with open(fp, "rb+") as f:
            misc.log(f"File loaded from: {fp}", 'debug')
            contents = f.read()
    except Exception as e:
        misc.log(
            e,
            'critical',
            crashmsg="Fatal error encountered loading file with load_file().")
    return classes.save(contents, fp)
    def __init__(self, settings):
        '''Constructor
			- settings: Settings structure
		'''
        log("Entering connected state")

        self.__settings = settings
        self.__hyperion = None
        self.__capture = None

        # try to connect to hyperion
        self.__hyperion = Hyperion(self.__settings.address,
                                   self.__settings.port)

        # create the capture object
        self.__capture = xbmc.RenderCapture()
        self.__capture.capture(64, 64)
    def __sendMessage(self, builder, commandType, command):
        '''Send the given flatbuffers message to Hyperion. 
        - message : flatbuffers request to send
        '''
        try:
            RequestStart(builder)
            RequestAddCommandType(builder, commandType)
            RequestAddCommand(builder, command)
            builder.Finish(RequestEnd(builder))

            msg = builder.Output()
            self.__socket.sendall(struct.pack(">I", len(msg)) + msg)
            return True
        except Exception, e:
            self.enterFailureState()
            log("__sendMessage: %s" % e)
            return False
	def readSettings(self):
		'''(Re-)read all settings
		'''
		log("Reading settings")
		addon = xbmcaddon.Addon()
		self.enable = bool(addon.getSetting("hyperion_enable"))
		self.enableScreensaver = bool(addon.getSetting("screensaver_enable"))
		self.address = addon.getSetting("hyperion_ip")
		self.port = int(addon.getSetting("hyperion_port"))
		self.priority = int(addon.getSetting("hyperion_priority"))
		self.timeout = int(addon.getSetting("reconnect_timeout"))
		self.capture_width = int(addon.getSetting("capture_width"))
		self.capture_height = int(addon.getSetting("capture_height"))
		self.framerate = int(addon.getSetting("framerate"))

		self.showErrorMessage = True
		self.rev += 1
Beispiel #34
0
def socketserver():
    misc.log('starting socketserver')
    host = 'localhost'
    port = int(sys.argv[1])

    server_socket = socket.socket()  # get instance
    # look closely. The bind() function takes tuple as argument
    server_socket.bind((host, port))  # bind host address and port together

    # configure how many client the server can listen simultaneously
    server_socket.listen(1)
    while True:
        print('now listening')
        conn, address = server_socket.accept()  # accept new connection
        th = threading.Thread(target=run_command, args=(conn, address))
        th.daemon = True
        th.start()
def attemptConnect(socketObj, address, port):
    try:
        misc.log('Attempting to connect to ' + str(address) + ' on port ' + str(port))
        socketObj.connect((address, port))
        misc.log('Successfully connected to ' + str(address) + ' on port ' + str(port))
        addListningDaemon(socketObj)
        misc.log('Starting Listning Daemon')
        return True
    except OSError as exception:
        misc.log('Failed to connect to ' + str(address) + ' on port ' + str(port) + ' - \'' + str(exception) + '\'')
        return False
Beispiel #36
0
    def execute(self):
        '''Execute the state
          - return: The new state to execute
        '''
        # check if we still need to grab
        if not self.__settings.grabbing():
            self.clear_priority()

            # return to the disconnected state
            return DisconnectedState(self.__settings)
        # capture an image
        startReadOut = False

        self.__data = self.__capture.getImage()
        if len(self.__data) > 0:
            startReadOut = True

        if startReadOut:
            # retrieve image data and reformat into rgb format
            if self.__capture.getImageFormat() == 'BGRA':
                del self.__data[3::4]
                self.__data[0::3], self.__data[2::3] = self.__data[
                    2::3], self.__data[0::3]
                ba = self.__data
                size = (self.__capture.getWidth(), self.__capture.getHeight())
                img = Image.frombuffer('RGB', size, str(ba), 'raw', 'RGB', 0,
                                       1)
                #img.save("C:/tmp/kodi/image"+str(self.__counter)+".jpg")
                img.save("/storage/screenshots/" + str(self.__counter) +
                         ".jpg")
                log("Saved image " + str(self.__counter) + ".jpg")
                self.__counter += 1

            try:
                # send image to hyperion
                self.__hyperion.sendImage(self.__capture.getWidth(),
                                          self.__capture.getHeight(),
                                          str(self.__data),
                                          self.__settings.priority, -1)
            except Exception, e:
                # unable to send image. notify and go to the error state
                log(e)
                notify(xbmcaddon.Addon().getLocalizedString(32101))
                return ErrorState(self.__settings)
def write_text_on_image(im,
                        txt_list,
                        loc=(3, 0),
                        color=(1.0, 1.0, 1.0),
                        size=20):
    """Writes text info on an image.

  :param im: ndarray on which the text info will be written.
  :param txt_list: List of dictionaries, each describing one info line:
    - 'name': Entry name.
    - 'val': Entry value.
    - 'fmt': String format for the value.
  :param loc: Location of the top left corner of the text box.
  :param color: Font color.
  :param size: Font size.
  :return: Image with written text info.
  """
    im_pil = Image.fromarray(im)

    # Load font.
    try:
        font_path = os.path.join(os.path.dirname(__file__),
                                 'droid_sans_mono.ttf')
        font = ImageFont.truetype(font_path, size)
    except IOError:
        misc.log('Warning: Loading a fallback font.')
        font = ImageFont.load_default()

    draw = ImageDraw.Draw(im_pil)
    for info in txt_list:
        if info['name'] != '':
            txt_tpl = '{}:{' + info['fmt'] + '}'
        else:
            txt_tpl = '{}{' + info['fmt'] + '}'
        txt = txt_tpl.format(info['name'], info['val'])
        draw.text(loc,
                  txt,
                  fill=tuple([int(c * 255) for c in color]),
                  font=font)
        text_width, text_height = font.getsize(txt)
        loc = (loc[0], loc[1] + text_height)
    del draw

    return np.array(im_pil)
Beispiel #38
0
def attemptConnect(socketObj, address, port):
  try:
    misc.log('Attempting to connect to ' + str(address) + ' on port ' + str(port)) #log the attempt to connect
    socketObj.connect((address, port)) #connect to the serversocket
    misc.log('Successfully connected to ' + str(address) + ' on port ' + str(port))
    addListningDaemon(socketObj) #add a listner for the connection
    misc.log('Starting Listning Daemon')
    return True #return True => connection succesful
  except OSError as exception: #if the connection failed
    misc.log('Failed to connect to ' + str(address) + ' on port ' + str(port) + ' - \'' + str(exception) + '\'') #log the failure
    return False #reuturn False => connection unsuccesful
	def __init__(self, settings):
		'''Constructor
			- settings: Settings structure
		'''
		log("Entering connected state")

		self.__settings = settings
		self.__hyperion = None
		self.__capture = None
		self.__captureState = None
		self.__data = None
		self.__useLegacyApi = True

		# try to connect to hyperion
		self.__hyperion = Hyperion(self.__settings.address, self.__settings.port)

		# create the capture object
		self.__capture = xbmc.RenderCapture()
		self.__capture.capture(self.__settings.capture_width, self.__settings.capture_height)
Beispiel #40
0
def GetMultiFunctionTableHelper(_fd, sig, tagStartPos):
    reserved = getBytes4(_fd)
    assert reserved == 0
    numOfInputChannel = getCharToOrd(_fd)
    numOfOutputChannel = getCharToOrd(_fd)
    numOfCLUTGridPoints = getCharToOrd(_fd)
    padding = getCharToOrd(_fd)
    assert padding == 0
    encodedParas = []
    for _ in xrange(9):
        encodedParas.append(GetS15Fixed16Number(_fd))
    numOfInputTableEntries = getBytes2(_fd)
    numOfOutputTableEntries = getBytes2(_fd)

    log(" InChannels(%d) / OutChannels(%d) / GridPts(%d) / EncodedPars(%s)"\
        %(numOfInputChannel, numOfOutputChannel, numOfCLUTGridPoints,\
          str(encodedParas)))
    log(" InTableEntries(%d) / OutTableEntries(%d)"\
        %(numOfInputTableEntries, numOfOutputTableEntries))

    inputTables = []
    for _ in xrange(numOfInputChannel):
        tmp = []
        for __ in xrange(numOfInputTableEntries):
            tmp.append(getBytes2(_fd))
        inputTables.append(tmp)

    clut = []
    for _ in xrange(numOfCLUTGridPoints ** numOfInputChannel):
        tmp = []
        for __ in xrange(numOfOutputChannel):
            tmp.append(getBytes2(_fd))
        clut.append(tmp)

    outputTables = []
    for _ in xrange(numOfOutputChannel):
        tmp = []
        for __ in xrange(numOfOutputTableEntries):
            tmp.append(getBytes2(_fd))
        outputTables.append(tmp)

    return Lut16(sig, encodedParas, inputTables, clut, outputTables)
Beispiel #41
0
def GetCurveHelper(_fd, sig):
    reserved = getBytes4(_fd)
    assert reserved == 0
    count = getBytes4(_fd)

    exp = None
    tblLookUp = []
    if count in [0, 1]:
        first = 1.0 if count == 0 else getCharToOrd(_fd)
        second = 0.0 if count == 0 else getCharToOrd(_fd)
        exp = first + float(second/256.0)
        log(" count = %d / exp(%f)"%(count, exp))
    else:
        for _ in xrange(count):
            first, second = getCharToOrd(_fd), getCharToOrd(_fd)
            v = first + float(second/256.0)
            tblLookUp.append(v)
        log(" count = %d "%(count))
    sigDescObj = Curve(sig, exp, tblLookUp)
    return sigDescObj
Beispiel #42
0
def importQuestions(file):
  global status
  statusUpdate('Importing Questions...')
  questions = [] #Create an empty list to store the questions in
  cnt = 0 #Cnt the number of questions imported
  with open(file) as csvfile: #Open the CSV file
    questionfile = csv.reader(csvfile) #Return an iter object from the csvfile
    for row in questionfile: #For each item in the iter object / for each row in the csvfile
      try:
        #where row[0] = questions & row[1] = answer & row[2] = round to ask question in / difficulty
        if row[0] and row[1] and row[2]: #If a question difficulty is provided import the question and the difficulty
          questions.append([row[0], row[1], int(row[2])])
        elif row[0] and row[1]: #If a question difficulty is not provided don't import it
          questions.append([row[0], row[1]])
        cnt += 1 #Increment the counter for the number of questions imported -> call this last so that it won't run if an error is caught by the try: except:
      except: #Catch any errors opening/reading the question file
        misc.log('Error importing question - ' + str(sys.exc_info())) #Log the error
    statusUpdate('Imported ' + str(cnt) + ' Questions') #Update the status listing how many questions have been imported
    #with statement automatically closes the csv file cleanly even in event of unexpected script termination
    return questions #Return a list of questions
 def __parseAPP2(self, length):
     curPos = nowAt(self._file)
     iptcData = getChar(self._file, length)
     iccIdentifier = "ICC_PROFILE"
     if (iptcData.startswith(iccIdentifier)):
         iccData = iptcData[len(iccIdentifier)+1:]
         iccLen = 0
         if ord(iccData[0]) == 0x01 and ord(iccData[1]) == 0x01:
             iccLen = length -14
         elif ord(iccData[0]) == 0x01: # multi-page, support header only
             iccLen = 128
         else:
             log("Wrong ICC Profile format !")
             return
         seekTo(self._file, curPos+14)
         from ICCProfileParser import ICCProfileParser
         iccParser = ICCProfileParser(self._file)
         iccParser.parse()
     else:
         log("Wrong ICC Profile format !")
         assert False
Beispiel #44
0
    def __init__(self, settings):
        '''Constructor
          - settings: Settings structure
        '''
        log("Entering connected state")

        self.__settings = settings
        self.__hyperion = None
        self.__capture = None
        self.__captureState = None
        self.__data = None

        # try to connect to hyperion
        self.__hyperion = Hyperion(self.__settings.address, self.__settings.port)

        # Force clearing of priority (mainly for Orbs)
        self.clear_priority()

        # create the capture object
        self.__capture = xbmc.RenderCapture()
        self.__capture.capture(self.__settings.capture_width, self.__settings.capture_height)
Beispiel #45
0
        def parseTagTable():
            log("Enter", "[ICCProfileTagTable]", "add")
            tagCount = getBytes4(self._fd)
            log("Tag count = %d"%(tagCount))
            for idx in xrange(tagCount):
                tagStartPos = nowAt(self._fd)
                sig = ''.join(getChar(self._fd) for _ in xrange(4))
                offset = getBytes4(self._fd)
                size = getBytes4(self._fd)
                seekTo(self._fd, basePos+offset)
                log("Tag sig(%s) / offset(%d) / size(%d) / basePos(%d) / tagSigPos(%d) / tagTypePos(%d) "%(sig, offset, size, basePos, tagStartPos, basePos+offset))
                typeDesc = ''.join(getChar(self._fd) for _ in xrange(4))
                log("Type Desc(%s)"%(typeDesc))
                sigDescObj = GetSigObject(sig, typeDesc, self._fd, size, basePos+offset)
                assert sig not in self.__dicSig2TagInfo, "Check this file, two same sig !"
                self.__dicSig2TagInfo[sig] = sigDescObj
                seekTo(self._fd, tagStartPos+12)

            log("Leave", "[ICCProfileTagTable]", "remove")
            pprint.pprint(self.__dicSig2TagInfo)
            pass
Beispiel #46
0
    def __init__(self, settings):
        '''Constructor
			- settings: Settings structure
		'''
        log("Entering connected state")

        self.__settings = settings
        self.__hyperion = None
        self.__capture = None
        self.__captureState = None
        self.__data = None
        self.__useLegacyApi = True

        # try to connect to hyperion
        self.__hyperion = Hyperion(self.__settings.address,
                                   self.__settings.port)

        # create the capture object
        self.__capture = xbmc.RenderCapture()
        self.__capture.capture(self.__settings.capture_width,
                               self.__settings.capture_height)
Beispiel #47
0
 def __parseAPP2(self, length):
     curPos = nowAt(self._file)
     iptcData = getChar(self._file, length)
     iccIdentifier = "ICC_PROFILE"
     if (iptcData.startswith(iccIdentifier)):
         iccData = iptcData[len(iccIdentifier) + 1:]
         iccLen = 0
         if ord(iccData[0]) == 0x01 and ord(iccData[1]) == 0x01:
             iccLen = length - 14
         elif ord(iccData[0]) == 0x01:  # multi-page, support header only
             iccLen = 128
         else:
             log("Wrong ICC Profile format !")
             return
         seekTo(self._file, curPos + 14)
         from ICCProfileParser import ICCProfileParser
         iccParser = ICCProfileParser(self._file)
         iccParser.parse()
     else:
         log("Wrong ICC Profile format !")
         assert False
    def __parseIFDs(self, base, start, end, IFD=""):
        assert IFD != ""
        log("Enter", "[%s]"%(IFD), "add")

        if not self._file:
            assert False
        entries = getBytes2(self._file, self._orderAPP1)
        log("Number of entries = %d"%(entries))

        for idx in xrange(entries):
            tag = getBytes2(self._file, self._orderAPP1)
            dataFormat = getBytes2(self._file, self._orderAPP1)
            numOfComps = getBytes4(self._file, self._orderAPP1)
            posBeforeDataOffset = nowAt(self._file)
            dataOffset = getBytes4(self._file, self._orderAPP1)
            posAfterDataOffset = nowAt(self._file)

            if 0 == dataFormat or dataFormat >= len(EXIF_TIFF_DATAFORMAT_LIST):
                assert False, "dataformat incorrect = %d"%(dataFormat)
                continue
            bytesPerComp = EXIF_TIFF_DATAFORMAT_LIST[dataFormat]
            dataSize = bytesPerComp * numOfComps
            if dataSize > 4:
                targetOffset = base + dataOffset
                if targetOffset <= start or targetOffset >= end:
                    continue
                else:
                    seekTo(self._file, targetOffset)
            else:
                seekTo(self._file, posBeforeDataOffset)
            entry = self.__getDataFromFormat(tag, dataFormat, dataSize)
            seekTo(self._file, posAfterDataOffset)

        log("Leave", "[%s]"%(IFD), "remove")
def GetParaCurveHelper(_fd, sig):
    reserved = getBytes4(_fd)
    assert reserved == 0
    funcType = getBytes2(_fd)
    reserved2 = getBytes2(_fd)
    assert reserved2 == 0
    para_g = para_a = para_b = para_c = para_d = para_e = para_f = None

    if funcType == 0:
        para_g = GetS15Fixed16Number(_fd)
    elif funcType == 1:
        para_g = GetS15Fixed16Number(_fd)
        para_a = GetS15Fixed16Number(_fd)
        para_b = GetS15Fixed16Number(_fd)
    elif funcType == 2:
        para_g = GetS15Fixed16Number(_fd)
        para_a = GetS15Fixed16Number(_fd)
        para_b = GetS15Fixed16Number(_fd)
        para_c = GetS15Fixed16Number(_fd)
    elif funcType == 3:
        para_g = GetS15Fixed16Number(_fd)
        para_a = GetS15Fixed16Number(_fd)
        para_b = GetS15Fixed16Number(_fd)
        para_c = GetS15Fixed16Number(_fd)
        para_d = GetS15Fixed16Number(_fd)
    elif funcType == 4:
        para_g = GetS15Fixed16Number(_fd)
        para_a = GetS15Fixed16Number(_fd)
        para_b = GetS15Fixed16Number(_fd)
        para_c = GetS15Fixed16Number(_fd)
        para_d = GetS15Fixed16Number(_fd)
        para_e = GetS15Fixed16Number(_fd)
        para_f = GetS15Fixed16Number(_fd)
    sigDescObj = ParaCurve(sig, para_g, para_a, para_b, para_c, para_d,\
                           para_e, para_f)
    log(" ParaCurve - g(%s), a(%s), b(%s), c(%s), d(%s), e(%s), f(%s)"%(\
        str(para_g), str(para_a), str(para_b), str(para_c), str(para_d),\
        str(para_e), str(para_f)))
    return sigDescObj
def GetMlucHelper(_fd, sig, tagStartPos):
    reserved = getBytes4(_fd)
    assert reserved == 0
    numOfRecords = getBytes4(_fd)
    recordSize = getBytes4(_fd)
    log(" numOfRecords = %d / recordSize = %s"%(numOfRecords, recordSize))

    sigDescObj = MultiLocalizedUnicode(sig)
    for _ in xrange(numOfRecords):
        langCode = ''.join(getChar(_fd) for i in xrange(2))
        langCountryCode = ''.join(getChar(_fd) for i in xrange(2))
        lenRecordString = getBytes4(_fd)
        offsetRecordString = getBytes4(_fd)

        here = nowAt(_fd)
        seekTo(_fd, tagStartPos + offsetRecordString)
        uniBytes = getChar(_fd, lenRecordString)
        # TODO : Think a better way to store these special unicode glyph
        uniChar = unicode(uniBytes, errors='replace')
        log(" uniChar = %s"%(uniChar))
        sigDescObj.add(langCode, langCountryCode, uniChar)
        seekTo(_fd, here)
    return sigDescObj
Beispiel #51
0
 def weakestLink(self):    
   statusUpdate('You must now choose the Weakest Link')
   i = 1 #index of the contestant currently being examined
   while i - 1 < len(self.contestants): #loop through each of the contestants
     statusUpdate(str(i) + '\t' + self.contestants[i-1].name + '\t' + str(self.contestants[i-1].score)) #update the status with the contestant index, name and score
     i += 1 #increment the index of the contestant currently being examined
   sendClientEvent('contestantUpdate', self.contestants) #update the clients with the latest list of contestants
   sendClientEvent('eliminationWait', [None]) #update the clients to select a contestant to eliminate
   while not self.end: #while the game should not end
     if network.messageInBuffer('removeContestant'): #wait for a contestant to be removed by one of the clients
       index = [contestant.uuid for contestant in self.contestants].index(network.getMessageofType('removeContestant', False)) #get the index of the contestant in the list of contestants to be removed
       eliminated = self.contestants[index] #get the contestant to be eliminated from the index
       statusUpdate(eliminated.name + ' you are the Weakest Link! Goodbye') #update the status with the eliminated contestant
       self.removedContestants.append(self.contestants.pop(index)) #remove the contestant from the list of contestants in the game and add it to the list of contestants removed from the game
       sendClientEvent('contestantEliminated', [eliminated]) #update the clients with the details of the eliminated contestant
       time.sleep(1) #give the clients time to display that the contestant has been eliminated
       break #no need to wait for another contestant to be eliminated so break out of the receive loop
       
     #server acts as a relay for prompt message
     if network.messageInBuffer('promptMsg'): #if a prompt message is in the network buffer
       promptMessage = network.getMessageofType('promptMsg', False) #get the message from the buffer
       misc.log('Relaying promptMessage \'' + promptMessage + '\'') #display the prompt message in the status log
       for socketObj in socketList:
         network.sendMessage('promtMsg', promptMessage, socketObj) #send the message to all the clients
def getMessage(socketObj):
    global receivedMessages
    while True:
        try:
            received = socketObj.recv(4096)
        except ConnectionResetError as exception:
            misc.log(str(exception))
            misc.log('Stopping Listning Daemon')
            break
        try:
            received = pickle.loads(received)
            if received.checkHash() == False:
                raise ValueError('The Checksum Failed')
        except (EOFError, ValueError, AttributeError) as exception:
            misc.log('Message Check Failed: \'' + str(exception) + '\'')
        else:
            receivedMessages.put(received, block=False)
            misc.log('Received the following Message: \''+ str(received.getContent()) + '\' of type \'' + str(received.type) + '\'')
Beispiel #53
0
def getMessage(socketObj): #get any messages in the sockets buffer
  global receivedMessages
  while True: #loop until a break
    try:
      received = socketObj.recv(4096) #blocking call waiting for their to be data in the sockets buffer
    except ConnectionResetError as exception: #if the conection is closed
      misc.log(str(exception)) #log the exception
      misc.log('Stopping Listning Daemon')
      break #break out of the loop (stop listning for messages)
    try:
      received = pickle.loads(received) #unpickle the message
      if received.checkHash() == False: #check if the message was correctly transmitted
        raise ValueError('The Checksum Failed') #raise an exception if the message was not transmitted correctly
    except (EOFError, ValueError, AttributeError) as exception:
      misc.log('Message Check Failed: \'' + str(exception) + '\'') #log any errors
    else: #if no errors occured
      receivedMessages.put(received, block=False) #put the message in the message Queue
      misc.log('Received the following Message: \''+ str(received.getContent()) + '\' of type \'' + str(received.type) + '\'') #log the receipt of the message 
Beispiel #54
0
 def lock(self):
     while (True):
         try:
             self.takeFileLock()
             break
         except OSError as ex:
             if ex.errno != errno.ENOENT:
                 misc.log('Got error ' , ex, ' , Continuing without taking any action')
             misc.log ('Going to wait for lock for : ', self.lockCheckSleepTimeSec, ' Seconds')
             time.sleep(self.lockCheckSleepTimeSec)
             lockfile = self.findLockFile()
             isProcessAlive = 1
             if(lockfile):
                isProcessAlive = self.isProcessAlive(lockfile)
                if(not isProcessAlive):
                   misc.log("Going to release the lock forcefully as process not Alive")
                   self.unlockForFile(lockfile)
                if(time.time() - self.getLockChangeTime() >= self.lockTimeOutSec):
                   misc.log("Going to release the lock forcefully as process Took long time to release lock")
                   self.unlockForFile(lockfile)
 def get(self, type, block=True, timeout=None):
     global usedTypes
     try:
         while block or self.types[type] > 0:
             item = super().get(block, timeout)
             misc.log('Got item \'' + str(item.type) + '\' from Stack')
             self.task_done()
             if item.type in usedTypes:
                 self.types[item.type] -= 1 #decrease the number of that type in the queue
                 if item.type == type: #put the item back if its a usedType but not of the type specified
                     misc.log('Stack Size: ' + str(self.qsize()))
                     return item
                 else:
                     self.put(item)
                     misc.log('Putting Item \'' + str(item.type) + '\' back into Stack')
             else: #if the item is not put back in the queue decrease the number of that type in the queue
                 misc.log('Removing Item \'' + str(item.type) + '\' from Stack as type not in usedTypes List')
                 self.types[item.type] -= 1
         raise Empty()
     except KeyError:
         raise Empty()