Пример #1
0
    def popLayer(self, layer):
        Log.debug("View: Pop: %s" % layer.__class__.__name__)

        if layer in self.incoming:
            self.incoming.remove(layer)
        if layer in self.layers and not layer in self.outgoing:
            self.outgoing.append(layer)
Пример #2
0
    def popLayer(self, layer):
        Log.debug("View: Pop: %s" % layer.__class__.__name__)

        if layer in self.incoming:
            self.incoming.remove(layer)
        if layer in self.layers and not layer in self.outgoing:
            self.outgoing.append(layer)
Пример #3
0
    def loadVideo(self, libraryName, songName):
        vidSource = None

        if self.songStage == 1:
            songBackgroundVideoPath = os.path.join(libraryName, songName, "background.ogv")
            if os.path.isfile(songBackgroundVideoPath):
                vidSource = songBackgroundVideoPath
                loop = False
            else:
                Log.warn("Video not found: %s" % songBackgroundVideoPath)

        if vidSource is None:
            vidSource = os.path.join(self.pathfull, "default.ogv")
            loop = True

        if not os.path.isfile(vidSource):
            Log.warn("Video not found: %s" % vidSource)
            Log.warn("Falling back to default stage mode.")
            self.mode = 1 # Fallback
            return

        try: # Catches invalid video files or unsupported formats
            Log.debug("Attempting to load video: %s" % vidSource)
            self.vidPlayer = VideoLayer(self.engine, vidSource,
                                        mute = True, loop = loop)
            self.engine.view.pushLayer(self.vidPlayer)
        except (IOError, VideoPlayerError):
            self.mode = 1
            Log.error("Failed to load song video (falling back to default stage mode):")
Пример #4
0
    def loadVideo(self, libraryName, songName):
        vidSource = None

        if self.songStage == 1:
            songBackgroundVideoPath = os.path.join(libraryName, songName,
                                                   "background.ogv")
            if os.path.isfile(songBackgroundVideoPath):
                vidSource = songBackgroundVideoPath
                loop = False
            else:
                Log.warn("Video not found: %s" % songBackgroundVideoPath)

        if vidSource is None:
            vidSource = os.path.join(self.pathfull, "default.ogv")
            loop = True

        if not os.path.isfile(vidSource):
            Log.warn("Video not found: %s" % vidSource)
            Log.warn("Falling back to default stage mode.")
            self.mode = 1  # Fallback
            return

        try:  # Catches invalid video files or unsupported formats
            Log.debug("Attempting to load video: %s" % vidSource)
            self.vidPlayer = VideoLayer(self.engine,
                                        vidSource,
                                        mute=True,
                                        loop=loop)
            self.engine.view.pushLayer(self.vidPlayer)
        except (IOError, VideoPlayerError):
            self.mode = 1
            Log.error(
                "Failed to load song video (falling back to default stage mode):"
            )
Пример #5
0
 def __init__(self, engine, controlnum, samprate=44100):
     Task.__init__(self)
     self.engine = engine
     self.controlnum = controlnum
     devnum = self.engine.input.controls.micDevice[controlnum]
     if devnum == -1:
         devnum = None
         self.devname = pa.get_default_input_device_info()['name']
     else:
         self.devname = pa.get_device_info_by_index(devnum)['name']
     self.mic = pa.open(samprate, 1, pyaudio.paFloat32, input=True, input_device_index=devnum, start=False)
     self.analyzer = pypitch.Analyzer(samprate)
     self.mic_started = False
     self.lastPeak    = 0
     self.detectTaps  = True
     self.tapStatus   = False
     self.tapThreshold = -self.engine.input.controls.micTapSensitivity[controlnum]
     self.passthroughQueue = []
     passthroughVolume = self.engine.input.controls.micPassthroughVolume[controlnum]
     if passthroughVolume > 0.0:
         Log.debug('Microphone: creating passthrough stream at %d%% volume' % round(passthroughVolume * 100))
         self.passthroughStream = Audio.MicrophonePassthroughStream(engine, self)
         self.passthroughStream.setVolume(passthroughVolume)
     else:
         Log.debug('Microphone: not creating passthrough stream')
         self.passthroughStream = None
Пример #6
0
    def create_table(self):
        """ Creates a table for the class in which every instance object which
        starts with 'c_'. For example 'c_id'. This variable can be accessed
        with self["c_id"]

        returns self
        """
        import re
        Log.debug("Creating Table for %s" % self.__name__)
        cursor = self.db_connection.cursor()
        sql = "CREATE TABLE "
        sql += self.__name__
        sql += """ (
                c_pk INTEGER PRIMARY KEY AUTOINCREMENT,
                date DATE,
                adapter TEXT"""
        attrs = self.get_attributes()
        if not 'c_id' in attrs:
            raise AttributeError('c_id not defined')
        for i in attrs:
            if i == 'c_pk':
                continue
            if i == "c_id":
                sql += ", %s UNIQUE" % i
            elif re.search('^f_(?P<classname>.+?)_.+', i):
                class_match = re.match('^f_(?P<classname>.+?)_.+', i)
                referenced_class = class_match.groupdict()['classname']
                sql += ', %s REFERENCES %s (c_pk)' % (i, referenced_class)
            else:
                sql += ", %s" % i
        sql += ");"
        Log.debug('Creating table, executing query: ' + sql)
        cursor.execute(sql)
        self.db_connection.commit()
        return self
Пример #7
0
 def start(self):
     if not self.mic_started:
         self.mic_started = True
         self.mic.start_stream()
         self.engine.addTask(self, synchronized=False)
         Log.debug('Microphone: started %s' % self.devname)
         if self.passthroughStream is not None:
             Log.debug('Microphone: starting passthrough stream')
             self.passthroughStream.play()
Пример #8
0
    def remove(self):
        """ Remove component with given name.

        Returns True if the component successfully removed.
        """
        Log.debug("Pubkey.remove(): removing")
        self._remove_key()
        super().remove()
        return True
Пример #9
0
 def stop(self):
     if self.mic_started:
         if self.passthroughStream is not None:
             Log.debug('Microphone: stopping passthrough stream')
             self.passthroughStream.stop()
         self.engine.removeTask(self)
         self.mic.stop_stream()
         self.mic_started = False
         Log.debug('Microphone: stopped %s' % self.devname)
Пример #10
0
 def start(self):
     if not self.mic_started:
         self.mic_started = True
         self.mic.start_stream()
         self.engine.addTask(self, synchronized=False)
         Log.debug('Microphone: started %s' % self.devname)
         if self.passthroughStream is not None:
             Log.debug('Microphone: starting passthrough stream')
             self.passthroughStream.play()
Пример #11
0
 def stop(self):
     if self.mic_started:
         if self.passthroughStream is not None:
             Log.debug('Microphone: stopping passthrough stream')
             self.passthroughStream.stop()
         self.engine.removeTask(self)
         self.mic.stop_stream()
         self.mic_started = False
         Log.debug('Microphone: stopped %s' % self.devname)
Пример #12
0
 def loadLibrary(self):
     Log.debug("Loading libraries in %s" % self.library)
     self.loaded = False
     self.tiersPresent = False
     if self.splash:
         Dialogs.changeLoadingSplashScreenText(self.engine, self.splash, _("Browsing Collection..."))
     else:
         self.splash = Dialogs.showLoadingSplashScreen(self.engine, _("Browsing Collection..."))
         self.loadStartTime = time.time()
     self.engine.resource.load(self, "libraries", lambda: Song.getAvailableLibraries(self.engine, self.library), onLoad = self.loadSongs, synch = True)
Пример #13
0
 def drop_table(self):
     """ Should remove the tables created by the class. Every child of
     database which stores its own data should implement this function.
     """
     Log.debug("Dropping Table %s" % self.__name__)
     cursor = self.db_connection.cursor()
     sql = "DROP TABLE "
     sql += self.__name__
     cursor.execute(sql)
     self.db_connection.commit()
Пример #14
0
 def drop_table(self):
     """ Should remove the tables created by the class. Every child of
     database which stores its own data should implement this function.
     """
     Log.debug("Dropping Table %s" % self.__name__)
     cursor = self.db_connection.cursor()
     sql = "DROP TABLE "
     sql += self.__name__
     cursor.execute(sql)
     self.db_connection.commit()
Пример #15
0
    def getSoundObjectList(self, soundPath, soundPrefix, numSounds, soundExtension=".ogg"):  # MFH
        Log.debug("{0}1{2} - {0}{1}{2} found in {3}".format(soundPrefix, numSounds, soundExtension, soundPath))

        sounds = []
        for i in xrange(1, numSounds + 1):
            filePath = os.path.join(soundPath, "%s%d%s" % (soundPrefix, i, soundExtension))
            soundObject = Sound(self.resource.fileName(filePath))
            sounds.append(soundObject)

        return sounds
Пример #16
0
    def showTutorial(self):
        # evilynux - Make sure tutorial exists before launching
        tutorialpath = self.engine.tutorialFolder
        if not os.path.isdir(self.engine.resource.fileName(tutorialpath)):
            Log.debug("No folder found: %s" % tutorialpath)
            Dialogs.showMessage(self.engine, _("No tutorials found!"))
            return

        self.engine.startWorld(1, None, 0, 0, tutorial = True)

        self.launchLayer(lambda: Lobby(self.engine))
Пример #17
0
    def showTutorial(self):
        # evilynux - Make sure tutorial exists before launching
        tutorialpath = self.engine.tutorialFolder
        if not os.path.isdir(self.engine.resource.fileName(tutorialpath)):
            Log.debug("No folder found: %s" % tutorialpath)
            Dialogs.showMessage(self.engine, _("No tutorials found!"))
            return

        self.engine.startWorld(1, None, 0, 0, tutorial=True)

        self.launchLayer(lambda: Lobby(self.engine))
Пример #18
0
    def upload_to_web(self, url):
        """ Upload the component to the given url

        """
        Log.critical('upload_to_web() has been called. This function is deprecated')
        Log.debug("Uploading component to url %s" % url)
        import requests
        manifest_file = self._component_file
        files = {'manifest': open(manifest_file, "rb")}
        r = requests.post(url, files=files)
        if r.status_code != requests.codes.ok:
            Log.critical("Error %s occured while upload" % r.status_code)
Пример #19
0
 def add(cls, name, exe_hash):
     """ Creates a new Comonent log and saves it. The new component log will
     be returned.
     """
     Log.debug('Component_Log.add(): adding killed component.')
     data = {'c_name': name, 'c_exe_hash': exe_hash}
     cl = cls.create(data)
     try:
         cl.save()
     except NoSuchTable:
         cl.create_table().save()
     return cl
Пример #20
0
    def add(cls, attr):
        """ This method adds a new object to database and authorized_keys.

        attr is expected to be a dictionary.
        The attr are at least and have to be compatible with the create()
        attributes:
            * c_id
            * f_Pubkey_pubkey
        """
        Log.debug('Creating object with ssh access'
                  ' and granting access for public key.')
        return cls.create(attr)
Пример #21
0
    def pushLayer(self, layer):
        Log.debug("View: Push: %s" % layer.__class__.__name__)

        if not layer in self.layers:
            self.layers.append(layer)
            self.incoming.append(layer)
            self.visibility[layer] = 0.0
            layer.shown()
        elif layer in self.outgoing:
            layer.hidden()
            layer.shown()
            self.outgoing.remove(layer)
        self.engine.addTask(layer)
Пример #22
0
 def test_get(self):
     from datetime import datetime
     from datetime import timedelta
     self.comp.create_table()
     self.comp.save()
     # Test get all
     comps = Component.get()
     self.assertIsNotNone(comps, "Could not retrieve Component")
     self.assertEqual(comps[0], self.comp, "Could not deserialize data")
     time_since = datetime.today() - timedelta(minutes=10)
     comps = Component.get(time_since)
     Log.debug("test_get(): comps: " + str(comps))
     self.assertEqual(comps[0], self.comp, "Could not deserialize data")
Пример #23
0
 def test_get(self):
     from datetime import datetime
     from datetime import timedelta
     self.comp.create_table()
     self.comp.save()
     # Test get all
     comps = Component.get()
     self.assertIsNotNone(comps, "Could not retrieve Component")
     self.assertEqual(comps[0], self.comp, "Could not deserialize data")
     time_since = datetime.today() - timedelta(minutes=10)
     comps = Component.get(time_since)
     Log.debug("test_get(): comps: " + str(comps))
     self.assertEqual(comps[0], self.comp, "Could not deserialize data")
Пример #24
0
    def pushLayer(self, layer):
        Log.debug("View: Push: %s" % layer.__class__.__name__)

        if not layer in self.layers:
            self.layers.append(layer)
            self.incoming.append(layer)
            self.visibility[layer] = 0.0
            layer.shown()
        elif layer in self.outgoing:
            layer.hidden()
            layer.shown()
            self.outgoing.remove(layer)
        self.engine.addTask(layer)
Пример #25
0
    def upload_to_web(self, url):
        """ Upload the component to the given url

        """
        Log.critical(
            'upload_to_web() has been called. This function is deprecated')
        Log.debug("Uploading component to url %s" % url)
        import requests
        manifest_file = self._component_file
        files = {'manifest': open(manifest_file, "rb")}
        r = requests.post(url, files=files)
        if r.status_code != requests.codes.ok:
            Log.critical("Error %s occured while upload" % r.status_code)
Пример #26
0
 def add(cls, name, exe_hash):
     """ Creates a new Comonent log and saves it. The new component log will
     be returned.
     """
     Log.debug('Component_Log.add(): adding killed component.')
     data = {'c_name': name,
             'c_exe_hash': exe_hash}
     cl = cls.create(data)
     try:
         cl.save()
     except NoSuchTable:
         cl.create_table().save()
     return cl
Пример #27
0
    def __init__(self, name, number):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("Player class init (Player.py)...")

        self.name     = name

        self.reset()
        self.keyList     = None

        self.progressKeys = []
        self.drums        = []
        self.keys         = []
        self.soloKeys     = []
        self.soloShift    = None
        self.soloSlide    = False
        self.actions      = []
        self.yes          = []
        self.no           = []
        self.conf         = []
        self.up           = []
        self.down         = []
        self.left         = []
        self.right        = []
        self.controller   = -1
        self.controlType  = -1

        self.guitarNum    = None
        self.number       = number

        self.bassGrooveEnabled = False
        self.currentTheme = 1

        self.lefty       = _playerDB.execute('SELECT `lefty` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.twoChordMax = _playerDB.execute('SELECT `twochord` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.drumflip    = _playerDB.execute('SELECT `drumflip` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.assistMode  = _playerDB.execute('SELECT `assist` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.autoKick    = _playerDB.execute('SELECT `autokick` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.neck        = _playerDB.execute('SELECT `neck` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.neckType    = _playerDB.execute('SELECT `necktype` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.whichPart   = _playerDB.execute('SELECT `part` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self._upname      = _playerDB.execute('SELECT `upname` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self._difficulty  = _playerDB.execute('SELECT `difficulty` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        #MFH - need to store selected practice mode and start position here
        self.practiceMode = False
        self.practiceSpeed = 1.0
        self.practiceSection = None
        self.startPos = 0.0

        self.hopoFreq = None
Пример #28
0
    def add(cls, key, access):
        """ A given key will be added to the local database, referencing the
        given Access-Instance.

        returns newly created object
        """
        Log.debug("add(package): adding package to local database")
        # Create Database entry
        data = {'c_key': key, 'f_Access_access': access, }
        pubkey = cls.create(data)
        try:
            pubkey.save()
        except NoSuchTable:
            pubkey.create_table().save()
        return pubkey
Пример #29
0
    def getSoundObjectList(self,
                           soundPath,
                           soundPrefix,
                           numSounds,
                           soundExtension=".ogg"):  #MFH
        Log.debug("{0}1{2} - {0}{1}{2} found in {3}".format(
            soundPrefix, numSounds, soundExtension, soundPath))

        sounds = []
        for i in xrange(1, numSounds + 1):
            filePath = os.path.join(
                soundPath, "%s%d%s" % (soundPrefix, i, soundExtension))
            soundObject = Sound(self.resource.fileName(filePath))
            sounds.append(soundObject)

        return sounds
Пример #30
0
 def gcDump(self):
     before = len(gc.get_objects())
     coll   = gc.collect()
     after  = len(gc.get_objects())
     Log.debug("%d GC objects collected, total %d -> %d." % (coll, before, after))
     fn = "gcdump.txt"
     f = open(fn, "w")
     n = 0
     gc.collect()
     for obj in gc.garbage:
         try:
             print >>f, obj
             n += 1
         except:
             pass
     f.close()
     Log.debug("Wrote a dump of %d GC garbage objects to %s." % (n, fn))
Пример #31
0
    def loadTex2D(self, fname, type = GL_RGB):
        file = os.path.join(self.workdir,fname)
        if os.path.exists(file):
            img = pygame.image.load(file)
            noise = pygame.image.tostring(img, "RGB")
        else:
            Log.debug("Can't load %s; generating random 2D noise instead." % fname)
            return self.makeNoise2D(16)

        texture = 0
        glBindTexture(GL_TEXTURE_2D, texture)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, 1, img.get_width(), img.get_height(), 0, type, GL_UNSIGNED_BYTE, noise)
        return texture
Пример #32
0
    def open(self, frequency=22050, bits=16, stereo=True, bufferSize=1024):
        try:
            pygame.mixer.quit()
        except:
            pass

        try:
            pygame.mixer.init(frequency, -bits, stereo and 2 or 1, bufferSize)
        except:
            Log.warn("Audio setup failed. Trying with default configuration.")
            pygame.mixer.init()

        Log.debug("Audio configuration: %s" % str(pygame.mixer.get_init()))

        #myfingershurt: ensuring we have enough audio channels!
        pygame.mixer.set_num_channels(10)

        return True
Пример #33
0
 def gcDump(self):
     before = len(gc.get_objects())
     coll = gc.collect()
     after = len(gc.get_objects())
     Log.debug("%d GC objects collected, total %d -> %d." %
               (coll, before, after))
     fn = "gcdump.txt"
     f = open(fn, "w")
     n = 0
     gc.collect()
     for obj in gc.garbage:
         try:
             print >> f, obj
             n += 1
         except:
             pass
     f.close()
     Log.debug("Wrote a dump of %d GC garbage objects to %s." % (n, fn))
Пример #34
0
 def get_exactly(cls, name, field="c_id"):
     """ Returns exactly one object with the given (unique) name.
     If no object with the given name was found, a InstanceNotFoundError is
     raised.
     """
     sql = "SELECT c_pk, adapter FROM " + cls.__name__ + " WHERE "
     sql += "%s = ?" % field
     cursor = Database.db_connection.cursor()
     Log.debug("Database.get_exactly(): Requesting %s with %s = %s" % (cls.__name__, field, name))
     Log.debug("Database.get_exactly(): executing query: " + sql)
     try:
         cursor.execute(sql, (name,))
     except sqlite3.OperationalError:
         raise NoSuchTable()
     try:
         return cls.convert(cursor.fetchone())
     except TypeError:  # Object was not in database
         raise InstanceNotFoundError()
Пример #35
0
 def get_exactly(cls, name, field='c_id'):
     """ Returns exactly one object with the given (unique) name.
     If no object with the given name was found, a InstanceNotFoundError is
     raised.
     """
     sql = 'SELECT c_pk, adapter FROM ' + cls.__name__ + ' WHERE '
     sql += '%s = ?' % field
     cursor = Database.db_connection.cursor()
     Log.debug("Database.get_exactly(): Requesting %s with %s = %s" %
               (cls.__name__, field, name))
     Log.debug("Database.get_exactly(): executing query: " + sql)
     try:
         cursor.execute(sql, (name, ))
     except sqlite3.OperationalError:
         raise NoSuchTable()
     try:
         return cls.convert(cursor.fetchone())
     except TypeError:  # Object was not in database
         raise InstanceNotFoundError()
Пример #36
0
    def make(self, fname, name = ""):
        """Compile a shader.
           fname = base filename for shader files
           name  = name to use for this shader (defaults to fname)

           Returns nothing, or raises an exception on error."""

        if name == "":
            name = fname
        fullname = os.path.join(self.workdir, fname)
        vertname, fragname = fullname+".vert", fullname+".frag"
        Log.debug('Compiling shader "%s" from %s and %s.' % (name, vertname, fragname))
        program = self.compile(open(vertname), open(fragname))
        sArray = {"program": program, "name": name, "textures": []}
        self.getVars(vertname, program, sArray)
        self.getVars(fragname, program, sArray)
        self.shaders[name] = sArray
        if self.shaders[name].has_key("Noise3D"):
            self.setTexture("Noise3D",self.noise3D,name)
Пример #37
0
    def remove(self):
        """ Remove component with given name.

        Returns ComponentLog if the component successfully removed.
        """
        Log.debug("Component.remove(): removing")
        name = self.c_id
        exe_hash = self.c_exe_hash
        super().remove()
        import os
        try:
            os.remove(self._component_file)
        except IOError:
            Log.error("Component.remove(): unable to remove component file.")
            return False
        try:
            cl = ComponentLog.add(name, exe_hash)
        except InstanceAlreadyExists as e:
            cl = e.original()
        return cl
Пример #38
0
    def remove(self):
        """ Remove component with given name.

        Returns ComponentLog if the component successfully removed.
        """
        Log.debug("Component.remove(): removing")
        name = self.c_id
        exe_hash = self.c_exe_hash
        super().remove()
        import os
        try:
            os.remove(self._component_file)
        except IOError:
            Log.error("Component.remove(): unable to remove component file.")
            return False
        try:
            cl = ComponentLog.add(name, exe_hash)
        except InstanceAlreadyExists as e:
            cl = e.original()
        return cl
Пример #39
0
    def loadTex3D(self, fname, type = GL_RED):
        file = os.path.join(self.workdir,fname)
        if os.path.exists(file):
            noise = open(file).read()
            size = int(len(noise)**(1/3.0))
        else:
            Log.debug("Can't load %s; generating random 3D noise instead." % file)
            return self.makeNoise3D(16)


        texture = 0

        glBindTexture(GL_TEXTURE_3D_EXT, texture)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_T, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_R_EXT, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexImage3DEXT(GL_TEXTURE_3D_EXT, 0, 1,size, size, size, 0, type, GL_UNSIGNED_BYTE, noise)
        return texture
Пример #40
0
    def add(cls, component):
        """ A given package will be added to the local database.

        A package has to be in the ctlweb-format which can be found in our
        docmuentation.

        returns newly created object
        """
        from os import path
        Log.debug("add(package): adding package to local database")
        # Create Database entry
        data = Component._unpack(component)
        comp = cls.create(data)
        comp._component_file = component
        try:
            comp.save()
        except NoSuchTable:
            comp.create_table().save()
        except ValueError as e:
            Log.critical('%s' % e.args[0])
            return
        except MergedWarning as e:
            Log.info('Merged components')
            return comp
        # Copy package to store
        comp._component_file = None  # reset the component to default.
        try:
            comp_log = ComponentLog.get_exactly(comp['c_exe_hash'])
            comp_log.remove()
        except (InstanceNotFoundError, NoSuchTable):
            pass
        import shutil
        try:
            target_name = comp._component_file
            shutil.copy(component, target_name)
        except IOError:
            Log.critical("Unable to save component to Manifest store in %s" %
                         store)
            exit(1)
        return comp
Пример #41
0
    def add(cls, component):
        """ A given package will be added to the local database.

        A package has to be in the ctlweb-format which can be found in our
        docmuentation.

        returns newly created object
        """
        from os import path
        Log.debug("add(package): adding package to local database")
        # Create Database entry
        data = Component._unpack(component)
        comp = cls.create(data)
        comp._component_file = component
        try:
            comp.save()
        except NoSuchTable:
            comp.create_table().save()
        except ValueError as e:
            Log.critical('%s' % e.args[0])
            return
        except MergedWarning as e:
            Log.info('Merged components')
            return comp
        # Copy package to store
        comp._component_file = None  # reset the component to default.
        try:
            comp_log = ComponentLog.get_exactly(comp['c_exe_hash'])
            comp_log.remove()
        except (InstanceNotFoundError, NoSuchTable):
            pass
        import shutil
        try:
            target_name = comp._component_file
            shutil.copy(component, target_name)
        except IOError:
            Log.critical("Unable to save component to Manifest store in %s"
                         % store)
            exit(1)
        return comp
Пример #42
0
 def getImgDrawing(self, fileName, openImage=True):
     imgDrawing = None
     for dataPath in self.resource.dataPaths:
         fileName1 = os.path.join(dataPath, fileName)
         if self.logLoadings == 1:
             if openImage:
                 Log.notice("Trying to load image: %s" % fileName1)
             else:
                 Log.notice("Checking image: %s" % fileName1)
         #check if fileName1 exists (has extension)
         if os.path.exists(fileName1):
             if openImage == True:
                 try:
                     imgDrawing = ImgDrawing(self.svg, fileName1)
                     return imgDrawing
                 except IOError:
                     Log.warn("Unable to load image file: %s" % fileName1)
                 except OverflowError:
                     Log.warn("Unable to read image file: %s" % fileName1)
             else:
                 return True
         else:
             #find extension
             fileName1 = os.path.splitext(fileName1)[0]
             files = glob.glob('%s.*' % fileName1)
             if openImage == True:
                 for i in range(len(files)):
                     try:
                         imgDrawing = ImgDrawing(self.svg, files[i])
                         return imgDrawing
                     except IOError:
                         Log.warn("Unable to load image file: %s" %
                                  files[i])
             elif len(files) > 0:
                 return True
     #image not found
     if self.logImageNotFound:
         Log.debug("Image not found: %s" % fileName)
     return False
Пример #43
0
    def convert(cls, s):
        """ Returns an object built out of the string s. This function is used
        by sqlite3
        """
        Log.debug("Building %s object" % cls.__name__)
        attribute_box = {}
        attribute_box["c_pk"] = s[0]
        import re

        attrs = s[1].split(";")
        for attr in sorted(attrs):
            key, val = attr.split("=", 1)
            if re.search("^f_(?P<classname>.+?)_.+", key):
                class_name = attribute_box["c_referenced_class"]
                exec("from .%s import %s" % (class_name.lower(), class_name))
                exec("attribute_box[key] = " + class_name + ".get_exactly(val, 'c_pk')")
                continue
            attribute_box[key] = val
        Log.debug("Got following attributes: " + str(attribute_box))
        instance = cls.create(attribute_box)
        instance.c_pk = s[0]
        return instance
Пример #44
0
 def convert(cls, s):
     """ Returns an object built out of the string s. This function is used
     by sqlite3
     """
     Log.debug("Building %s object" % cls.__name__)
     attribute_box = {}
     attribute_box['c_pk'] = s[0]
     import re
     attrs = s[1].split(';')
     for attr in sorted(attrs):
         key, val = attr.split("=", 1)
         if re.search('^f_(?P<classname>.+?)_.+', key):
             class_name = attribute_box['c_referenced_class']
             exec('from .%s import %s' % (class_name.lower(), class_name))
             exec('attribute_box[key] = ' + class_name +
                  ".get_exactly(val, 'c_pk')")
             continue
         attribute_box[key] = val
     Log.debug('Got following attributes: ' + str(attribute_box))
     instance = cls.create(attribute_box)
     instance.c_pk = s[0]
     return instance
Пример #45
0
def test_login():
    '''测试登录功能'''
    try:
        # path = r"C:\Users\Administrator\Desktop\公开课资料\chromedriver_win32\chromedriver"
        # driver = webdriver.Chrome(path)
        # driver.get('https://mail.163.com')
        # driver.maximize_window()
        # LoginAccount.LoginAccount.login(driver,'zhangming002', 'zmkmzmkm')

        path = r"C:\Users\Administrator\Desktop\公开课资料\chromedriver_win32\chromedriver"

        Log.debug('开始加载测试数据')
        excel = OperateExcel()
        excel.load_workbook(testdataPath)
        excel.get_sheet_by_name('login')
        rows_nums = excel.get_rows_num()
        row1_values = excel.get_row_values(0)

        # {'用户名':'xxxx','密码':'xxxxx','是否执行':'y'}
        for i in range(1, rows_nums):

            row_values = excel.get_row_values(i)
            values = dict(zip(row1_values, row_values))
            if values['是否执行'].lower() == 'y':
                driver = webdriver.Chrome(path)
                username = values['用户名']
                password = values['密码']
                Log.debug('开始打开网页')
                driver.get('https://mail.163.com')
                driver.maximize_window()
                LoginAccount.LoginAccount.login(driver, username, password)
                time.sleep(3)
                driver.quit()

    except Exception as e:
        raise e
    finally:
        time.sleep(3)
Пример #46
0
 def getImgDrawing(self, fileName, openImage=True):
     imgDrawing = None
     for dataPath in self.resource.dataPaths:
         fileName1 = os.path.join(dataPath, fileName)
         if self.logLoadings == 1:
             if openImage:
                 Log.notice("Trying to load image: %s" % fileName1)
             else:
                 Log.notice("Checking image: %s" % fileName1)
         # check if fileName1 exists (has extension)
         if os.path.exists(fileName1):
             if openImage == True:
                 try:
                     imgDrawing = ImgDrawing(self.svg, fileName1)
                     return imgDrawing
                 except IOError:
                     Log.warn("Unable to load image file: %s" % fileName1)
                 except OverflowError:
                     Log.warn("Unable to read image file: %s" % fileName1)
             else:
                 return True
         else:
             # find extension
             fileName1 = os.path.splitext(fileName1)[0]
             files = glob.glob("%s.*" % fileName1)
             if openImage == True:
                 for i in range(len(files)):
                     try:
                         imgDrawing = ImgDrawing(self.svg, files[i])
                         return imgDrawing
                     except IOError:
                         Log.warn("Unable to load image file: %s" % files[i])
             elif len(files) > 0:
                 return True
     # image not found
     if self.logImageNotFound:
         Log.debug("Image not found: %s" % fileName)
     return False
Пример #47
0
 def _read_control(control):
     """ Reads for the backend required keys of the control file. See
     Component.create() for more detail.
     """
     Log.debug("_read_control(): parsing control file %s")
     import configparser
     parser = configparser.ConfigParser()
     parser.read(control)
     try:
         name = parser['DEFAULT']['name']
     except KeyError:
         Log.critical("Found no component name")
         raise
     try:
         exe = parser['DEFAULT']['exe']
         exe_hash = parser['DEFAULT']['exe_hash']
     except KeyError:
         Log.critical("Found no corresponding exe in component")
         raise
     return {"c_id": name,
             "c_exe": exe,
             "c_exe_hash": exe_hash,
             }
Пример #48
0
    def disableScreensaver(self):
        if os.name == 'nt':
            # See the DisableScreensaver and RestoreScreensaver functions in
            # modules/video_output/msw/common.c in the source code for VLC.
            import win32gui
            import win32con
            import atexit

            Log.debug('Disabling screensaver.')

            old_lowpowertimeout = win32gui.SystemParametersInfo(
                win32con.SPI_GETLOWPOWERTIMEOUT)
            if old_lowpowertimeout != 0:
                atexit.register(lambda: win32gui.SystemParametersInfo(
                    win32con.SPI_SETLOWPOWERTIMEOUT, old_lowpowertimeout))
                win32gui.SystemParametersInfo(win32con.SPI_SETLOWPOWERTIMEOUT,
                                              0)

            old_powerofftimeout = win32gui.SystemParametersInfo(
                win32con.SPI_GETPOWEROFFTIMEOUT)
            if old_powerofftimeout != 0:
                atexit.register(lambda: win32gui.SystemParametersInfo(
                    win32con.SPI_SETPOWEROFFTIMEOUT, old_powerofftimeout))
                win32gui.SystemParametersInfo(win32con.SPI_SETPOWEROFFTIMEOUT,
                                              0)

            old_screensavetimeout = win32gui.SystemParametersInfo(
                win32con.SPI_GETSCREENSAVETIMEOUT)
            if old_screensavetimeout != 0:
                atexit.register(lambda: win32gui.SystemParametersInfo(
                    win32con.SPI_SETSCREENSAVETIMEOUT, old_screensavetimeout))
                win32gui.SystemParametersInfo(
                    win32con.SPI_SETSCREENSAVETIMEOUT, 0)

        else:
            Log.debug(
                'Screensaver disabling is not implemented on this platform.')
Пример #49
0
 def __init__(self, engine, controlnum, samprate=44100):
     Task.__init__(self)
     self.engine = engine
     self.controlnum = controlnum
     devnum = self.engine.input.controls.micDevice[controlnum]
     if devnum == -1:
         devnum = None
         self.devname = pa.get_default_input_device_info()['name']
     else:
         self.devname = pa.get_device_info_by_index(devnum)['name']
     self.mic = pa.open(samprate,
                        1,
                        pyaudio.paFloat32,
                        input=True,
                        input_device_index=devnum,
                        start=False)
     self.analyzer = pypitch.Analyzer(samprate)
     self.mic_started = False
     self.lastPeak = 0
     self.detectTaps = True
     self.tapStatus = False
     self.tapThreshold = -self.engine.input.controls.micTapSensitivity[
         controlnum]
     self.passthroughQueue = []
     passthroughVolume = self.engine.input.controls.micPassthroughVolume[
         controlnum]
     if passthroughVolume > 0.0:
         Log.debug(
             'Microphone: creating passthrough stream at %d%% volume' %
             round(passthroughVolume * 100))
         self.passthroughStream = Audio.MicrophonePassthroughStream(
             engine, self)
         self.passthroughStream.setVolume(passthroughVolume)
     else:
         Log.debug('Microphone: not creating passthrough stream')
         self.passthroughStream = None
Пример #50
0
    def create_table(self):
        """ Creates a table for the class in which every instance object which
        starts with 'c_'. For example 'c_id'. This variable can be accessed
        with self["c_id"]

        returns self
        """
        import re

        Log.debug("Creating Table for %s" % self.__name__)
        cursor = self.db_connection.cursor()
        sql = "CREATE TABLE "
        sql += self.__name__
        sql += """ (
                c_pk INTEGER PRIMARY KEY AUTOINCREMENT,
                date DATE,
                adapter TEXT"""
        attrs = self.get_attributes()
        if not "c_id" in attrs:
            raise AttributeError("c_id not defined")
        for i in attrs:
            if i == "c_pk":
                continue
            if i == "c_id":
                sql += ", %s UNIQUE" % i
            elif re.search("^f_(?P<classname>.+?)_.+", i):
                class_match = re.match("^f_(?P<classname>.+?)_.+", i)
                referenced_class = class_match.groupdict()["classname"]
                sql += ", %s REFERENCES %s (c_pk)" % (i, referenced_class)
            else:
                sql += ", %s" % i
        sql += ");"
        Log.debug("Creating table, executing query: " + sql)
        cursor.execute(sql)
        self.db_connection.commit()
        return self
Пример #51
0
 def _read_control(control):
     """ Reads for the backend required keys of the control file. See
     Component.create() for more detail.
     """
     Log.debug("_read_control(): parsing control file %s")
     import configparser
     parser = configparser.ConfigParser()
     parser.read(control)
     try:
         name = parser['DEFAULT']['name']
     except KeyError:
         Log.critical("Found no component name")
         raise
     try:
         exe = parser['DEFAULT']['exe']
         exe_hash = parser['DEFAULT']['exe_hash']
     except KeyError:
         Log.critical("Found no corresponding exe in component")
         raise
     return {
         "c_id": name,
         "c_exe": exe,
         "c_exe_hash": exe_hash,
     }
Пример #52
0
    def get(cls, time_since=None):
        """ Returns a list of objects stored in the database.
        Optional Parameter time_since is instance of datetime.datetime and
        represents the oldest object to be found by get. Default searches for
        every object stored in the database.
        """
        # FIXME should use the get_exactly for easy maintenance; skipped due to
        #       motivational problems
        from datetime import datetime
        import time

        sql = (
            "SELECT c_pk, adapter FROM "
            + cls.__name__
            + """
                WHERE date >= ?"""
        )
        values = []
        if not time_since:
            Log.debug("Database.get(): Get all objects of %s" % cls.__name__)
            sql = "SELECT c_pk, adapter FROM " + cls.__name__
        Log.debug("Database.get(): time_since is %s" % time_since)

        try:
            if isinstance(time_since, str):
                time_since = datetime(*(time.strptime(time_since, "%Y-%m-%d")[:3]))
                Log.debug("Database.get(): Get %s newer than %s" % (cls.__name__, time_since))
                time_since = time_since.strftime("%s")
                values.append(time_since)
        except:
            Log.debug("Wrong dateformat caught in %s.get()" % cls.__name__)
            raise ValueError()

        cursor = Database.db_connection.cursor()

        try:
            cursor.execute(sql, values)
        except sqlite3.IntegrityError:
            return None
        except sqlite3.OperationalError:
            raise NoSuchTable()
        result_set = []
        for row in cursor.fetchall():
            result_set.append(cls.convert(row))
        return result_set
Пример #53
0
 def remove(self):
     """ Removes rows on the basis of the id
     """
     Log.debug("Removing %s object from database." % self.__name__)
     cursor = Database.db_connection.cursor()
     table = self.__name__
     sql = (
         "DELETE FROM "
         + table
         + """
             WHERE c_id = """
         "'%s'"
         """
             """
         % self["c_id"]
     )
     Log.debug("Will execute %s to remove %s object." % (sql, self.__name__))
     cursor.execute(sql)
     Database.db_connection.commit()
     Log.debug("Removed %s successfully from database." % self.__name__)