def on_exit(*args): ''' Exits application ''' if app.dirty_config: Configuration.store(config) root.quit()
def main(): # Get parameters from arguments parser = argparse.ArgumentParser(description='Model training') parser.add_argument('-c', '--config_path', type=str, default=None, help='Configuration file') parser.add_argument('-e', '--exp_name', type=str, default=None, help='Name of the experiment') parser.add_argument('-s', '--shared_path', type=str, default='/share/mastergpu/module5', help='Path to shared data folder') parser.add_argument('-l', '--local_path', type=str, default='/share/mastergpu/module5', help='Path to local data folder') arguments = parser.parse_args() assert arguments.config_path is not None, 'Please provide a configuration'\ 'path using -c config/pathname'\ ' in the command line' assert arguments.exp_name is not None, 'Please provide a name for the '\ 'experiment using -e name in the '\ 'command line' # Define the user paths shared_path = arguments.shared_path local_path = arguments.local_path dataset_path = os.path.join(local_path, 'Datasets') shared_dataset_path = os.path.join(shared_path, 'Datasets') experiments_path = os.path.join('/home/master/M5/results', 'Experiments') shared_experiments_path = os.path.join('/home/master/M5/results', 'Experiments') # Load configuration files configuration = Configuration(arguments.config_path, arguments.exp_name, dataset_path, shared_dataset_path, experiments_path, shared_experiments_path) cf = configuration.load() # Train /test/predict with the network, depending on the configuration process(cf) # Copy result to shared directory configuration.copy_to_shared()
def setting_communications(): try: print("before first request") cwd = os.path.dirname(os.path.abspath(__file__)) Configuration(os.path.join(cwd, 'config/config.json')) config = Configuration.get() db = Mongo() pub = Publisher(config["AMQP"]) mqttc = Mongo.get_mqttc() threading.Thread(target=mqttc_keep_alive, args=(mqttc, )).start() except Exception as e: print("log", str(e))
def _save_user_xml(self, random_password): user_xml = os.path.expanduser("~/.faraday/config/user.xml") if not os.path.exists(user_xml): shutil.copy(FARADAY_BASE_CONFIG_XML, user_xml) conf = Configuration(user_xml) conf.setAPIUrl('http://localhost:5985') conf.setAPIUsername('faraday') conf.setAPIPassword(random_password) conf.saveConfig()
def remove_route(self): self.ui.routes_list.blockSignals(True) # fix it!!! current_row = self.ui.routes_list.currentRow() current_path = self.ui.routes_list.currentItem().text() self.ui.routes_list.takeItem(current_row) self.ui.routes_list.blockSignals(False) # update configuration routes = Configuration.routes() routes.remove(current_path) Configuration.set_routes(routes=routes)
def database_backup(): """ Copies db.json from current path to the archieve one with prepending current datetime """ config = Configuration() today = datetime.datetime.today().isoformat() path_to_db = config.get_db_path() path_to_db_without_filename = os.path.dirname(path_to_db) path_to_copy = os.path.join(path_to_db_without_filename, "arch", today + "_db.json") # if archive path does not exist, create one if not os.path.exists(os.path.dirname(path_to_copy)): os.makedirs(os.path.dirname(path_to_copy)) shutil.copy(path_to_db, path_to_copy)
def sendAlarm(self, abstand): config = Configuration() alert = AService.AlertService(self.pubsub) message = "Alarm, wir haben den Schwellwert von:", alert.minimumdistance, " mit", float( abstand), alert.unit, " unterschritten" self.client.publish(config.config["alert_topic"], str(message)) pass
def __init__(self): if not exists(Configuration.index_path()): mkdir(Configuration.index_path()) schema = Schema( title=TEXT(), author=TEXT(), content=TEXT(), url=ID(unique=True, stored=True) ) create_in(dirname=Configuration.index_path(), schema=schema) self._index_database = open_dir( dirname=str(Configuration.index_path()) )
def __init__(self): print("Mongo object init...") self.__config = Configuration.get() self.__mongo_config = self.__config["MONGO"] self.__host = self.__mongo_config["HOST"] self.__user = self.__mongo_config["USER"] self.__password = self.__mongo_config["PASSWORD"] self.__port = self.__mongo_config["PORT"] # self.__auth_db = self.__mongo_config["AUTH_DB"] # self.__timeout = self.__mongo_config["TIMEOUT"] Mongo.connection = MongoClient(self.__host, self.__port, username=self.__user, password=self.__password, authMechanism='SCRAM-SHA-256') # Mongo.connection = MongoClient(f"mongodb+srv://{self.__user}:{self.__password}@{self.__host}/test?retryWrites=true&w=majority") if self.__config["DEBUG"]: self.__set_database(self.__mongo_config["DEBUG_DATABASE"]) else: self.__set_database(self.__mongo_config["DATABASE"]) try: self.__check_connection() Mongo.__mqttc = mqtt.Client() Mongo.__mqttc.connect(self.__mongo_config["MQTT_SERVER"], 1883, 60) Mongo.__mbus_server_ip = self.__mongo_config["MBUS_SERVER"] except Exception as e: raise e
def main(): config = Configuration() if config.config.cmd == 'train': train_seg(config.config) elif config.config.cmd == 'test': test_seg(config.config)
def __init__(self, parent, individual, ann=None): self.individual = individual self.ann = ann config = Configuration.get() wrap=config["fitness"]["tracker"]["parameters"]["wrap"] pull=config["fitness"]["tracker"]["parameters"]["pull"] self.scenario = Simulator(wrap = wrap, pull = pull) top = self.top = Toplevel(parent) top.title("Tracker game - results wrap=" + str(wrap) + " pull=" + str(pull)) top.grid() w = 30 h = 15 self.canvas = TrackerAgentDisplay(top, w, h, wrap=wrap) self.canvas.set_model(self.scenario) self.canvas.grid(row=0, column=0, columnspan=5, sticky=(N,W,S,E) ,padx=4, pady=4) self.v = StringVar() speed_adjuster = Scale(top, from_=10, to=1000, command=self.set_speed,orient=HORIZONTAL, variable=self.v) speed_adjuster.set(400) speed_adjuster.grid(row=1, column=0,padx=4, pady=4) restart_button = Button(top, text="Restart", command=self.reset) restart_button.grid(row=1, column=4,padx=4, pady=4) new_button = Button(top, text="New recording", command=self.restart) new_button.grid(row=1, column=3,padx=4, pady=4) finish_button = Button(top, text="OK", command=self.ok) finish_button.grid(row=2, column=4,padx=4, pady=10) self.record_agent()
def __init__(self, crossover_rate=1.0, mutation_rate=0.01): #print("cross_over: ", crossover_rate, " , mutation_rate :", mutation_rate) self.crossover_rate = crossover_rate self.mutation_rate = mutation_rate self.genotype = None #TODO: parameterize self.k = Configuration.get()["translator"]["parameter"]["parameters"]["k"]
def weatherstack(): config = Configuration.get() url = "http://api.weatherstack.com/current" params = {} params["query"] = config["OPEN_DATA"]["TOWN"] params["access_key"] = config["OPEN_DATA"]["WEATHER_STACK"]["KEY"] r = requests.get(url, params) return r
def weatherapi(): config = Configuration.get() url = "http://api.weatherapi.com/v1/current.json" params = {} params["q"] = config["OPEN_DATA"]["TOWN"] params["key"] = config["OPEN_DATA"]["WEATHER_API"]["KEY"] r = requests.get(url, params) return r
def openweathermap(): config = Configuration.get() url = "http://api.openweathermap.org/data/2.5/weather" params = {} params["q"] = config["OPEN_DATA"]["TOWN"] params["appid"] = config["OPEN_DATA"]["OPEN_WEATHER_MAP"]["KEY"] r = requests.get(url, params) return r
def select_pdf_app(self): pdf_app = QtGui.QFileDialog.getOpenFileName( self, 'Abrir', QtCore.QDir.homePath(), 'Ejecutables (*.exe *.bat)' ) if pdf_app != '': self.ui.pdf_app_route.setText( QtCore.QDir.fromNativeSeparators(pdf_app) ) Configuration.set_app_route( document_type=Configuration.PDF_DOCUMENT, route=pdf_app )
def __init__(self, jsonIn): self._inv = jsonIn if Configuration.is_redis_enabled(): self._redis = redis.StrictRedis(host=Configuration.redis_host, port=Configuration.redis_port, db=Configuration.redis_db) self._groups = [] self._hosts = {} self._parse()
def restore_defaults(self): reply = QtWidgets.QMessageBox.question(self, 'Message', "Are you sure to restore the defaults?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: self._tmp = Configuration() self._tmp.save() config.read() self.accept()
def _redis_vars(self, name, mastervars, group=False): if not Configuration.is_redis_enabled(): return mastervars r_key = "groupvars::" + name if group else "hostvars::" + name r_vars = self._redis.get(r_key) if not r_vars: return mastervars r_json = json.loads(r_vars) result = self._merge_dicts(mastervars, r_json) return result
def update(self): microbars = [ MicroBar(minimum=0, maximum=1) for _ in Configuration().limits ] out = '' out += 'Thermal Load: ' for (fan, headroom, microbar) in zip(Configuration().fans, State().headrooms, microbars): try: load = str(round(1 - headroom, 2))[1:4].ljust(3, '0') bar = microbar.get_bar(value=1 - headroom) out += fan + ' ' out += load + ' ' out += bar + ' ' except TypeError: pass print(out, end='\r')
def __init__(self, parent=None): QtWidgets.QDialog.__init__(self, parent) # temporary Configuration which saves the current changes self._tmp = Configuration() self._tmp.read() vbox = QtWidgets.QVBoxLayout() tab_widget = QtWidgets.QTabWidget() graphics_page = GraphicsSettingsPage(tab_widget, self._tmp) path_page = PathSettingsPage(tab_widget, self._tmp) comp_page = ComputationSettingsPage(tab_widget, self._tmp) self.cutoff_history_entries_for_deletion = lambda: comp_page.tw_cutoff_history.history_entries_for_deletion self.cutoff_preset_entries_for_deletion = lambda: comp_page.tw_cutoff_presets.preset_entries_for_deletion # Ok, Cancel and Restore defaults Buttons ok = QtWidgets.QPushButton('Ok', self) cancel = QtWidgets.QPushButton('Cancel', self) restore_btn = QtWidgets.QPushButton('Restore defaults', self) ok.clicked.connect(self.ok) cancel.clicked.connect(self.cancel) restore_btn.clicked.connect(self.restore_defaults) tab_widget.addTab(graphics_page, 'graphics') tab_widget.addTab(path_page, 'path') tab_widget.addTab(comp_page, 'computation') vbox.addWidget(tab_widget) hbox = QtWidgets.QHBoxLayout() hbox.addStretch() hbox.addWidget(ok) hbox.addStretch() hbox.addWidget(cancel) hbox.addStretch() hbox.addWidget(restore_btn) hbox.addStretch() vbox.addLayout(hbox) self.setLayout(vbox) self.exec_()
def make_adult_selector(selector=FULL, config=None): ''' Factory method create object by the supplied string argument, selector. Configurations are also retrieved and supplied as a kwarg argument for the object. ''' if not config: selections = Configuration.get()["adult_selection"] else: selections = config["adult_selection"] return getattr(sys.modules[__name__], selections[selector]["class_name"])()
def load(path): logger = Txt_file_logger() try: with open(path) as json_file: config = Configuration(**json.load(json_file)) except OSError: logger.error(f"Can`t load config {path}") return Json_config_loader._verify(config)
def make_parent_selector(selector=PROPORTIONATE, config=None): ''' Factory method create object by the supplied string argument, selector. Configurations are also retrieved and supplied as a kwarg argument for the object. ''' if not config: selected = Configuration.get()["parent_selection"][selector] else: selected = config["parent_selection"][selector] config = selected['parameters'] return getattr(sys.modules[__name__], selected["class_name"])(**config)
def make_fitness_evaluator(genome_length, evaluator=DEFAULT, config=None): ''' Factory method create object by the supplied string argument, evaluator. Configurations are also retrieved and supplied as a kwarg argument for the object. ''' if not config: selected = Configuration.get()["fitness"][evaluator] else: selected = config["fitness"][evaluator] config = selected["parameters"] return getattr(sys.modules[__name__], selected["class_name"])(genome_length, **config)
def make_genotype(genotype=DEFAULT, config=None): ''' Factory method create object by the supplied string argument, genotype. Configurations are also retrieved and supplied as a kwarg argument for the object. ''' if not config: selected = Configuration.get()["genotype"][genotype] else: selected = config["genotype"][genotype] config = selected["parameters"] return getattr(sys.modules[__name__], selected["class_name"])(**config)
def initialize_ui(self): routes = Configuration.routes() self.ui.routes_list.clear() for route in routes: self.ui.routes_list.addItem(route) if len(routes) > 0: self.ui.remove_route.setEnabled(True) else: self.ui.remove_route.setDisabled(True)
def make_translator(translator=DEFAULT, config=None): ''' Factory method create object by the supplied string argument, translator. Configurations are also retrieved and supplied as a kwarg argument for the object. ''' if not config: selected = Configuration.get()["translator"][translator] else: selected = config["translator"][translator] config = selected["parameters"] print(config) return getattr(sys.modules[__name__], selected["class_name"])(**config)
def appSpecificInit(self, conf:dict): """This method performs application-specific initialization for the Info application, at app creation time.""" #---------------------------------------------------------- # First, get the system configuration, because it contains # key information we need, such as the location of the AI's # data directory. sysConf = Configuration() # Note this retrieves the singleton instance # of the Configuration class. #------------------------------------------------------ # First, get the location of the AI's data directory, # which is in the system configuration. aiDataDir = sysConf.aiDataDir #----------------------------------------------------- # Next, we need to get the name of the info text file # (relative to that directory). This comes from our # app-specific configuration data. infoFilename = conf['info-filename'] #------------------------------------------------------ # Next, we need to construct the full pathname of the # info text file. infoPathname = path.join(aiDataDir, infoFilename) #------------------------------------------------------ # Next, we need to actually load the info text from the # appropriate data file in that directory. with open(infoFilename) as file: infoText = "\n" + file.read() + "\n" #-------------------------------------------------- # Next, we size our window to exactly fit the text. self.window.nRows = countLines(infoText) #---------------------------------------------- # Finally, we have our window display the text. self.window.addText(helpMsg)
def main(): # Get parameters from arguments parser = argparse.ArgumentParser(description='Model training') parser.add_argument('-c', '--config_path', type=str, default='./config/diwu_rematch.py', help='Configuration file') arguments = parser.parse_args() assert arguments.config_path is not None, 'Please provide a path using -c config/pathname in the command line' print('\n > Start Time:') print(' ' + datetime.now().strftime('%a, %d %b %Y-%m-%d %H:%M:%S')) start_time = time.time() # Define the user paths # Load configuration files configuration = Configuration(arguments.config_path) cf = configuration.load() configurationPATH(cf) process(cf) # End Time end_time = time.time() print('\n > End Time:') print(' ' + datetime.now().strftime('%a, %d %b %Y-%m-%d %H:%M:%S')) print('\n ET: ' + HMS(end_time - start_time))
def add_route(self): path = QtGui.QFileDialog.getExistingDirectory( self, 'Seleccionar ruta', QtCore.QDir.homePath() ) if path != '': for index in xrange(self.ui.routes_list.count()): if self.ui.routes_list.item(index).text() == path: QtGui.QMessageBox.information( self, _from_Utf8('Añadir ruta'), 'La ruta seleccionada ya existe' ) return path_dir = QtCore.QDir(path) if not path_dir.isReadable: QtGui.QMessageBox.critical( self, _from_Utf8('Añadir ruta'), 'El directorio seleccionado no tiene permiso de lectura' ) return # update ui self.ui.routes_list.addItem(path) # update configuration routes = Configuration.routes() routes.append(path) Configuration.set_routes(routes=routes)
def main(): while True: try: email_client = GmailClient(Configuration.get_email_address(), Configuration.get_password()) task = raw_input("What task? ") TaskMailer(task=task, email_client=email_client).send() print "Task sent successfully!" except MissingTaskException: print "Seriously we need a task..." except EmailNotSetException: Configuration.set_email_address(raw_input("We need your GMail username. What is it? ")) except PasswordNotSetException: Configuration.set_password(raw_input("We need your GMail password. Give it up! ")) except BadUsernamePasswordException: Configuration.set_password(raw_input("Google said your password was garbage. Want to try a new one? ")) except CorruptConfigFileException: sys.stderr.write("Your config is corrupt. Why don't you fix it? ") return
def __init__(self, pubsub): config = Configuration() self.broker = config.config["broker_host"] self.port = config.config["broker_port"] logging.info(self.broker, self.port) self.client = mqtt.Client() self.client.connect(self.broker, self.port) self.client.on_message = self.on_message self.client.subscribe(config.config["config_topic"], qos=1) self.client.loop_start() self.pubsub = pubsub self.pubsub.on_connect = self.on_connect self.pubsub.on_message = self.on_message pass
def __init__(self, parent, individual, ann=None): self.individual = individual self.ann = ann config = Configuration.get() wrap = config["fitness"]["tracker"]["parameters"]["wrap"] pull = config["fitness"]["tracker"]["parameters"]["pull"] self.scenario = Simulator(wrap=wrap, pull=pull) top = self.top = Toplevel(parent) top.title("Tracker game - results wrap=" + str(wrap) + " pull=" + str(pull)) top.grid() w = 30 h = 15 self.canvas = TrackerAgentDisplay(top, w, h, wrap=wrap) self.canvas.set_model(self.scenario) self.canvas.grid(row=0, column=0, columnspan=5, sticky=(N, W, S, E), padx=4, pady=4) self.v = StringVar() speed_adjuster = Scale(top, from_=10, to=1000, command=self.set_speed, orient=HORIZONTAL, variable=self.v) speed_adjuster.set(400) speed_adjuster.grid(row=1, column=0, padx=4, pady=4) restart_button = Button(top, text="Restart", command=self.reset) restart_button.grid(row=1, column=4, padx=4, pady=4) new_button = Button(top, text="New recording", command=self.restart) new_button.grid(row=1, column=3, padx=4, pady=4) finish_button = Button(top, text="OK", command=self.ok) finish_button.grid(row=2, column=4, padx=4, pady=10) self.record_agent()
def find_documents(self): """ find valid documents :return: """ self._find_documents() documents = Configuration.indexed_documents() documents_added = [] for document in self._documents_finded: if document in documents: documents.remove(document) else: documents_added.append(document) return documents_added, documents
def search_documents(self): """ search valid documents in config routes :return: document_added, documents deleted """ self.documents_added = [] self.documents_deleted = [] routes = Configuration.routes() for route in routes: document_finder = DocumentFinder(path=route) added, deleted = document_finder.find_documents() self.documents_added += added self.documents_deleted += deleted return len(self.documents_added), len(self.documents_deleted)
def openData(): config = Configuration.get() if request.method == "GET": data = request.values if not data.has_key('source'): return jsonify({"msg": "Source API not provided"}), 400 source = data.get('source') if source not in config["OPEN_DATA"]["SOURCES"]: return jsonify({"msg": "Unknown open data source"}), 400 apiresponse = None if(config["DEBUG"]): apiresponse = debugResponse(source) else: if source == 'openweathermap': apiresponse = openweathermap() if source == 'weatherapi': apiresponse = weatherapi() if source == "weatherstack": apiresponse = weatherstack() if apiresponse.status_code != 200: print("log the error") abort(500) return jsonify(json.loads(apiresponse.text)), 200
def search(self): self.ui.banner.setVisible(False) if len(Configuration.indexed_documents()) != 0: query_manager = QueryManager() results = query_manager.serch( to_search=unicode(self.ui.search_text.text()), field=FIELD_OPTIONS[self.ui.search_filter.currentIndex()] ) if len(results) == 0: self.ui.info_label.setText( _from_Utf8( 'No se encontró ningún documento con esa descripción' ) ) self.ui.search_results_list.setVisible(False) self.ui.info_label.setVisible(True) else: self.ui.search_results_list.clear() for result in results: self.ui.search_results_list.addItem(result['url']) self.ui.search_results_list.setVisible(True) self.ui.info_label.setVisible(False) else: self.ui.info_label.setText( _from_Utf8( 'No exsiten documentos indexados en la base de datos' ) ) self.ui.search_results_list.setVisible(False) self.ui.info_label.setVisible(True)
def test_volt(): config = Configuration() config.read('config/test_config.ini') assert config.volt_device == 'test_volt_device' assert config.volt_interval == 1.5
class App(): def __init__(self): self.CONFIG_FILENAME = 'config/config.ini' self._config = None self._api = None self._gpsDevice = None self._accelDevice = None self._thermoDevice = None self._voltDevice = None self._baroDevice = None self._obdDevice = None self.read_configuration_file() self.configure_obd() self.configure_gps() self.configure_thermo() self.configure_acceleromenter() self.configure_volt() self.configure_baro() self._deviceList = DeviceCollection(thermoDevice=self._thermoDevice, gpsDevice=self._gpsDevice, accelDevice=self._accelDevice, voltDevice=self._voltDevice, baroDevice=self._baroDevice, obdDevice=self._obdDevice) self._manager = Manager(self._config, self._deviceList) def read_configuration_file(self): self._config = Configuration() self._config.read(self.CONFIG_FILENAME) def configure_obd(self): if self._config.obd_device == "obd": self._obdDevice = OBDDevice() elif self._config.obd_device == "mock": self._obdDevice = MockOBDDevice() else: print("incorrect obd config") def configure_gps(self): if self._config.gps_device == "fixed_mock": self._gpsDevice = MockFixedGPSDevice() elif self._config.gps_device == "gps3": self._gpsDevice = GPS3Device() else: print("incorrect gps config") def configure_thermo(self): if self._config.thermo_device == 'fixed_mock': self._thermoDevice = MockFixedThermoDevice() elif self._config.thermo_device == 'rising_mock': self._thermoDevice = MockRisingThermoDevice() elif self._config.thermo_device == "mpu": self._thermoDevice = MPUThermoDevice() else: print("incorrect thermo config") def configure_acceleromenter(self): if self._config.accel_device == "fixed_mock": self._accelDevice = MockFixedAccelDevice() elif self._config.accel_device == "mpu": self._accelDevice = MPUAccelDevice() else: print("incorrect accel config") def configure_volt(self): if self._config.volt_device == 'mock': self._voltDevice = MockVoltDevice() else: print("incorrect volt config") def configure_baro(self): if self._config.baro_device == 'mock': self._baroDevice = MockBaroDevice() else: print("incorrect baro config") def run(self): self._manager.print_all_accumulator_means()
def test_accel(): config = Configuration() config.read('config/test_config.ini') assert config.accel_device == 'test_accel_device' assert config.accel_interval == 1.3
def test_baro(): config = Configuration() config.read('config/test_config.ini') assert config.baro_device == 'test_baro_device' assert config.baro_interval == 1.4
def test_updating_config_does_not_override_other_entries(self): Configuration.set_password('existed') Configuration.set_email_address('some_attribute_value') self.assertEquals('some_attribute_value', Configuration.get_email_address()) self.assertEquals('existed', Configuration.get_password())
def test_password_is_stored_in_a_way_that_looks_like_it_encrypted(self): Configuration.set_password('secret') self.assertNotEquals('secret', self.gateway.get_json()['password'])
def index(self): """ index all documents available :return: """ self.cancel = False # start progress bar data current_document = 0 total_documents = len(self.documents_added) + len(self.documents_deleted) # start info data documents_added = 0 documents_deleted = 0 # update progress bar self.updated_progress.emit(ADDING_STATE, current_document * 100 / total_documents) # add new documents for document_added in self.documents_added: file_info = QtCore.QFileInfo(document_added) document_type = str(file_info.suffix().toLower()) if document_type in DOCUMENTS_PARSERS: parser = DOCUMENTS_PARSERS[document_type] parser.set_filename(document_added) self._index_document( title=parser.title(), author=parser.author(), content=parser.content(), url=unicode(document_added) ) current_document += 1 documents_added += 1 # update indexed documents configuration indexed_documents = Configuration.indexed_documents() indexed_documents.append(document_added) Configuration.set_indexed_documents(indexed_documents) # update info self.updated_info.emit(documents_added, documents_deleted) # cancel index process if self.cancel: self.update_canceled.emit() return # update progress bar self.updated_progress.emit(ADDING_STATE, current_document * 100 / total_documents) # update progress bar self.updated_progress.emit(REMOVING_STATE, current_document * 100 / total_documents) # delete removed documents for document_deleted in self.documents_deleted: self._remove_document(content=document_deleted) current_document += 1 documents_deleted += 1 indexed_documents = Configuration.indexed_documents() indexed_documents.remove(document_deleted) Configuration.set_indexed_documents(indexed_documents) # update info self.updated_info.emit(documents_added, documents_deleted) # cancel index process if self.cancel: self.update_canceled.emit() return # update progress bar self.updated_progress.emit(REMOVING_STATE, current_document * 100 / total_documents) # update progress bar self.updated_progress.emit(DONE_STATE, 100) # update info self.updated_info.emit(documents_added, documents_deleted)
def send(self): if not self.task: raise MissingTaskException() self.email_client.send_email(EmailFromMyself(subject="TODO: {task}".format(task=self.task), body="from GoogleTODO", to_address=Configuration.get_email_address()))
def show_result(best, ann): root = Tk() f = Frame(master=root) config = Configuration.get() result_dialog = ResultDialog(f, best) root.mainloop()
print(dir,"4") genome_length = 306 #272 (no pull and wrap) #352 (pull and wrap) #296 (no pull and no wrap) #306 (no pull and wrap) 9 bit #396 (pull and wrap) 9 bit #342 (no pull and no wrap) 9 bit #486 (no wrap no pull) 3 hidden pop_size = 50 gen = 10 threshold = 30 config = Configuration.get() ea_system = EA(config) listner = Listner() ea_system.add_listener(listner) translator = "parameter" fitness = "tracker" genotype = "default" adult = "mixing" parent = "sigma" ea_system.setup(translator,fitness,genotype,adult,parent,genome_length) best = ea_system.run(pop_size, gen, threshold) ann = RecurrentNeuralNet([5,2,2]) p = best.phenotype_container p = ann.restructure_parameters(p) ann.set_weights(p)
def test_can_save_and_get_password(self): Configuration.set_password('secret') self.assertEquals('secret', Configuration.get_password())
def get_envdict(yaml_config, default_config): """Helper method which returns the environment dict Parameters ---------- yaml_config: Configuration `Configuration` object read from the yaml file default_config: Configuration `Configuration` object created using the default config """ conf_dict = update_dict(default_config.as_dict(), yaml_config.as_dict(), []) config = Configuration(conf_dict) config.connect('PROJECTNAME', 'metadata.projectname') config.connect('VERSION', 'metadata.version') config.connect('AUTHOR', 'metadata.author') config.connect('DEBUG', 'metadata.debug') config.connect('ENABLE_INLINE_MATH', 'metadata.inline_math') config.connect('AUTOINDEX_INCLUDE_FILES', 'metadata.autoindex.include@') config.connect('AUTOINDEX_INCLUDE_TOC', 'metadata.autoindex.toc.show') config.connect('AUTOINDEX_TOC_HEADING', 'metadata.autoindex.toc.heading') config.connect('AUTOINDEX_INCLUDE_SUBPROJECT', 'metadata.autoindex.subproject.show') config.connect('AUTOINDEX_SUBPROJECT_HEADING', 'metadata.autoindex.subproject.heading') config.connect('AUTOINDEX_INCLUDE_APIDOC', 'metadata.autoindex.apidoc.show') config.connect('AUTOINDEX_APIDOC_HEADING', 'metadata.autoindex.apidoc.heading') config.connect('AUTOINDEX_INCLUDE_JAVADOC', 'metadata.autoindex.apidoc.javadoc.show') config.connect('AUTOINDEX_INCLUDE_SWAGGER', 'metadata.autoindex.apidoc.swagger.show') config.connect('AUTOINDEX_RSS_HEADING', 'metadata.autoindex.rss.heading') config.connect('AUTOINDEX_RSS_URL', 'metadata.autoindex.rss.url') config.connect('AUTOINDEX_TWEETS_HEADING', 'metadata.autoindex.twitter.heading') config.connect('AUTOINDEX_TWEETS_QUERY', 'metadata.autoindex.twitter.query') config.connect('MARKDOWN_FLAVOUR', 'build.markdown_flavour', validate=validate_markdown_flavour) config.connect('LOGO', 'build.logo', validate=validate_mimetype_image) config.connect('DOCTHEME', 'build.theme.name') config.connect('DOCTHEME_OPTIONS_KEYS', 'build.theme.options', callback=theme_options_keys) config.connect('DOCTHEME_OPTIONS_VALUES', 'build.theme.options', callback=theme_options_values) config.connect('DOCPATH', 'build.source') config.connect('MOCK_MODULES', 'build.mock@') config.connect('GITHUB_RIBBON_COLOR', 'build.github_ribbon.color') config.connect('GITHUB_RIBBON_POSITION', 'build.github_ribbon.position') config.connect('GITHUB_BUTTONS', 'build.github_button.buttons', callback=github_btn_callback) config.connect('GITHUB_BUTTON_LARGE', 'build.github_button.large') config.connect('GITHUB_BUTTON_SHOW_COUNT', 'build.github_button.show_count') config.connect('SUBPROJECT_URLS', 'build.subproject@url', validate=validate_subproject) config.connect('SUBPROJECT_DOCPATHS', 'build.subproject@source', default='docs', validate=validate_subproject) config.connect('AUTOAPI_PYTHON', 'build.autoapi@language', callback=lambda x: 'python' in x) config.connect('AUTOAPI_JAVA', 'build.autoapi@language', callback=lambda x: 'java' in x) config.connect('AUTOAPI_PYTHON_PATH', 'build.autoapi@', callback=autoapi_python_source) config.connect('AUTOAPI_JAVA_PATH', 'build.autoapi@', callback=autoapi_java_source) config.connect('DOCURL', 'publish.ghpages.url') config.connect('HEROKU_APP_NAME', 'publish.heroku.app_name') config.connect('SWAGGER_SPEC_URL', 'extras.swagger.url') config.connect('SWAGGER_UI', 'extras.swagger.ui') config.connect('JAVADOC_PATH', 'extras.javadoc.path') yaml_config.connect('GITHUB_RIBBON_ENABLE', 'build.github_ribbon', contains=True) yaml_config.connect('GITHUB_BUTTON_ENABLE', 'build.github_button', contains=True) envdict = config.getenv() envdict.update(yaml_config.getenv()) return envdict
def initialize_ui(self): self.ui.pdf_app_route.setText( Configuration.app_route(document_type=Configuration.PDF_DOCUMENT) )
def read_configuration_file(self): self._config = Configuration() self._config.read(self.CONFIG_FILENAME)
class SettingsDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QDialog.__init__(self, parent) # temporary Configuration which saves the current changes self._tmp = Configuration() self._tmp.read() vbox = QtWidgets.QVBoxLayout() tab_widget = QtWidgets.QTabWidget() graphics_page = GraphicsSettingsPage(tab_widget, self._tmp) path_page = PathSettingsPage(tab_widget, self._tmp) comp_page = ComputationSettingsPage(tab_widget, self._tmp) self.cutoff_history_entries_for_deletion = lambda: comp_page.tw_cutoff_history.history_entries_for_deletion self.cutoff_preset_entries_for_deletion = lambda: comp_page.tw_cutoff_presets.preset_entries_for_deletion # Ok, Cancel and Restore defaults Buttons ok = QtWidgets.QPushButton('Ok', self) cancel = QtWidgets.QPushButton('Cancel', self) restore_btn = QtWidgets.QPushButton('Restore defaults', self) ok.clicked.connect(self.ok) cancel.clicked.connect(self.cancel) restore_btn.clicked.connect(self.restore_defaults) tab_widget.addTab(graphics_page, 'graphics') tab_widget.addTab(path_page, 'path') tab_widget.addTab(comp_page, 'computation') vbox.addWidget(tab_widget) hbox = QtWidgets.QHBoxLayout() hbox.addStretch() hbox.addWidget(ok) hbox.addStretch() hbox.addWidget(cancel) hbox.addStretch() hbox.addWidget(restore_btn) hbox.addStretch() vbox.addLayout(hbox) self.setLayout(vbox) self.exec_() def ok(self): global config self._tmp.save() config.read() cutoff_history.remove_list(self.cutoff_history_entries_for_deletion()) cutoff_history.save() cutoff_presets.remove_list(self.cutoff_preset_entries_for_deletion()) cutoff_presets.save() self.accept() for widget in QtWidgets.QApplication.topLevelWidgets(): for gl_widget in widget.findChildren(GLWidget): gl_widget.update_needed = True QtWidgets.QApplication.postEvent(gl_widget, UpdateGLEvent()) def restore_defaults(self): reply = QtWidgets.QMessageBox.question(self, 'Message', "Are you sure to restore the defaults?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: self._tmp = Configuration() self._tmp.save() config.read() self.accept() def cancel(self): self.reject()
def test_can_set_config_value_on_empty_file(self): Configuration.set_email_address('some_attribute_value') self.assertEquals('some_attribute_value', Configuration.get_email_address())
def setUp(self): Configuration.gateway = InMemoryConfigFileGateway() Configuration.set_email_address('*****@*****.**')