Пример #1
0
def main():
    global config_file
    time.sleep(5)
    configPath = Path("db/config.ini")
    if not configPath.is_file():
        config.create_config()
    config_file = config.read_config()

    passdb_conf = config.read_dovecot_passdb_conf_template()
    plist_ldap = config.read_sogo_plist_ldap_template()
    extra_conf = config.read_dovecot_extra_conf()

    passdb_conf_changed = config.apply_config('conf/dovecot/ldap/passdb.conf',
                                              config_data=passdb_conf)
    extra_conf_changed = config.apply_config('conf/dovecot/extra.conf',
                                             config_data=extra_conf)
    plist_ldap_changed = config.apply_config('conf/sogo/plist_ldap',
                                             config_data=plist_ldap)

    if passdb_conf_changed or extra_conf_changed or plist_ldap_changed:
        logging.info(
            "One or more config files have been changed, please make sure to restart dovecot-mailcow and sogo-mailcow!"
        )

    api.api_host = config_file['MailHostName']
    api.api_key = config_file['API-Key']

    while (True):
        sync()
        interval = int(config_file['Sync-Interval'])
        logging.info(
            f"Sync finished, sleeping {interval} seconds before next cycle")
        time.sleep(interval)
Пример #2
0
    def __init__(self):
        # Configfile
        try:
            config = configparser.ConfigParser()
            config.read('config.cfg')
            default = config['DEFAULT']
            self.name = default['name']
            self.width = int(default['width'])
            self.height = int(default['height'])
            self.tps = int(default['tps'])
            filenames = config['FILENAMES']
            self.background = pygame.image.load(os.path.join("game_assets", filenames['background']))
        except KeyError:
            create_config()
            Game()

        # Initialization
        pygame.mixer.pre_init(44100, -16, 2, 512)
        pygame.init()
        self.resolution = (self.width, self.height)
        self.screen = pygame.display.set_mode(self.resolution)
        self.tps_clock = pygame.time.Clock()
        self.tps_delta = 0.0
        self.game_map = GameMap(self)
        self.player = Player(self)
        self.magic_ball = MagicBall(self)

        # Sounds
        pygame.mixer.music.load('game_assets/sounds/game_sound.wav')
        pygame.mixer.music.set_volume(0.3)
        pygame.mixer.music.play(-1)

        # Run main loop
        self.run()
Пример #3
0
def get_master_key():
    master_key = ""
    if os.path.isfile(GLOBAL_CONFIG_FILEPATH):
        global_config_object = config.load_config(GLOBAL_CONFIG_FILEPATH)
        if "MAPAdmin" in global_config_object.sections():
            admin_items = config.load_user(global_config_object, "MAPAdmin")
            if "MAPILLARY_SECRET_HASH" in admin_items:
                master_key = admin_items["MAPILLARY_SECRET_HASH"]
            else:
                create_config = raw_input(
                    "Master upload key does not exist in your global Mapillary config file, set it now?"
                )
                if create_config in ["y", "Y", "yes", "Yes"]:
                    master_key = set_master_key()
        else:
            create_config = raw_input(
                "MAPAdmin section not in your global Mapillary config file, set it now?"
            )
            if create_config in ["y", "Y", "yes", "Yes"]:
                master_key = set_master_key()
    else:
        create_config = raw_input(
            "Master upload key needs to be saved in the global Mapillary config file, which does not exist, create one now?"
        )
        if create_config in ["y", "Y", "yes", "Yes"]:
            config.create_config(GLOBAL_CONFIG_FILEPATH)
            master_key = set_master_key()

    return master_key
Пример #4
0
def cli(ctx, configfile, debug, simulate, verbose):
    config = ctx.obj["config"]
    if configfile:
        with open(configfile, "r") as f:
            config.update(yaml.safe_load(f))
    elif os.path.isfile(os.path.expanduser("~/.trdb.yaml")):
        with open(os.path.expanduser("~/.trdb.yaml"), "r") as f:
            config.update(yaml.safe_load(f))
    elif os.path.isfile("/etc/trdb/conf.yaml"):
        with open("/etc/trdb/conf.yaml", "r") as f:
            config.update(yaml.safe_load(f))
    else:
        create_config()
        print "wrote config out to ~/.trdb.yaml"
        sys.exit(1)
    config.verbose = verbose
    config.debug = debug
    config.simulate = simulate
    if config.debug:
        logging.basicConfig(level=logging.DEBUG)
        print "config:"
        print json.dumps(config, indent=2)
    elif verbose:
        lvl = logging.ERROR - (verbose * 10)
        logging.basicConfig(level=lvl)
    else:
        logging.basicConfig(level=logging.ERROR)
Пример #5
0
def get_master_key():
    master_key = ""
    if os.path.isfile(GLOBAL_CONFIG_FILEPATH):
        global_config_object = config.load_config(GLOBAL_CONFIG_FILEPATH)
        if "MAPAdmin" in global_config_object.sections():
            admin_items = config.load_user(global_config_object, "MAPAdmin")
            if "MAPILLARY_SECRET_HASH" in admin_items:
                master_key = admin_items["MAPILLARY_SECRET_HASH"]
            else:
                create_config = raw_input(
                    "Master upload key does not exist in your global Mapillary config file, set it now?")
                if create_config in ["y", "Y", "yes", "Yes"]:
                    master_key = set_master_key()
        else:
            create_config = raw_input(
                "MAPAdmin section not in your global Mapillary config file, set it now?")
            if create_config in ["y", "Y", "yes", "Yes"]:
                master_key = set_master_key()
    else:
        create_config = raw_input(
            "Master upload key needs to be saved in the global Mapillary config file, which does not exist, create one now?")
        if create_config in ["y", "Y", "yes", "Yes"]:
            config.create_config(GLOBAL_CONFIG_FILEPATH)
            master_key = set_master_key()

    return master_key
def main():
    # if config file doesn't exist
    if not check_file("config.txt"):
        # create config file
        create_config()
    # get and unpack config file
    files_directory = get_config("config.txt")['files_directory']
    index_directory = get_config("config.txt")['index_directory']
    extensions = get_config("config.txt")['extensions']
    delimiter = get_config("config.txt")['delimiter']
    encoding = get_config("config.txt")['encoding']
    # if files directory doesn't exist
    if not check_directory(files_directory):
        # create files directory
        create_directory(files_directory)
    # if index directory doesn't exist
    if not check_directory(index_directory):
        # create index directory
        create_directory(index_directory)
    # if there is an existing index
    if len(find_files(index_directory, ["txt"])) > 0:
        # find all files
        files = find_files(index_directory, extensions)
        # load existing index into memory
        index = load_index(index_directory, files)
    # if there are new files to index
    if len(find_files(files_directory, extensions)) > 0:
        # find all files
        files = find_files(files_directory, extensions)
        # index files
        index_files(files_directory, index_directory, delimiter, files,
                    encoding)
    return
Пример #7
0
 def test_create_config_yaml(self,stream):
         mock.mock_open(stream);
         w=StringIO.StringIO()
         stream().write.side_effect= lambda t: w.write(t)
         config.create_config()
         cnf=yaml.load(w.getvalue())
         assert cnf.history_file==os.path.join(config.config_folder(),config.HISTORY_FILE)
         assert cnf.rss_url==config.URL_NOT_SET
         assert cnf.download_dir==os.path.join(config.config_folder(),config.TORRENTS_DIR)
Пример #8
0
def authenticate_user(user_name):
    user_items = None
    if os.path.isfile(GLOBAL_CONFIG_FILEPATH):
        global_config_object = config.load_config(GLOBAL_CONFIG_FILEPATH)
        if user_name in global_config_object.sections():
            user_items = config.load_user(global_config_object, user_name)
            return user_items
    print("enter user credentials for user " + user_name)
    user_items = prompt_user_for_user_items(user_name)
    config.create_config(GLOBAL_CONFIG_FILEPATH)
    config.update_config(
        GLOBAL_CONFIG_FILEPATH, user_name, user_items)
    return user_items
Пример #9
0
def authenticate_user(user_name):
    user_items = None
    if os.path.isfile(GLOBAL_CONFIG_FILEPATH):
        global_config_object = config.load_config(GLOBAL_CONFIG_FILEPATH)
        if user_name in global_config_object.sections():
            user_items = config.load_user(global_config_object, user_name)
            return user_items
    user_items = prompt_user_for_user_items(user_name)
    if not user_items:
        return None
    config.create_config(GLOBAL_CONFIG_FILEPATH)
    config.update_config(
        GLOBAL_CONFIG_FILEPATH, user_name, user_items)
    return user_items
Пример #10
0
 def __init__(self):
     path = Game.conf()
     config.create_config(path)
     self.config = config.get_config(path)
     self.bullets = []
     self.road = ([Vector(0, 350), Vector(1000, 350)], )
     self.player = Player()
     self.level = 0
     self.tower = None
     self.game_level = 0
     self.monsters = []
     self.lock = threading.Lock()
     self.spawn = threading.Thread(target=self.create, daemon=True)
     self.spell = None
Пример #11
0
 def test_create_config(self,stream,dump,mkpath):
         conf=config.create_config()
         assert conf.history_file==os.path.join(config.config_folder(),config.HISTORY_FILE)
         assert conf.rss_url==config.URL_NOT_SET
         assert conf.download_dir==os.path.join(config.config_folder(),config.TORRENTS_DIR)
         mkpath.assert_called_once()
         dump.assert_called_once()
Пример #12
0
def authenticate_user(user_name):
    user_items = None
    if os.path.isfile(GLOBAL_CONFIG_FILEPATH):
        global_config_object = config.load_config(GLOBAL_CONFIG_FILEPATH)
        if user_name in global_config_object.sections():
            user_items = config.load_user(global_config_object, user_name)
            return user_items
    user_items = prompt_user_for_user_items(user_name)
    if not user_items:
        return None
    try:
        config.create_config(GLOBAL_CONFIG_FILEPATH)
    except Exception as e:
        print("Failed to create authentication config file due to ".format(e))
        sys.exit()
    config.update_config(GLOBAL_CONFIG_FILEPATH, user_name, user_items)
    return user_items
Пример #13
0
 def change_temperature(self, wf):
     temperature = wf.args[2]
     req = aircon.ChangeTemperatureRequest(create_config(), temperature)
     dic = RemoClient.call(req)
     temperature = dic['temp']
     mode = dic['mode']
     text = u'{0}度({1})になったよ'.format(temperature, mode)
     notify.notify(text, u'エアコンの温度を変更')
Пример #14
0
def run():
    with open('models.csv', 'r') as csvfile:
        reader = csv.reader(csvfile)
        header = next(reader)
        # print(header)
        for row in reader:
            args = dict(zip(header, row))
            model_name = args['model_name']
            # print(model_name)
            if os.path.exists('models/{}/config.json'.format(model_name)):
                args = load_config('models/{}/config.json'.format(model_name))
            else:
                create_config(args)
            preprocess(args)
            organize(args)
            print("-------- training --------")
            train(args)
Пример #15
0
def authenticate_user(user_name):
    user_items = None
    if os.path.isfile(GLOBAL_CONFIG_FILEPATH):
        global_config_object = config.load_config(GLOBAL_CONFIG_FILEPATH)
        if user_name in global_config_object.sections():
            user_items = config.load_user(global_config_object, user_name)
            return user_items
    user_items = prompt_user_for_user_items(user_name)
    if not user_items:
        return None
    try:
        config.create_config(GLOBAL_CONFIG_FILEPATH)
    except Exception as e:
        print("Failed to create authentication config file due to {}".format(e))
        sys.exit(1)
    config.update_config(
        GLOBAL_CONFIG_FILEPATH, user_name, user_items)
    return user_items
Пример #16
0
 def show_temperature_and_humidity(self, wf):
     req = device.ListRequest(create_config())
     dic = RemoClient.call(req)
     newest_events = dic[0]['newest_events']
     temp = newest_events['te']['val']
     humo = newest_events['hu']['val']
     text = u"室温: %0.2f度\\n湿度: %0.2f%" % (temp, humo)
     notify.notify(u'室温と湿度', text)
     wf.add_item(title=text, icon='icon.png', arg=text, valid=True)
     wf.send_feedback()
Пример #17
0
def create_app(config_name='default'):
    app = Flask(__name__)

    config = create_config(config_name)
    app.config.from_object(config)

    db.init_app(app)
    ma.init_app(app)
    jwt = JWT(app, authenticate, identity)  # cria /auth

    _initialize_blueprints(app)

    return app
Пример #18
0
def create_version(is_base_version: bool, archive_agent) -> VersionAgent:
    """Create a version.
    :type archive_agent: ArchiveAgent"""
    # generate version uuid
    version_uuid = str(uuid.uuid4())
    while archive_agent.get_version(version_uuid):
        version_uuid = str(uuid.uuid4())

    # prepare version record
    version_record = dict(VERSION_RECORD_TEMPLATE)
    version_record.update({
        'TimeOfCreation': time.time(),
        'IsBaseVersion': is_base_version,
        'UUID': version_uuid
    })
    ABUNDANT_LOGGER.debug('Creating %s version: %s' % ('base' if is_base_version else 'non-base', version_uuid))

    # create version config if no version is present
    version_config_path = os.path.join(archive_agent.archive_dir, 'meta', 'version_config.json')
    if not os.path.exists(version_config_path):
        create_config(VERSION_CONFIG_TEMPLATE, version_config_path)
        ABUNDANT_LOGGER.debug('Created version config: %s' % archive_agent.uuid)

    # add version record
    with get_config(version_config_path, save_change=True) as version_config:
        version_config['VersionRecords'].append(version_record)
    archive_agent.load_versions()
    ABUNDANT_LOGGER.info('Added version record: %s' % version_uuid)

    # create version directory and copy files
    version = archive_agent.get_version(version_uuid)
    if not os.path.exists(version.version_dir):
        os.mkdir(version.version_dir)
    version.copy_files()

    ABUNDANT_LOGGER.info('Created %s version %s' % ('base' if is_base_version else 'non-base', version_uuid))
    return version
Пример #19
0
def main(env, ctrl_type, ctrl_args, overrides, logdir):
    set_global_seeds(0)

    ctrl_args = DotMap(**{key: val for (key, val) in ctrl_args})
    cfg = create_config(env, ctrl_type, ctrl_args, overrides, logdir)
    cfg.pprint()

    assert ctrl_type == 'MPC'

    cfg.exp_cfg.exp_cfg.policy = MPC(cfg.ctrl_cfg)
    exp = MBExperiment(cfg.exp_cfg)

    os.makedirs(exp.logdir)
    with open(os.path.join(exp.logdir, "config.txt"), "w") as f:
        f.write(pprint.pformat(cfg.toDict()))

    exp.run_experiment()
Пример #20
0
def main(_):
    """Launch training"""

    # Load hyperparameters
    params = config.create_config()

    # Prepare function that will be used for loading context/utterance
    model_fn = model.create_model_fn(params, model_impl=selected_model)

    # Prepare estimator
    estimator = tf.contrib.learn.Estimator(model_fn=model_fn,
                                           model_dir=MODEL_DIR,
                                           config=tf.contrib.learn.RunConfig(
                                               gpu_memory_fraction=0.25,
                                               save_checkpoints_secs=60 * 2,
                                               keep_checkpoint_max=1,
                                               log_device_placement=False))

    # Prepare input training examples
    input_fn_train = inputs.create_input_fn(
        mode=tf.contrib.learn.ModeKeys.TRAIN,
        input_files=[TRAIN_FILE],
        batch_size=params.batch_size,
        num_epochs=FLAGS.num_epochs,
        params=params)

    # Prepare input validation examples
    input_fn_eval = inputs.create_input_fn(mode=tf.contrib.learn.ModeKeys.EVAL,
                                           input_files=[VALIDATION_FILE],
                                           batch_size=params.eval_batch_size,
                                           num_epochs=1,
                                           params=params)

    # Load recall metrics for validation
    eval_metrics = metrics.create_evaluation_metrics()

    # Prepare monitor for validation
    eval_monitor = tf.contrib.learn.monitors.ValidationMonitor(
        input_fn=input_fn_eval,
        every_n_steps=FLAGS.eval_every,
        metrics=eval_metrics)

    # Lauch training
    estimator.fit(input_fn=input_fn_train, steps=None, monitors=[eval_monitor])
Пример #21
0
    def show_remocon_list(self, wf):
        conf = config.create_config()
        req = appliance.ListRequest(conf)
        dic_array = RemoClient.call(req)
        remo_cons = []
        for dic in dic_array:
            remo_con = {}
            remo_con['id'] = dic['id']
            remo_con['nickname'] = dic['nickname']
            remo_cons.append(remo_con)

        for remo_con in remo_cons:
            appliance_id = remo_con['id']
            nickname = remo_con['nickname']
            if appliance_id == conf.aircon_id:
                nickname += '(registered)'
            wf.add_item(title = nickname, subtitle=appliance_id, icon='icon.png', arg = appliance_id, valid = True)

        wf.send_feedback()
Пример #22
0
def create_app(config_strategy, override_settings=None, logger=None):
    """
    Create a Flask application using the factory pattern.
    """
    if config_strategy is None:
        abort('Configuration strategy not specified.')

    cfg = create_config(config_strategy=config_strategy,
                        override_settings=override_settings)

    app = Flask(__name__,
                static_folder=cfg.STATIC_DIR,
                template_folder=cfg.TEMPLATE_DIR)

    if logger:
        logger_ = logging.getLogger(logger)
        app.logger.handlers = logger_.handlers
        app.logger.setLevel(logger_.level)

        app.logger.info(f'Using logger: {logger}')
    else:
        logging_map = {
            'debug': logging.DEBUG,
            'info': logging.INFO,
            'warning': logging.WARNING,
            'error': logging.ERROR,
            'critical': logging.CRITICAL,
        }
        logging_level = logging_map[os.getenv('LOG_LEVEL', 'debug')]
        app.logger.setLevel(logging_level)

        app.logger.info('No logger specified, streaming logs to output.')

    app.config.from_object(cfg)

    init_jinja_env(app)
    init_blueprints(app)
    init_extensions(app)
    init_error_handlers(app)
    init_db(app)

    return app
Пример #23
0
def main(args):
    #set_global_seeds(0)

    cfg = create_config(args)
    cfg.pprint()

    assert args.ctrl_type == 'MPC'

    cfg.exp_cfg.exp_cfg.policy = MPC(cfg.ctrl_cfg)
    exp = MBExperiment(cfg.exp_cfg)

    if args.load_model_dir is not None:
        exp.policy.model.load_state_dict(
            torch.load(os.path.join(args.load_model_dir, 'weights')))
    if not os.path.exists(exp.logdir):
        os.makedirs(exp.logdir)
    with open(os.path.join(exp.logdir, "config.txt"), "w") as f:
        f.write(pprint.pformat(cfg.toDict()))

    exp.run_experiment()
def main(env, ctrl_type, ctrl_args, overrides, model_dir, logdir):
    ctrl_args = DotMap(**{key: val for (key, val) in ctrl_args})

    overrides.append(["ctrl_cfg.prop_cfg.model_init_cfg.model_dir", model_dir])
    overrides.append(["ctrl_cfg.prop_cfg.model_init_cfg.load_model", "True"])
    overrides.append(["ctrl_cfg.prop_cfg.model_pretrained", "True"])
    overrides.append(["exp_cfg.exp_cfg.ninit_rollouts", "0"])
    overrides.append(["exp_cfg.exp_cfg.ntrain_iters", "1"])
    overrides.append(["exp_cfg.log_cfg.nrecord", "1"])
    cfg = create_config(env, ctrl_type, ctrl_args, overrides, logdir)
    cfg.pprint()

    env = get_required_argument(cfg.exp_cfg.sim_cfg, "env",
                                "Must provide environment.")
    # 150 for Jaco
    task_hor = get_required_argument(cfg.exp_cfg.sim_cfg, "task_hor",
                                     "Must provide task horizon.")
    policy = MPC(cfg.ctrl_cfg)

    agent_sample(env, task_hor, policy, "transfer.mp4")
Пример #25
0
def main(env, ctrl_type, ctrl_args, overrides, model_dir, logdir):
    ctrl_args = DotMap(**{key: val for (key, val) in ctrl_args})

    overrides.append(["ctrl_cfg.prop_cfg.model_init_cfg.model_dir", model_dir])
    overrides.append(["ctrl_cfg.prop_cfg.model_init_cfg.load_model", "True"])
    overrides.append(["ctrl_cfg.prop_cfg.model_pretrained", "True"])
    overrides.append(["exp_cfg.exp_cfg.ninit_rollouts", "0"])
    overrides.append(["exp_cfg.exp_cfg.ntrain_iters", "1"])
    overrides.append(["exp_cfg.log_cfg.nrecord", "1"])

    cfg = create_config(env, ctrl_type, ctrl_args, overrides, logdir)
    cfg.pprint()

    if ctrl_type == "MPC":
        cfg.exp_cfg.exp_cfg.policy = MPC(cfg.ctrl_cfg)
    exp = MBExperiment(cfg.exp_cfg)

    os.makedirs(exp.logdir)
    with open(os.path.join(exp.logdir, "config.txt"), "w") as f:
        f.write(pprint.pformat(cfg.toDict()))

    exp.run_experiment()
Пример #26
0
    def show_status(self, wf):
        config = create_config()
        req = appliance.ListRequest(config)
        dicts = RemoClient.call(req)
        aircon = None
        for dic in dicts:
            if dic['id'] == config.aircon_id:
                aircon = dic['settings']
                break

        if aircon is None:
            text = u'エアコンが登録されてないっぽい'
            wf.add_item(title=text, icon='icon.png', arg=text, valid=False)
            wf.send_feedback()
            return

        power_state = aircon.get('button', '')
        aircon['button'] = 'ON' if len(power_state) == 0 else 'OFF'
        text = u"設定温度: {temp}度\\nモード: {mode}\\nvol: {vol}\\n電源: {button}".format(
            **aircon)
        notify.notify(u'エアコン設定', text)
        wf.add_item(title=text, icon='icon.png', arg=text, valid=True)
        wf.send_feedback()
Пример #27
0
def main(args):
    set_global_seeds(0)

    cfg = create_config(args)
    cfg.pprint()

    # Set env for PointmassEnv
    if (isinstance(cfg.ctrl_cfg.env, PointmassEnv)):
        # Change optimizer to discrete CEM
        cfg.ctrl_cfg.opt_cfg.mode = 'DCEM'

    #assert args.ctrl_type == 'MPC'
    if args.ctrl_type == 'PuP':
        print("Using Pets-using-Pets Policy.")
        cfg.exp_cfg.exp_cfg.policy = ExploreEnsembleVarianceMPC(cfg.ctrl_cfg)
    elif args.ctrl_type == 'RND':
        assert False, "JL: Not implemented fully yet!"
        print("Using RND Policy.")
        cfg.exp_cfg.exp_cfg.policy = ExploreRNDMPC(cfg.ctrl_cfg)
    else:
        print("Using default MPC Policy.")
        cfg.exp_cfg.exp_cfg.policy = MPC(cfg.ctrl_cfg)

    exp = MBExperiment(cfg.exp_cfg)

    if args.load_model_dir is not None:
        exp.policy.model.load_state_dict(
            torch.load(os.path.join(args.load_model_dir, 'weights')))
    if not os.path.exists(exp.logdir):
        os.makedirs(exp.logdir)
        os.makedirs(os.path.join(exp.logdir, "TRAIN"))
        os.makedirs(os.path.join(exp.logdir, "ADAPT"))

    with open(os.path.join(exp.logdir, "config.txt"), "w") as f:
        f.write(pprint.pformat(cfg.toDict()))

    exp.run_experiment()
Пример #28
0
def create_app():
    app = Flask(__name__)
    config_ = create_config(os.getenv('FLASK_CONFIG') or 'default')
    app.config.from_object(config_)
    app.register_blueprint(api)
    return app
Пример #29
0
                "unet_downsampled",
                "unet_snipped",
                "unet_tapered",
        ]:
            if hparams.out == "fwi_reanalysis":
                ModelDataset = importlib.import_module(
                    f"dataloader.{hparams.out}").ModelDataset
        elif hparams.model in ["unet_interpolated"]:
            if hparams.out == "gfas_frp":
                ModelDataset = importlib.import_module(
                    f"dataloader.{hparams.out}").ModelDataset
        else:
            raise ImportError(
                f"{hparams.model} and {hparams.out} combination invalid.")

    model = Model(hparams).to("cuda" if hparams.gpus else "cpu")
    model.prepare_data(ModelDataset)
    return model


if __name__ == "__main__":
    """
    Script entrypoint.
    """
    hparams = create_config()
    # ---------------------
    # RUN TRAINING
    # ---------------------

    main(hparams)
Пример #30
0
    port = random.randint(3000, 9000)
    subprocess.call("clear", shell=True)
    print("------------------------------------------")
    print("Domain: %s" % domain)
    print("Repository URL: %s" % repo_url)
    print("Repository name: %s" % name)
    print("Port chosen: %s" % port)
    print("File name: %s" % app_name)
    print("------------------------------------------")
    confirm = input("Confirm (y/n) ")
    if confirm != "y":
        print("Fatal: No confirmation!")
        exit()
    subprocess.call("git clone %s ../server/%s -q" % (repo_url, name),
                    shell=True)
    config.create_config(domain, port, name)
    #subprocess.call("sudo certbot -d %s --nginx --redirect -n -q" % domain, shell=True)
    config_db.insert({
        'domain': domain,
        'port': port,
        'folder': name,
        'app_name': app_name
    })
    time.sleep(4)
    reboot_servers.reload()
    time.sleep(4)
    reboot_servers.reload()
    print("Done")
elif action in ['r', 'R']:
    for number, value in enumerate(config_db.all()):
        print("%s) %s" % (number + 1, value['folder']))
Пример #31
0
import csv
from config import create_config
from preprocess import preprocess, organize
from keras_train import train

with open('models.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    header = reader.next()
    #print header
    for row in reader:
        args = dict(zip(header, row))
        print args['model_name']
        create_config(args)
        preprocess(args)
        organize(args)
        train(args)
Пример #32
0
issues_close_parser = issues_subparsers.add_parser("close")
issues_close_parser.add_argument('issue')

issues_view_parser = issues_subparsers.add_parser("view")
issues_view_parser.add_argument('issue')

issues_create_parser = issues_subparsers.add_parser("create")
issues_create_parser.add_argument('title', action='store')
issues_create_parser.add_argument('--description', nargs=1, action='store')

options = base_parser.parse_args()


if not os.path.exists(CONFIG_FILE):
    create_config()

if options.create:
    project_name = options.repository
    description = options.descriptions
    organization = options.organization
    create_repository(project_name, description, organization=organization)
elif options.issues:
    url = find_github_remote()
    username, url = get_username_and_repo(url)
    if options.create:
        title = options.title
        description = options.description
        create_issue(username, url, title, description)
    elif options.list:
        get_issues(username, url, options.assigned)
Пример #33
0
from Tkinter import *
import mysql.connector
from config import create_config

root = Tk()
configscreen = create_config()

# db connection

db = mysql.connector.connect(user="******", password="******", host="localhost",
                             database="magic100", buffered=True)

# globals
all_student_names = []
first_five = []
first_five_id = []
student_id = 0
# functions


def make_selection():
    global student_id, first_five
    next_words_box.delete(0, END)
    remaining_unknown_words_box.delete(0, END)
    first_five = []
    cur = name_list.curselection()
    student_id = int('%d' % cur) + 1
    student_name = all_student_names[student_id-1]
    student_name_title['text'] = student_name

    if student_id < 10:
Пример #34
0
        channel.basic_publish(exchange=exchange_name,
                              routing_key=routing_key,
                              body=message_body)
        logger.info("[x] Message sent to consumer")
        connection.close()
    else:
        click.echo("Host hasn't been configured")


def load_data_file(data_file):
    if not os.path.isabs(data_file):
        data_file = os.path.abspath(data_file)
    with open(data_file) as f:
        message_body = f.read()
    return message_body


def load_config_dict_for_profile(profile):
    config_object = parse_config(CONFIG_PATH)
    config_dict = get_config_dict(config_object, profile)
    return config_dict


cli.add_command(config)
cli.add_command(sd)

if __name__ == '__main__':
    if not os.path.exists(CONFIG_PATH):
        create_config(CONFIG_PATH)
    cli()
Пример #35
0
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    handler = logging.FileHandler('sensor.log')
    logging.getLogger().setLevel(logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    parser = argparse.ArgumentParser(description="Choose parameters to be used with the sensor box")
    parser.add_argument("--sensors", metavar='-j',
                        help="Choose json file with the description of the available sensors",
                        default="config.yaml")
    args = parser.parse_args()

    try:
        with open(args.sensors, 'r') as f:
            try:
                from raspberry_handler import Raspy

                config.create_config(config=yaml.safe_load(f))
                rasp = Raspy(get_serial())
                rasp.run()

            except yaml.YAMLError as exc:
                logger.error(exc)

    except FileNotFoundError:
        logger.error("File sensor settings file ({}) doesn't exist".format(args.sensors))
Пример #36
0
def mainfunction():
    create_config()
    signalchain = SignalChain()
    window = GuiWindow(signalchain=signalchain)
    window.Show()
    window.Join()
Пример #37
0
		time.sleep(1)
	print("match is over!")





if __name__ == "__main__":
	parser = argparse.ArgumentParser()
	parser.add_argument("--config_file", type=str, default=None)
	args = parser.parse_args()

	if args.config_file is None:
		karuta_config = {}
	else:
		karuta_config = create_config(args.config_file)

	if karuta_config.get("poems_dir", None) is None:
		print("No poems directory specified. Can't play sounds. Set `poems_dir` in your config")


	#Preprocessing of config so that everything with 1 arg is recognized as a list.

	for keyword in ["include_syllable_counts", "include_syllable_beginnings", "include_cards",
					"exclude_syllable_counts", "exclude_syllable_beginnings", "exclude_cards"]:
		if karuta_config.get(keyword, None) is not None and type(karuta_config[keyword]) is not list:
			karuta_config[keyword] = [karuta_config[keyword]]

	for i in range(karuta_config.get("num_games", 1)):
		print("starting new game...")
		main(karuta_config)
Пример #38
0
    scope = str(args.scope)
    additional_epochs = list(args.additional_epochs)
    competition_epochs = list(args.competition_epochs)
    batch_sizes = list(args.batch_sizes)
    treshold = float(args.treshold)

    assert len(nets) == 0 or set(nets).issubset(
        set(['u_xception', 'u_resnet50v2', 'unet'])
    ), "nets_to_train must be a subset of ['u_xception', 'u_resnet50v2', 'unet']"
    assert scope in [
        'train', 'predict', 'train+predict'
    ], "scope must be one between train, predict, train+predict"
    assert treshold >= 0.0 and treshold <= 1.0, "treshold must be a float between 0. and 1.0"

    for epochs in additional_epochs:
        assert epochs > 0, "epochs numbers can't be lower or equal than 0"
    for epochs in competition_epochs:
        assert epochs > 0, "epochs numbers can't be lower or equal than 0"
    for batch_size in batch_sizes:
        assert epochs > 0, "batch sizes can't be lower or equal than 0"

    config = create_config(nets, save_path, batch_sizes, additional_epochs,
                           competition_epochs, treshold)

    if scope == 'train' or 'train+predict':
        main_train(config)
        if scope == 'train+predict':
            main_predict(config)
    elif scope == 'predict':
        main_predict(config)