Example #1
0
 def configure_logs(self, config):
     if not Settings.is_foreground():
         config.update({
                 'log.screen': False,
                 'log.access_file': Settings.get_access_log_path(),
                 'log.error_file': Settings.get_error_log_path()
                 })
Example #2
0
 def configure_server(self, config):
     config.update({
             'server.socket_host': '0.0.0.0',
             'server.socket_port': Settings.get_port(),
             'error_page.404': handle_error,
             'error_page.401': handle_error
         })
Example #3
0
 def __init__(self, path):
     self.path = path
     self.queue = Queue.PriorityQueue()
     self.watcher = Watcher(path, self.queue)
     self.walker = Walker(path, self.queue, Settings.is_rescan_forced())
     self.reader = Reader(self.queue)
     self.validator = Validator(self.queue)
Example #4
0
    def __init__(self):
        setproctitle('GWinWrap')
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                             gtk.main_quit)
        faulthandler.enable()  # For better debug info

        settings = Settings()
        builder = settings.returnBuilder()

        # Gets the methods from the classes and sets to handler.
        # Then, builder connects to any signals it needs.
        classes = [CrossClassSignals(settings)]

        handlers = {}
        for c in classes:
            methods = inspect.getmembers(c, predicate=inspect.ismethod)
            handlers.update(methods)

        builder.connect_signals(handlers)
        window = settings.createWindow()
        window.show()
Example #5
0
    def __init__(self, domainString, rootIn=None):
        '''Should also be a singleton class - otherwise you can actually circumvent the point of FlatOntologyManager() being a 
            singleton, which is that if ontology is to be dynamic at all - then everything should refer to the one single source.
            
            :param domainString:  tag such as 'SFHotels' or 'CamHotels'
            :type domainString: str
            :param rootIn: path of repository - default None -
            :type rootIn: str
        '''
        # For conditional goal generation:
        self.PROB_MASS_OVER_CONDITIONALS = 0.9  # must be less than 1.0

        if rootIn is not None:
            Settings.load_root(
                rootIn
            )  # for use with semi file parser - where no config is given to set repository root by

        self.domainString = domainString
        self._set_ontology()  # sets self.ontology
        self._set_db()  # sets self.db
        self._set_domains_informable_and_requestable_slots()
Example #6
0
def example_1():
    rotor_1 = machine_data.get_rotor("i")
    rotor_2 = machine_data.get_rotor("ii")
    rotor_3 = machine_data.get_rotor("iii")
    etw = machine_data.get_entry_wheel('etw')
    reflector = machine_data.get_reflector("b")

    rotor_1.update({'start_position': 'A', 'position': 1})
    rotor_2.update({'start_position': 'A', 'position': 2})
    rotor_3.update({'start_position': 'Z', 'position': 3})

    settings = Settings()
    settings.add_entry_wheel(etw)
    settings.add_rotors([rotor_1, rotor_2, rotor_3])
    settings.add_reflector(reflector)
    settings.set_switchboard_pairs(
        ['HL', 'MO', 'AJ', 'CX', 'BZ', 'SR', 'NI', 'YW', 'DG', 'PK'])

    enigma = Enigma(settings=settings)

    print(enigma.parse("HELLOWORLD"))
Example #7
0
    def test_non_notch_rotor_preventing_rotations(self):
        settings = Settings()
        data = EnigmaMachineData()
        data.set_machine("example_machine")

        iv = data.get_rotor("iv")
        v = data.get_rotor("v")
        beta = data.get_rotor("beta")
        i = data.get_rotor("i")

        iv.update({"start_position": "E", "ring_setting": 18, "position": 1})
        v.update({"start_position": "Z", "ring_setting": 24, "position": 2})
        beta.update({"start_position": "G", "ring_setting": 3, "position": 3})
        i.update({"start_position": "P", "ring_setting": 5, "position": 4})

        settings.add_rotors([iv, v, beta, i])
        settings.add_reflector(data.get_reflector("a"))

        scrambler = Scrambler(settings=settings)
        self.assertEqual("E", scrambler._rotors[3].get_current_position())
        self.assertEqual("Z", scrambler._rotors[2].get_current_position())
        self.assertEqual("G", scrambler._rotors[1].get_current_position())
        self.assertEqual("P", scrambler._rotors[0].get_current_position())
        scrambler.rotate_rotors()
        self.assertEqual("E", scrambler._rotors[3].get_current_position())
        self.assertEqual("Z", scrambler._rotors[2].get_current_position())
        self.assertEqual("G", scrambler._rotors[1].get_current_position())
        self.assertEqual("Q", scrambler._rotors[0].get_current_position())
Example #8
0
    def train(self):
        '''
        call this function when the episode ends
        '''

        if not self.is_training:
            self.logger.info("Not in training mode")
            return
        else:
            self.logger.info("Update a2c policy parameters.")

        self.episodecount += 1
        self.logger.info("Sample Num so far: %s" % self.samplecount)
        self.logger.info("Episode Num so far: %s" % self.episodecount)

        Settings.add_count()
        globalEpisodeCount = copy.deepcopy(Settings.get_count())
        self.loadLastestPolicy()

        if self.samplecount >= self.minibatch_size * 1 and globalEpisodeCount % self.training_frequency == 0:
            self.logger.info('start training...')

            assert len(Settings.global_policysaver) == Settings.global_threadsnum
            # self.dqn.reset_noise()
            total_batch_size = 0
            for k, thread_policy in Settings.global_policysaver.items():
                s_batch, a_batch_one_hot, V_trace, advantage = Settings.global_hackpolicysaver[k]._sample_and_updateV()
                grad, batch_size = thread_policy.train(s_batch, a_batch_one_hot, V_trace, advantage)
                total_batch_size += batch_size
                Settings.load_grad(grad, k)

            assert len(Settings.global_gradsaver) == Settings.global_threadsnum
            grads_list = Settings.grad_sum()
            self._load_and_update(grads_list, total_batch_size)
            self.savePolicyInc()
Example #9
0
 def test_B_II_IV_Beta_Gamma_4_24_17_7(self):
     settings = Settings()
     data = EnigmaMachineData()
     data.set_machine("example_machine")
     ii = data.get_rotor("ii")
     iv = data.get_rotor("iv")
     beta = data.get_rotor("beta")
     gamma = data.get_rotor("gamma")
     ii.update({"start_position": "V", "ring_setting": 4, "position": 1})
     iv.update({"start_position": "E", "ring_setting": 24, "position": 2})
     beta.update({"start_position": "Q", "ring_setting": 17, "position": 3})
     gamma.update({"start_position": "J", "ring_setting": 7, "position": 4})
     settings.add_entry_wheel(data.get_entry_wheel("etw"))
     settings.add_rotors([ii, iv, beta, gamma])
     settings.add_reflector(data.get_reflector("b"))
     settings.set_switchboard_pairs(["AT", "LU", "NR", "IG"])
     enigma = Enigma(settings=settings)
     self.assertEqual(
         "ACOMPUTERWOULDDESERVETOBECALLEDINTELLIGENTIFITCOULDDECEIVEAHUMANINTOBELIEVINGTHATITWASHUMANSOMETIMESITSTHEVERYPEOPLEWHONOONEIMAGINESANYTHINGOFWHODOTHETHINGSNOONECANIMAGINESOMETIMESITISTHEPEOPLENOONECANIMAGINEANYTHINGOFWHODOTHETHINGSNOONECANIMAGINETHOSEWHOCANIMAGINEANYTHINGCANCREATETHEIMPOSSIBLEALANTURING",
         enigma.parse(
             "BHCHRJCBLHJBPWXCAPXQCUAZRKBBTFEXBQWJFGVATZUJLXEMZRLOJHFWTMFUCAGFOHNNCPIOCJKAHJTWLWVHFJAQCZDXAHHMLSCRKXMJTXYFPKMBJFFLSNAOYYWCUOOPCBJGJUHFVOZOJNSNAWYMTCKBKAHQPYCUDPFZGAGIOHLKYTSXUOBDCJSGLMDCOIXJHFIUTCBVWOXKROVLBFVSYXBDJPUOIWAZEPHNUXRDVDKFFRXOXXHOVFUGZNAPNNJEOACFBSXUDDBCDWVFVIOOBISLKCDMRPDDCTZXNVWMFZDGJXUGC"
         ))
Example #10
0
 def __init__(self, settings=Settings()):
     self.settings = settings
     self.mkdir_images()
     self.pdir = "dataset" 
     self.get_max_disparity()
     self.load_test_data()
     self.load_mask()
     self.network  = None
     self.train_data_loaded = False
     if self.settings.epe:
         self.best_epe = self.settings.epe
     else:
         self.best_epe = 100.0
Example #11
0
    def vacuum(cls, session):
        cls.purge_orphans(session)
        
        num_removed = 0

        while cls.get_cache_size(session) > Settings.get_max_cache_size():
            cls.remove_oldest_transcoding(session)
            num_removed += 1

        if num_removed > 0:
            cherrypy.log("Expired %d transcoding%s (cache size: %d)" %
                         (num_removed, "s" if num_removed != 1 else "",
                          cls.get_cache_size(session)), cls.LOG_TAG)
Example #12
0
 def test_IV_V_Beta_I_A_EZGP_18_24_03_05(self):
     settings = Settings()
     data = EnigmaMachineData()
     data.set_machine("example_machine")
     iv = data.get_rotor("iv")
     v = data.get_rotor("v")
     beta = data.get_rotor("beta")
     i = data.get_rotor("i")
     iv.update({"start_position": "E", "ring_setting": 18, "position": 1})
     v.update({"start_position": "Z", "ring_setting": 24, "position": 2})
     beta.update({"start_position": "G", "ring_setting": 3, "position": 3})
     i.update({"start_position": "P", "ring_setting": 5, "position": 4})
     settings.add_entry_wheel(data.get_entry_wheel("etw"))
     settings.add_rotors([iv, v, beta, i])
     settings.add_reflector(data.get_reflector("a"))
     settings.set_switchboard_pairs(
         ["PC", "XZ", "FM", "QA", "ST", "NB", "HY", "OR", "EV", "IU"])
     enigma = Enigma(settings=settings)
     self.assertEqual(
         "CONGRATULATIONSONPRODUCINGYOURWORKINGENIGMAMACHINESIMULATOR",
         enigma.parse(
             "BUPXWJCDPFASXBDHLBBIBSRNWCSZXQOLBNXYAXVHOGCUUIBCVMPUZYUUKHI"))
Example #13
0
    def _update_kana(self):
        # update the selected status of the rows and columns
        for row, checkbox in self.row_checkboxes.items():
            y = self.kana.row_table[row]["y"]
            checkbox.selected = all([
                self.checkboxes[kana].selected for kana in self.kana.characters
                if self.kana.table[kana]["y"] == y
            ])
        for col, checkbox in self.col_checkboxes.items():
            x = self.kana.col_table[col]["x"]
            checkbox.selected = all([
                self.checkboxes[kana].selected for kana in self.kana.characters
                if self.kana.table[kana]["x"] == x
            ])

        # serialize the currently selected kana to settings
        selected_kana = [
            kana  # note: selected means don't learn
            for kana in self.kana.table.keys()
            if not self.checkboxes[kana].selected
        ]
        Settings.set(f"{self.kana_name}_kana", selected_kana)
Example #14
0
 def test_sondermaschine(self):
     settings = Settings()
     data = EnigmaMachineData()
     data.set_machine("sondermaschine")
     i = data.get_rotor("i")
     ii = data.get_rotor("ii")
     iii = data.get_rotor("iii")
     i.update({"start_position": "P", "position": 1})
     ii.update({"start_position": "D", "position": 2})
     iii.update({"start_position": "U", "position": 3})
     settings.add_entry_wheel(data.get_entry_wheel("etw"))
     settings.add_rotors([i, ii, iii])
     settings.add_reflector(data.get_reflector("ukw"))
     enigma = Enigma(settings=settings)
     self.assertEqual("WEPKI", enigma.parse("AAAAA"))
Example #15
0
 def test_norenigma(self):
     settings = Settings()
     data = EnigmaMachineData()
     data.set_machine("norenigma")
     i = data.get_rotor("i")
     iii = data.get_rotor("iii")
     v = data.get_rotor("v")
     i.update({"start_position": "A", "position": 1})
     iii.update({"start_position": "A", "position": 2})
     v.update({"start_position": "A", "position": 3})
     settings.add_entry_wheel(data.get_entry_wheel("etw"))
     settings.add_rotors([i, iii, v])
     settings.add_reflector(data.get_reflector("ukw"))
     enigma = Enigma(settings=settings)
     self.assertEqual("DBMZX", enigma.parse("AAAAA"))
Example #16
0
 def closeEvent(self, e: QtGui.QCloseEvent):
     pandaQueue.put(PandaCommands.Close())
     Settings.setValue(SETTINGS.QT.PREFIX, SETTINGS.QT.ACTOR_PATH,
                       self.recentActorFilePath)
     Settings.setValue(SETTINGS.QT.PREFIX, SETTINGS.QT.ANIMATION_PATH,
                       self.recentAnimationFilePath)
     Settings.setValue(SETTINGS.PANDA.PREFIX, SETTINGS.PANDA.BACKGROUND, \
      TableWidgetProperty.propertySerialize(self.ui.oSceneProperties, 'background-color'))
Example #17
0
 def test_m3(self):
     settings = Settings()
     data = EnigmaMachineData()
     data.set_machine("m3")
     i = data.get_rotor("i")
     v = data.get_rotor("v")
     viii = data.get_rotor("viii")
     i.update({"start_position": "P", "position": 1})
     v.update({"start_position": "Y", "position": 2})
     viii.update({"start_position": "Z", "position": 3})
     settings.add_entry_wheel(data.get_entry_wheel("etw"))
     settings.add_rotors([i, v, viii])
     settings.add_reflector(data.get_reflector("b"))
     enigma = Enigma(settings=settings)
     self.assertEqual("ZMOIR", enigma.parse("AAAAA"))
Example #18
0
 def test_m4_Beta_I_II_III_B_Thin_AQEV(self):
     settings = Settings()
     data = EnigmaMachineData()
     data.set_machine("m4")
     beta = data.get_rotor("beta")
     i = data.get_rotor("i")
     ii = data.get_rotor("ii")
     iii = data.get_rotor("iii")
     beta.update({"start_position": "A", "position": 1})
     i.update({"start_position": "Q", "position": 2})
     ii.update({"start_position": "E", "position": 3})
     iii.update({"start_position": "V", "position": 4})
     settings.add_entry_wheel(data.get_entry_wheel("etw"))
     settings.add_rotors([beta, i, ii, iii])
     settings.add_reflector(data.get_reflector("b-thin"))
     self.assertEqual("LNPJG", Enigma(settings=settings).parse("AAAAA"))
Example #19
0
def checkOntology(domain):
    Settings.load_root(root)
    Settings.load_config(None)
    Settings.config.add_section("GENERAL")
    Settings.config.set("GENERAL", 'domains', domain)

    Ontology.init_global_ontology()

    gOnt = Ontology.global_ontology
    for dstring in gOnt.possible_domains:
        informable = gOnt.get_informable_slots(dstring)

        for slot in informable:
            valuesJson = gOnt.get_informable_slot_values(dstring, slot)
            results = gOnt.ontologyManagers[dstring].db.customQuery(
                'SELECT DISTINCT {} FROM {} ORDER BY {} ASC'.format(
                    slot, dstring, slot))
            valuesDB = [entry[slot] for entry in results]
            # valuesDB = map(lambda a : a.lower(),valuesDB)
            valuesJson.append("not available")
            difference = list(set(valuesDB) - set(valuesJson))
            if len(difference):
                print dstring + " " + slot + " " + str(difference)
Example #20
0
    def configure_ssl(self, config):
        keyfile = Settings.get_ssl_key_path()
        crtfile = Settings.get_ssl_cert_path()

        if os.path.exists(keyfile) and os.path.exists(crtfile):
            config.update({
                    'server.ssl_module': 'pyopenssl',
                    'server.ssl_certificate': crtfile,
                    'server.ssl_private_key': keyfile
                    })

            return True
        else:
            if not os.path.exists(keyfile):
                cherrypy.log("Key file %s missing" % (keyfile), \
                                 self.LOG_TAG, logging.WARNING)
    
            if not os.path.exists(crtfile):
                cherrypy.log("Certificate file %s missing" % (crtfile), \
                                 self.LOG_TAG, logging.WARNING)

            cherrypy.log("SSL disabled", self.LOG_TAG, logging.WARNING)

            return False
Example #21
0
    def __init__(self, render_surface, surface_size, kana_name):
        Screen.__init__(self, render_surface, surface_size)
        self.kana_name = kana_name
        self.kana = Kana(self.kana_name)

        self.widgets = {
            "heading_kanaselectscreen":
            Heading(
                self.render_surface,
                (0, 0, 1920, 100),
                f"Select Kana: {self.kana_name}",
            ).set_themed(),
            "button_back":
            Button(self.render_surface, (10, 10, 230, 80),
                   "Back").set_themed(),
        }

        self.checkboxes = {}
        self.row_checkboxes = {}
        self.col_checkboxes = {}
        width_factor = 1520 / 6000
        height_factor = 950 / 3750
        width = 500 * width_factor
        height = 625 * height_factor

        kana_list = Settings.get(f"{self.kana_name}_kana")

        gen_checkbox = lambda kana, data: Checkbox(
            self.render_surface,
            (
                data["x"] * width_factor + 200,
                data["y"] * height_factor + 115,
                width,
                height,
            ),
            box_only=True,
            themed=True,
        ).set_selected(kana not in kana_list)

        for kana, data in self.kana.table.items():
            self.checkboxes[kana] = gen_checkbox(kana, data)
        for row_name, data in self.kana.row_table.items():
            self.row_checkboxes[row_name] = gen_checkbox(row_name, data)
        for col_name, data in self.kana.col_table.items():
            self.col_checkboxes[col_name] = gen_checkbox(col_name, data)

        # update the rows and columns which could be wrong by default
        self._update_kana()
Example #22
0
    def setUp(self):
        self.root_storage = tempfile.TemporaryDirectory()
        settings = Settings({'tested': True})
        settings.apis['Kink.com']._site_capabilities = []
        if settings.apis.get('Default', None) is not None:
            settings.apis['Default']._site_capabilities = []
        self.kinksorter = KinkSorter(self.root_storage.name, settings)
        self.kinksorter._is_video_file = MagicMock(return_value=b"video/")

        self.file1 = tempfile.NamedTemporaryFile(dir=self.root_storage.name,
                                                 delete=False)
        self.file2 = tempfile.NamedTemporaryFile(dir=self.root_storage.name,
                                                 delete=False)
        self.dir3 = tempfile.TemporaryDirectory(dir=self.root_storage.name)
        self.file3 = tempfile.NamedTemporaryFile(dir=self.dir3.name,
                                                 delete=False)
Example #23
0
    def configure_authentication(self, config):
        password = Settings.get_password()

        if password:
            passdict = { 'muckebox' : password }
            checkpassword = cherrypy.lib.auth_basic.checkpassword_dict(passdict)
            config.update({
                    'tools.auth_basic.on': True,
                    'tools.auth_basic.realm': 'muckebox',
                    'tools.auth_basic.checkpassword': checkpassword
                    })

            return True
        else:
            cherrypy.log("Password is not set", self.LOG_TAG,
                         logging.WARNING)
            return False
Example #24
0
    def configure(self):
        config = { }

        self.configure_logs(config)
        self.configure_server(config)

        ssl_enabled = self.configure_ssl(config)
        password_enabled = self.configure_authentication(config)

        if not ((ssl_enabled and password_enabled) or
                Settings.allow_insecure()):
            cherrypy.log("Insecure operation disabled, stopping", self.LOG_TAG)
            return False

        cherrypy.config.update(config)

        return True
Example #25
0
 def __init__(self, filename):
     from utils import Scanner
     fn = Settings.locate_file(filename)
     if os.path.exists(fn):
         f = open(fn)
         string = f.read()
         string.replace('\t', ' ')
         file_without_comment = Scanner.remove_comments(string)
         scanner = Scanner.Scanner(file_without_comment)
         scanner.next()
         self.rules = []
         self.functions = []
         self.function_map = {}
         self.parse_rules(scanner)
         f.close()
     else:
         logger.error("Cannot locate template file %s", filename)
Example #26
0
def multiple_rotors_3():
    rotor_1 = machine_data.get_rotor("i")
    rotor_2 = machine_data.get_rotor("ii")
    rotor_3 = machine_data.get_rotor("iii")
    etw = machine_data.get_entry_wheel('etw')
    reflector = machine_data.get_reflector("b")

    rotor_1.update({'start_position': 'Q', 'position': 1})
    rotor_2.update({'start_position': 'E', 'position': 2})
    rotor_3.update({'start_position': 'V', 'position': 3})

    settings = Settings()
    settings.add_entry_wheel(etw)
    settings.add_rotors([rotor_1, rotor_2, rotor_3])
    settings.add_reflector(reflector)

    enigma = Enigma(settings=settings)

    print(enigma.parse("A"))
Example #27
0
def multiple_rotors_4():
    rotor_1 = machine_data.get_rotor("iv")
    rotor_2 = machine_data.get_rotor("v")
    rotor_3 = machine_data.get_rotor("beta")
    etw = machine_data.get_entry_wheel('etw')
    reflector = machine_data.get_reflector("b")

    rotor_1.update({'start_position': 'A', 'position': 1, 'ring_setting': 14})
    rotor_2.update({'start_position': 'A', 'position': 2, 'ring_setting': 9})
    rotor_3.update({'start_position': 'A', 'position': 3, 'ring_setting': 24})

    settings = Settings()
    settings.add_entry_wheel(etw)
    settings.add_rotors([rotor_1, rotor_2, rotor_3])
    settings.add_reflector(reflector)

    enigma = Enigma(settings=settings)

    print(enigma.parse("H"))
Example #28
0
    def loadPolicy(self, filename):
        """
        load model and replay buffer
        """
        # lock.acquire()
        tmp = self.out_policy_file.split('/')
        nfilename = tmp[-1].split('-')[1:-1]
        nfilename.append('shared-lastest')
        nfilename = '-'.join(nfilename)
        tmp[-1] = nfilename
        nfilename = '/'.join(tmp)

        tmp = filename.split('-')
        str_tmp = ''
        for i in range(len(tmp) - 2):
            str_tmp = str_tmp + tmp[i] + '-'
        str_tmp = str_tmp + tmp[-2]

        globalEpisodeCount = copy.deepcopy(Settings.get_count())

        if tmp[-1].split('.')[-1] == '0' or globalEpisodeCount == 0:
            # lock.acquire()
            self.dqn.load_network(str_tmp + '-00.21.dqn.ckpt')
            # lock.release()
        else:
            # lock.acquire()
            self.dqn.load_test_network(nfilename + '.dqn.ckpt')
            self.dqn.load_trainer(filename + '.dqn.ckpt')
            # lock.release()

        # load replay buffer

        try:
            print 'load from: ', filename
            f = open(filename + '-' + self.domainString + '.episode', 'rb')
            loaded_objects = []
            for i in range(2):  # load nn params and collected data
                loaded_objects.append(pickle.load(f))
            self.samplecount = int(loaded_objects[0])
            self.episodes[self.domainString] = copy.deepcopy(loaded_objects[1])
            self.logger.info(
                "Loading both model from %s and replay buffer..." % filename)
            f.close()
        except:
            self.logger.info("Loading only models...")
Example #29
0
def multiple_rotors_5():
    rotor_1 = machine_data.get_rotor("I")
    rotor_2 = machine_data.get_rotor("ii")
    rotor_3 = machine_data.get_rotor("III")
    rotor_4 = machine_data.get_rotor("iv")
    etw = machine_data.get_entry_wheel('etw')
    reflector = machine_data.get_reflector("c")

    rotor_1.update({'start_position': 'Q', 'position': 1, 'ring_setting': 7})
    rotor_2.update({'start_position': 'e', 'position': 2, 'ring_setting': 11})
    rotor_3.update({'start_position': 'V', 'position': 3, 'ring_setting': 15})
    rotor_4.update({'start_position': 'Z', 'position': 4, 'ring_setting': 19})

    settings = Settings()
    settings.add_entry_wheel(etw)
    settings.add_rotors([rotor_1, rotor_2, rotor_3, rotor_4])
    settings.add_reflector(reflector)

    enigma = Enigma(settings=settings)

    print(enigma.parse("Z"))
Example #30
0
    def __init__(
        self,
        screen,
        is_controller,
        option: str,
    ) -> None:
        self.config = Settings()
        self.option = option

        self.screen: pg.Surface = screen
        self.background_image: pg.Surface = self.config.bg_image
        self.is_controller: bool = is_controller

        self.sound_chip_1 = self.config.sound_chip_1
        self.sound_chip_2 = self.config.sound_chip_2
        self.volume = self.config.volume
        self.chip_1 = self.config.chip_1
        self.chip_2 = self.config.chip_2
        self.ai_chip: int = 2
def register():
    reload_topbar_menu()

    for cls in classes:
        try:
            bpy.utils.register_class(cls)
        except ValueError:
            pass

    try:
        bpy.types.Scene.panel_props = bpy.props.PointerProperty(
            type=PanelPropertyGroup)
    except AttributeError:
        pass
    finally:
        bpy.types.TOPBAR_MT_editor_menus.append(
            TOPBAR_MT_google_earth_optimization_menus.draw)

        if not hasattr(bpy.types.Scene, "settings"):
            bpy.types.Scene.settings = Settings(get_sources_path())
Example #32
0
    def train(self):
        '''
        call this function when the episode ends
        '''

        # print(threading.currentThread().getName() + ' Domain: ' +self.domainString + ' Training')

        if not self.is_training:
            self.logger.info("Not in training mode")
            return
        else:
            self.logger.info("Update dqn policy parameters.")

        self.episodecount += 1

        # lock = Settings.load_lock()
        # lock.acquire()
        # try:
        Settings.add_count()
        globalEpisodeCount = copy.deepcopy(Settings.get_count())

        # print('###################################################')
        # print(threading.currentThread().getName() + ' ' + str(globalEpisodeCount))

        self.logger.info("Sample Num so far: %s" % (self.samplecount))
        self.logger.info("Episode Num so far: %s" % (self.episodecount))

        # if self.samplecount >= self.minibatch_size * 10 and self.episodecount % self.training_frequency == 0:
        if self.samplecount >= self.minibatch_size * 10 and globalEpisodeCount % self.training_frequency == 0:
            self.logger.info('start training...')

            # print('reshaped_targetdis_shape: ')
            # print(reshaped_targetdis.shape)
            # print('a_batch_one_hot_shape: ')
            # print(a_batch_one_hot.shape)

            assert len(Settings.global_policysaver) == Settings.global_threadsnum
            # self.dqn.reset_noise()
            total_batch_size = 0
            for k, v in Settings.global_policysaver.items():
                s_batch, a_batch_one_hot, reshaped_targetdis = Settings.global_hackpolicysaver[k]._sample_and_updateQ()
                grad, batch_size = Settings.global_policysaver[k].train(s_batch, a_batch_one_hot, reshaped_targetdis)
                total_batch_size += batch_size
                Settings.load_grad(grad, k)

            assert len(Settings.global_gradsaver) == Settings.global_threadsnum
            grads_list = Settings.grad_sum()
            self._load_and_update(grads_list, self.minibatch_size)
            self._savePolicyInc()
Example #33
0
    def __init__(self, screen: Any, data: dict, **kwargs):
        self.screen = screen
        self.data = data
        self.score_1, self.score_2 = data.values()
        self.name_1, self.name_2 = data.keys()
        self.st = Settings()
        self.size = self.st.size
        self.width = self.st.width

        self.resources = Path.resources()
        self.styles = Path.styles()
        self.sounds = Path.sounds()
        self.soundtrack = Path.soundtracks()
        self.font = Path.fonts()
        self.image = Path.images()

        self._createUI(kwargs)

        self.sb = ScoreboardData(data)
        self.sb.updateTable()
        self.sb.winnerUpdate()
Example #34
0
def reload_setting_props_property_group(context, reload_settings_file=True):
    if reload_settings_file:
        sources_path = context.scene.settings.sources_path
        del bpy.types.Scene.settings
        bpy.types.Scene.settings = Settings(sources_path)

    if hasattr(bpy.types.Scene, "setting_props"):
        del bpy.types.Scene.setting_props

    for idx, min_size_value in enumerate(
            bpy.types.Scene.settings.target_min_size_values):
        reverse_idx = (len(bpy.types.Scene.settings.target_min_size_values) -
                       1) - idx
        cur_lod = MAX_PHOTOGRAMMETRY_LOD - reverse_idx

        SettingsPropertyGroup.__annotations__[
            TARGET_MIN_SIZE_VALUE_PROPERTY_PREFIX +
            str(cur_lod)] = IntProperty(
                name=TARGET_MIN_SIZE_VALUE_PROPERTY_PREFIX + str(cur_lod),
                description="set the min size value for the lod " +
                str(cur_lod),
                default=int(min_size_value),
                soft_min=0,
                soft_max=100,
                step=1,
                update=SettingsPropertyGroup.target_min_size_value_updated,
            )

    data = {
        'bl_label': "updatedSettingsPropertyGroup",
        'bl_idname': "wm.updatedSettingsPropertyGroup",
        '__annotations__': SettingsPropertyGroup.__annotations__
    }

    updatedSettingsPropertyGroup = type("updatedSettingsPropertyGroup",
                                        (bpy.types.PropertyGroup, ), data)
    bpy.utils.register_class(updatedSettingsPropertyGroup)

    bpy.types.Scene.setting_props = bpy.props.PointerProperty(
        type=updatedSettingsPropertyGroup)
Example #35
0
    def mouse_event(self, event):
        Screen.mouse_event(self, event)
        if event.type == pygame.MOUSEBUTTONUP:
            if self.widgets["button_menu"].rect_hit(event.pos):
                return {"screen_id": "menuscreen"}

            for kana_widget_id, kana_widget in self.kana_widgets.items():
                checkbox = kana_widget["checkbox"]
                # check whether the kana checkboxes are hit
                checkbox.on_mouse_release(event.pos)
                if checkbox.rect_hit(event.pos):
                    # checkbox is hit, save the new setting
                    Settings.set(kana_widget["setting"], checkbox.selected)
                # check whether the buttons are hit
                if kana_widget["button"].rect_hit(event.pos):
                    return {"screen_id": f"optionsfor{kana_widget_id}"}

            for checkbox_widget_id, checkbox_widget in self.checkboxes.items():
                checkbox = checkbox_widget["checkbox"]
                checkbox.on_mouse_release(event.pos)
                if checkbox.rect_hit(event.pos):
                    # checkbox is hit, save the new setting
                    Settings.set(checkbox_widget["setting"], checkbox.selected)

            # theme switcher related buttons
            if self.theme_left.rect_hit(event.pos):
                self.update_theme_index(-1)

            if self.theme_right.rect_hit(event.pos):
                self.update_theme_index(1)

            if self.theme_apply.rect_hit(event.pos):
                # get the theme from the index and save the new theme
                theme = list(Settings.get("themes").keys())[self.theme_index]
                Settings.set("theme", theme)
                # update the text on the current theme widget
                self.widgets["theme_text"].set_text(
                    f"Current theme: '{theme}'"
                )
                # reapply the (new) theme to the GUI
                Collections.reapply_theme()
Example #36
0
    def __init__(self, args, unknownargs):
        if not debug:
            event_system.create_ipc_server()

        time.sleep(0.2)
        if not trace_debug:
            if not event_system.is_ipc_alive:
                if unknownargs:
                    for arg in unknownargs:
                        if os.path.isdir(arg):
                            message = f"FILE|{arg}"
                            event_system.send_ipc_message(message)

                raise Exception(
                    "IPC Server Exists: Will send data to it and close...")

        settings = Settings()
        settings.create_window()

        controller = Controller(settings, args, unknownargs)
        if not controller:
            raise Exception("Controller exited and doesn't exist...")

        # Gets the methods from the classes and sets to handler.
        # Then, builder from settings will connect to any signals it needs.
        classes = [controller]
        handlers = {}
        for c in classes:
            methods = None
            try:
                methods = inspect.getmembers(c, predicate=inspect.ismethod)
                handlers.update(methods)
            except Exception as e:
                print(repr(e))

        settings.get_builder().connect_signals(handlers)
Example #37
0
        def do(self, pandaScene: PandaScene):
            node = pandaScene.getMainNode()
            node.children.clear()


class QtCommands():
    "Classes to do main job for qt ui action"

    class ActorAdded():
        def __init__(self, name: str):
            self.name = name

        def do(self, wnd: MainWindow):
            wnd.ModelAdded(self.name)


if __name__ == "__main__":
    Settings.init(applicationName='ai_object_browser')
    print('Settings file: "{}"'.format(Settings.fileName()))
    from queue import Queue
    pandaThreadQeue = Queue(16)
    app = QtWidgets.QApplication(sys.argv)
    m = MainWindow()
    PandaSceneThread = PandaSceneThread()
    PandaSceneThread.start()
    m.show()
    app.exec_()
    print('app.exec_()')
    PandaSceneThread.stop()
Example #38
0
    def get_path_in_cache(cls, input, output):
        filekey = "%s:%d" % (input.id, output.quality)
        h = hashlib.sha1(filekey.encode('utf-8')).hexdigest()
        filename = "%s.%s" % (h, output.format)

        return Settings.get_cache_path() + "/" + filename