Beispiel #1
1
    def process_prog(self, data):
        now = time()

        if now - Status.rTime > 30:
            if sys.DEV_MODE:
                stat = os.statvfs(".")
            else:
                stat = os.statvfs("/var/audio")
            Status.remaining = (stat.f_bsize * stat.f_bavail) / (
                (core.depth / 8) * core.channels * core.rate * core.comp_ratio
            )
            Status.rTime = now
            updateBTimer()
            updateTemp()
            save_config()
            #            core.sync_dir()

        for msg in data:
            d = json.loads(msg)
            d["_t"] = "status"
            # d['c'] = os.getloadavg()
            d["r"] = Status.remaining
            d["s"] = core.port.gotSignal()
            d["ss"] = core.depth
            d["sr"] = core.rate
            #                d['bt'] = hrBTimer()
            d["ct"] = int(getTemp())
            #            if o:
            self.send(d)
        Status.pTime = now
Beispiel #2
0
def learn_name(name):
    # build a response
    response = "Okay {}".format(name)
    # say it
    speaker.speak(response)
    # save the data
    config.save_config("name", name)
Beispiel #3
0
def set_db_message(message):
    print("保存数据库链接信息")
    manager.manager.db_address = message["db_addr"]
    manager.manager.db_dbname = message["db_dbname"]
    manager.manager.db_password = message["db_password"]
    manager.manager.db_username = message["db_username"]
    config.save_config()
Beispiel #4
0
def config_editor():
    # validation errors
    errors = {}
    # values to display in the form
    values = {}
    success = None

    for config_item in config.ALL_ITEMS:
        values[config_item.key] = config_item.value

    if request.method == 'POST':
        for config_item in config.ALL_ITEMS:
            submitted_value = request.form[config_item.key].strip()
            error = config_item.validate(submitted_value)

            if error:
                errors[config_item.key] = error
            else:
                config_item.value = submitted_value

            values[config_item.key] = submitted_value
        
        # Save if there are no errors
        if not errors:
            for config_item in config.ALL_ITEMS:
                config_item.value = values[config_item.key]
            config.save_config()
            success = 'Config updated - some settings may not take effect without restarting'

    return render_template('config_editor.html', ALL_ITEMS=config.ALL_ITEMS, errors=errors,
                           values=values, success=success)
Beispiel #5
0
def main(_):

    # Create a random state using the random seed given by the config. This
    # should allow reproducible results.
    tf.reset_default_graph()
    rng = np.random.RandomState(config.random_seed)
    tf.set_random_seed(config.random_seed)

    # Train / Test
    if config.task == "train":
        # Import trainer module
        from trainer import Trainer

        # Create a trainer object
        task = Trainer(config, rng)
        save_config(config.logdir, config)

    else:
        # Import tester module
        from tester import Tester

        # Create a tester object
        task = Tester(config, rng)

    # Run the task
    task.run()
Beispiel #6
0
    def process_prog(self, data):
        now = time()

        if (now - Status.rTime > 30):
            if sys.DEV_MODE:
                stat = os.statvfs('.')
            else:
                stat = os.statvfs('/var/audio')
            Status.remaining = (stat.f_bsize * stat.f_bavail) / (
                (core.depth / 8) * core.channels * core.rate * core.comp_ratio)
            Status.rTime = now
            updateBTimer()
            updateTemp()
            save_config()
            #            core.sync_dir()

        for msg in data:
            d = json.loads(msg)
            d['_t'] = 'status'
            # d['c'] = os.getloadavg()
            d['r'] = Status.remaining
            d['s'] = core.port.gotSignal()
            d['ss'] = core.depth
            d['sr'] = core.rate
            #                d['bt'] = hrBTimer()
            d['ct'] = int(getTemp())
            #            if o:
            self.send(d)
        Status.pTime = now
Beispiel #7
0
 def start(self):
     self.show_auth_dialog()
     self.show_basedir_dialog()
     self.show_log_path_dialog()
     self.show_ignore_list_dialog()
     config.save_config()
     print('\nAll steps have been gone through.')
Beispiel #8
0
def main(_):

    # Create a random state using the random seed given by the config. This
    # should allow reproducible results.
    rng = np.random.RandomState(config.random_seed)
    tf.set_random_seed(config.random_seed)

    # Train / Test
    if config.task == "train":
        # Import trainer module
        from trainer import Trainer

        # Create a trainer object
        task = Trainer(config, rng)
        save_config(config.logdir, config)

    else:
        # Import tester module
        if 'hpatch' in cst.DATA:
            from methods.lift.evaluation.tester_hpatch import Tester
            print('WARNING: computation on the hpatch dataset')

        if cst.DATA == 'webcam':
            from methods.lift.evaluation.tester_webcam import Tester
            print('WARNING: computation on the webcam dataset')

        if cst.DATA == 'strecha':
            from methods.lift.evaluation.tester_strecha import Tester
            print('WARNING: computation on the strecha dataset')

        # Create a tester object
        task = Tester(config, rng)

    # Run the task
    task.run()
Beispiel #9
0
 def do_reset(self,args):
     if args:
         self.config[args] = get_default_config()[args]
     else:
         self.config = get_default_config()
     save_config(self.config)
     self._print_config()
def prune_model(model, train_ds):
    """ If the bundle entropy is larger than zero, the first conflicting layer 
        and all subsequent layers of the same block type (a, b, c or d) are 
        removed from the architecture.
    """
    print("Start pruning of architecture...", flush=True)
    conflicts = cb.bundle_entropy(model,
                                  train_ds,
                                  config.batch_size,
                                  config.learning_rate,
                                  config.num_classes,
                                  config.conflicting_samples_size,
                                  all_layers=True)

    layer = -1
    for block_type in range(len(config.pruned_layers)):
        new_layers = 0
        for block_layer in range(config.pruned_layers[block_type]):
            layer += 1
            bundle_entropy_of_layer = conflicts[layer][1]

            if bundle_entropy_of_layer <= 0:
                new_layers += 1
                #continue

        config.pruned_layers[block_type] = new_layers
    save_config(config)
Beispiel #11
0
def main():

    args = take_args()

    if args.clear_cache:
        AnyProvider = providers.WeatherProvider()
        AnyProvider.Cache_path = config.WEATHER_PROVIDERS['ACCU']['Cache_path']
        AnyProvider.clear_cache()
        del AnyProvider
        return None

    if args.u:  #sets updating interval
        config.Caching_time = args.u
        config.save_config(config.CONFIG)
        return None

    if args.accu:
        Accu = providers.AccuProvider()
        Accu.initiate(config.WEATHER_PROVIDERS['ACCU'])
        run_app(args, Provider=Accu, forec=args.forec)
    if args.rp5:
        RP5 = providers.RP5_Provider()
        RP5.initiate(config.WEATHER_PROVIDERS['RP5'])
        run_app(args, Provider=RP5, forec=args.forec)
    if args.sin:
        Sinoptik = providers.SinoptikProvider()
        Sinoptik.initiate(config.WEATHER_PROVIDERS['Sinoptik'])
        run_app(args, Provider=Sinoptik, forec=args.forec)
    if args.csv:
        save_csv(config.ACTUAL_WEATHER_INFO, args.csv)
    if args.save:
        save_txt(config.ACTUAL_PRINTABLE_INFO, args.save)

    config.save_config(config.CONFIG)
Beispiel #12
0
 def do_reset(self, args):
     if args:
         self.config[args] = get_default_config()[args]
     else:
         self.config = get_default_config()
     save_config(self.config)
     self._print_config()
Beispiel #13
0
 def set_config(self):
     self.config["ip"] = self.hostVar.get()
     self.config["password"] = self.passwordVar.get()
     self.config["path"] = self.pathVar.get()
     self.config["localPath"] = self.localPathVar.get()
     self.config["user"] = self.userVar.get()
     save_config(self.config)
Beispiel #14
0
	def run(self):
		config.log.info('syncer starts running')
		self.conn = sqlite3.connect(DAEMON_DB_PATH, isolation_level = None)
		self.conn.row_factory = sqlite3.Row
		self.cursor = self.conn.cursor()
		
		# when switch is set, the thread should stop
		while not self.switch.is_set():
			# block until there is something in the queue
			self.empty_lock.wait()
			# clear task queue
			
			while not self.switch.is_set() and not self.queue.empty():
				entry = self.queue.get()
				
				try:
					self.merge_dir(entry)
				except live_api.AuthError as e:
					config.log.error(e.__class__.__name__ + ': ' + str(e))
					app_tokens = self.api.refresh_token(config.APP_CONFIG['token']['refresh_token'])
					self.api.set_access_token(app_tokens['access_token'])
					config.save_token(app_tokens)
					config.save_config()
					self.enqueue(entry[0], entry[1])
				except live_api.NetworkError:
					config.log.error('Network error. Wait for {} seconds.'.format(NETWORKERR_WAIT_INTERVAL))
					time.sleep(NETWORKERR_WAIT_INTERVAL)
					self.enqueue(entry)
				
				self.queue.task_done()
			self.empty_lock.clear()
			config.log.debug('queue is now empty.')
		
		self.conn.close()
		config.log.info('syncer stops.')
Beispiel #15
0
def main():
    while 1:
        current_ip = get_ip()
        if current_ip:
            # 对于拥有多个出口 IP 负载均衡的服务器,上面的 get_ip() 函数会在几个 ip 之间不停切换
            # 然后频繁进入这个判断,进行 update_record(),然后很快就会触发 API Limited 了
            # 于是建立一个IP池记载这个服务器的几个出口IP,以免频繁切换

            ip_count = int(cfg['ip_count'])
            ip_pool = cfg['ip_pool'].split(',')[:ip_count]
            cfg['current_ip'] = current_ip
            if current_ip not in ip_pool:
                # new ip found
                logging.info("new ip found: %s", current_ip)

                ip_pool.insert(0, current_ip)
                cfg['ip_pool'] = ','.join([str(x) for x in ip_pool[:ip_count]])

                try:
                    update_record()
                    save_config()
                except Exception as e:
                    logging.warning('update_recoud or save_config failed: %s',
                                    str(e))
        else:
            logging.error('get current ip FAILED.')

        try:
            interval = int(cfg['interval'])
        except ValueError:
            interval = 5
        # await asyncio.sleep(interval)
        time.sleep(interval)
Beispiel #16
0
 def show_auth_dialog(self):
     print('=' * 30)
     if not query_yes_no(
             'Do you want to authorize onedrive-d to access your OneDrive account?'
     ):
         print('	Skipped.')
         return
     print(
         '\nYou will need to visit the OneDrive authorization page manually, '
     )
     print(
         'log in and authorize the onedrive-d, and then copy and paste the '
     )
     print('callback URL, which should start with \n"%s".\n' %
           self.api.client_redirect_uri)
     print(
         'The callback url is the URL when the authorization page finally goes blank.\n'
     )
     print('Please visit the authorization page via URL:\n')
     print(self.api.get_auth_uri())
     callback_uri = input('\nPlease paste the callback URL:\n')
     try:
         app_tokens = self.api.get_access_token(uri=callback_uri)
         config.save_token(app_tokens)
         config.save_config()
         print('\nonedrive-d has been successfully authorized.')
     except OneDrive_Error as e:
         print(
             'CRITICAL: failed to authorize the client with the given URL.')
         print('%s' % e)
Beispiel #17
0
 def handle(self, event_id, event_args=None):
     print('Dialog object received {} event.'.format(event_id))
     if event_id == 'refresh_code':
         app_tokens = self.api.get_access_token(uri=event_args)
         config.save_token(app_tokens)
         config.save_config()
     elif event_id == 'child_close':
         pass
Beispiel #18
0
 def get_user_auth(self, f):
     x = XMLBuilder('QUERIES')
     with x.QUERY(cmd='REGISTER'):
         x.CLIENT(self.CLIENT_ID_TAG)
     response = self.query_eyeq(x)
     self.USER = response['USER']
     self.config.USER = self.USER
     save_config(f, self.config)
Beispiel #19
0
def apply_gray_change(cf, current_set, gray_max, sw, im_num):
    if gray_max != current_set[0]:
        save_config("scan", "gray_max", gray_max)
        cf["gray_max"] = gray_max
    if sw != current_set[1]:
        im_num = -1
    cv2.setTrackbarPos('Restart', 'Laser Line', 0)
    return im_num
Beispiel #20
0
 def toggle_play_practice(self):
     if self.play_practice_button['background'] == "#00ff00":#color is green, so user is disabling
         self.play_practice_button.configure(background="#ff0000")
         defines.PLAY_PRACTICE=False
     else:#color is red, so user is enabling
         self.play_practice_button.configure(background="#00ff00")
         defines.PLAY_PRACTICE=True
     save_config()
Beispiel #21
0
 def toggle_random_attack(self):
     if self.random_attack_button['background'] == "#00ff00":#color is green, so user is disabling
         self.random_attack_button.configure(background="#ff0000")
         defines.RANDOM_ATTACKS=False
     else:#color is red, so user is enabling
         self.random_attack_button.configure(background="#00ff00")
         defines.RANDOM_ATTACKS=True
     save_config()
Beispiel #22
0
 def get_user_auth(self, f):
     x = XMLBuilder('QUERIES')
     with x.QUERY(cmd='REGISTER'):
         x.CLIENT(self.CLIENT_ID_TAG)
     response = self.query_eyeq(x)
     self.USER = response['USER']
     self.config.USER = self.USER
     save_config(f, self.config)
Beispiel #23
0
 def resizeEvent(self, event: G.QResizeEvent) -> None:
     super(MainWindow, self).resizeEvent(event)
     maximized = self.isMaximized()
     config.config['maximized'] = maximized
     if not maximized:
         config.config['width'] = self.width()
         config.config['height'] = self.height()
     config.save_config()
Beispiel #24
0
 def change_brightness(self):
     value = config.get_brightness()
     value += 1
     if value > 15:
         value = 7
     self.get_system().pmu.setScreenBrightness(value)
     config.save_config("brightness", value)
     print("set and save brightness value to", value)
Beispiel #25
0
 def toggle_move_mouse(self):
     if self.mouse_button['background'] == "#00ff00":#color is green, so user is disabling
         self.mouse_button.configure(background="#ff0000")
         defines.USE_MOUSE=False
     else:#color is red, so user is enabling
         self.mouse_button.configure(background="#00ff00")
         defines.USE_MOUSE=True
     save_config()
Beispiel #26
0
 def toggle_play_ranked(self):
     if self.play_ranked_button['background'] == "#00ff00":#color is green, so user is disabling
         self.play_ranked_button.configure(background="#ff0000")
         defines.PLAY_RANKED=False
     else:#color is red, so user is enabling
         self.play_ranked_button.configure(background="#00ff00")
         defines.PLAY_RANKED=True
     save_config()
Beispiel #27
0
 def toggle_mulligan(self):
     if self.mulligan_button['background'] == "#00ff00":#color is green, so user is disabling
         self.mulligan_button.configure(background="#ff0000")
         defines.MULLIGAN=False
     else:#color is red, so user is enabling
         self.mulligan_button.configure(background="#00ff00")
         defines.MULLIGAN=True
     save_config()
Beispiel #28
0
 def toggle_quest_reroll(self):
     if self.quest_button['background'] == "#00ff00":#color is green, so user is disabling
         self.quest_button.configure(background="#ff0000")
         defines.REROLL_QUESTS=False
     else:#color is red, so user is enabling
         self.quest_button.configure(background="#00ff00")
         defines.REROLL_QUESTS=True
     save_config()
Beispiel #29
0
def save_in_telegram(twitter_msg, context):
    """
    Saves a tweet and video in Telegram (with a archive.is link)
    :param twitter_msg: Twitter Status Object
    :param context: Telegram bot context
    :return: nothing
    """
    tweet_url = "https://www.twitter.com/{}/status/{}".format(
        twitter_msg.user.screen_name, twitter_msg.id)
    logging.info("Saving tweet {}".format(tweet_url))
    if twitter_msg.media is not None:
        saved_url = archive.save_in_archive(tweet_url)
        config.save_config()
        location = tweets.get_geo(twitter_msg)
        caption = "{} {}".format(saved_url, location)
        msg = None
        if saved_url is not None:
            # Individual file
            if len(twitter_msg.media) == 1:
                m = twitter_msg.media[0]
                if m.type == "photo":
                    msg = context.bot.send_photo(config.config["telegram"]["chatid"],
                                                 m.media_url_https,
                                                 disable_notification=True,
                                                 caption=caption)
                elif m.type == "video":
                    best_variant = tweets.get_best_variant(m.video_info["variants"])
                    if best_variant is not None:
                        msg = context.bot.send_video(config.config["telegram"]["chatid"],
                                                     best_variant,
                                                     disable_notification=True,
                                                     caption=caption)

            elif len(twitter_msg.media) > 1:
                mediaArr = []
                for m in twitter_msg.media:
                    if m.type == "photo":
                        mediaArr.append(telegram.InputMediaPhoto(media=m.media_url_https,
                                                                 caption=saved_url))
                    elif m.type == "video":
                        best_variant = tweets.get_best_variant(
                            m.video_info["variants"])
                        if best_variant is not None:
                            mediaArr.append(telegram.InputMediaVideo(media=best_variant,
                                                                     caption=saved_url))
                resps = context.bot.send_media_group(config.config["telegram"]["chatid"],
                                                     mediaArr,
                                                     disable_notification=True)
                if len(resps) > 0:
                    msg = resps[0]
            config.config["cached"][str(twitter_msg.id)] = {
                "archive_url": saved_url,
                "telegram_url": msg.link
            }
            config.save_config()
        else:
            logging.info("error saving tweet {}")
        return msg
Beispiel #30
0
 def _commit(self) -> None:
     config.config['last_target_dir'] = self.get_target_directory()
     config.config['decimals'] = self.get_decimals()
     config.config['prefix'] = self.get_prefix()
     config.config['copy'] = self.is_copy()
     size = self.size()
     config.config['apply_dialog_width'] = size.width()
     config.config['apply_dialog_height'] = size.height()
     config.save_config()
Beispiel #31
0
def configure():
    """loads, configures, and saves runtime configuration"""
    cfg = config.load_config()
    config.set_port(cfg)
    config.set_baud(cfg)
    config.set_update_rate(cfg)
    #config.set_channel(cfg)
    config.set_write_key(cfg)
    config.save_config(cfg)
Beispiel #32
0
def set_answer(update,context):
    if update.message.from_user.id == CONFIG['Admin'] :
        try:
            CONFIG['Feedback_answer'] = context.args[0]
            config.save_config()
            update.message.reply_text('反馈消息已经更新为:%s' % CONFIG['Feedback_answer'])
            return
        except (IndexError, ValueError):
            update.message.reply_text('使用说明: /setanswer 赞了一把,踩了一脚,吐了一地\n请使用逗号将每个按钮的反馈消息分开')
Beispiel #33
0
def unban(user_id):
    """
    allows to unban an user
    :param user_id:
    :return:
    """
    if str(user_id) in config.config["users"]:
        del config.config["users"][str(user_id)]
        config.save_config()
Beispiel #34
0
 def set_startup_file(self):
     layer_paths = []
     for layer in self.image_area:
         layer_paths.append(layer.file_path)
     dialog = SetStartupDialog(layer_paths,self)
     retval = dialog.exec_()
     path = layer_paths[retval]
     self.manager.system.startup_file_path = path
     cfg.save_config(self.startup_dir, self.manager, True)
Beispiel #35
0
def set_feedback(update,context):
    if update.message.from_user.id == CONFIG['Admin'] :
        try:
            CONFIG['Feedback_text'] = context.args[0]
            config.save_config()
            update.message.reply_text('反馈按钮已经更新为:%s' % CONFIG['Feedback_text'] )
            return
        except (IndexError, ValueError):
            update.message.reply_text('使用说明: /setfeedback 👍,👎,🤮\n请使用逗号将按钮分开')
Beispiel #36
0
def set_master_key():
    config_object = config.load_config(GLOBAL_CONFIG_FILEPATH)
    section = "MAPAdmin"
    if section not in config_object.sections():
        config_object.add_section(section)
    master_key = raw_input("Enter the master key : ")
    if master_key != "":
        config_object = config.set_user_items(
            config_object, section, {"MAPILLARY_SECRET_HASH": master_key})
        config.save_config(config_object, GLOBAL_CONFIG_FILEPATH)
    return master_key
Beispiel #37
0
 def config_deckbutton(self):
     deck=self.current_deckopt_num
     if self.deck_buttons[deck]['background'] == "#00ff00":#color is green, so user is disabling
         self.deck_buttons[deck].configure(background="#ff0000")
         self.deckopt_button.configure(background="#ff0000",text="Deck %i Disabled"%(deck+1))
         defines.DECKS_TO_USE.remove(deck)
     else:#color is red, so user is enabling
         self.deck_buttons[deck].configure(background="#00ff00")
         self.deckopt_button.configure(background="#00ff00",text="Deck %i Enabled "%(deck+1))
         defines.DECKS_TO_USE.append(deck)
     save_config()
Beispiel #38
0
 def set_quit(self):
     """退出播放"""
     self.q = True
     self.player.quit()
     subprocess.call('echo -e "\033[?25h";clear', shell=True)
     logger.debug("Terminal reset.")
     # store the token and the default info
     self.douban.login_data.update({"volume": self._volume, "channel": self._channel})
     logger.info(self.douban.login_data)
     config.save_config(self.history, self.douban.login_data)
     sys.exit(0)
Beispiel #39
0
def delete_file(filename):
    """Remove a file"""
    filename = os.path.basename(filename)
    
    # FIXME: possible race condition
    if os.path.exists(secure_path(cagibi_folder, filename)) and filename in files_info:
        os.remove(secure_path(cagibi_folder, filename))
        del files_info[filename]
        save_config(files_info, filename="files.json")
        return "Ok."
    else:
        abort(500, "File doesn't exist or is not in database.")
Beispiel #40
0
def name_input():
    clear()
    is_valid = False
    while not is_valid:
        try:
            choice = input('\n\n  Enter your project name :  ')
            is_valid = True
        except ValueError as err:
            print(("'%s' is not a valid name." % err.args[0].split(": ")[1]))
    name = get_available_name(choice)
    print("\n\nYour project name is {0}\n\n".format(name))
    save_config("scan", "name", name)
Beispiel #41
0
def save_config(data):
    json_obj = json.loads(data)
    config_dict = {}
    for section in json_obj:
        section_content = {}
        for key in json_obj[section]['config']:
            section_content[key] = json_obj[section]['config'][key]
        config_dict[json_obj[section]['name']] = section_content
    config.save_config(config_dict)
    # reload the config
    ConfigSingleton({ConfigElements.YOUTUBE_API_KEY.value: config.get_value_from_config(ConfigElements.YOUTUBE_API_KEY.value, Section.GENERAL),
                     ConfigElements.VIDEO_DIRECTORY.value: config.get_value_from_config(ConfigElements.VIDEO_DIRECTORY.value, Section.GENERAL)})
Beispiel #42
0
def cam_number_input():
    clear()
    is_valid = False
    while not is_valid:
        try:
            print('Enter your camera device number,')
            print('Get it with "uvcdynctrl -l"')
            choice = input('\n\n  Camera device number :')
            is_valid = True
        except ValueError as err:
            print(("'%s' is not a valid name." % err.args[0].split(": ")[1]))
    save_config("scan", "cam", choice)
    print("\n\nYour camera device number is {0}\n\n".format(choice))
Beispiel #43
0
 def apply_cursor_change(self, conf, new, trackbar_name, ini_name):
     # Save in conf dict
     conf[ini_name] = new
     # Apply cam settings if cam parameter
     if self.section == conf["webcam"]:
         print "apply"
         # apply_cam_setting("Brightness" = trackbar_name, new)
         # with trackbar_name = trackbarList[0][0]
         apply_cam_setting(int(conf["cam"]), trackbar_name, new)
     # Save in scan.ini
     # save_config(section, "brightness" = trackbarList[0][1], value)
     if self.section:
         # HD5000 255 29
         save_config(self.section, ini_name, new)
Beispiel #44
0
def remove_website(args):
    user_config = config.get_config()
    try:
        site = user_config["websites"][args.WEBSITE]
    except KeyError:
        print("")
        print("Unknown website configuration : {0}".format(args.WEBSITE))
        print("")
    else:
        del user_config["websites"][args.WEBSITE]
        config.save_config(user_config)
        print("")
        print("Local website configuration removed : {0}".format(args.WEBSITE))
        print("")
Beispiel #45
0
 def do_set(self,args):
     if not args:
         self._print_config()
     else:
         try:
             arglist = re.split(r' +',args)
             k = arglist[0]
             v = ' '.join(arglist[1:])
             set_config_key(self.config,k,v)
             save_config(self.config)
             self._print_config()
         except ValueError:
             print 'Syntax error: %s' % args
         except:
             raise
Beispiel #46
0
def name_input(cf):
    clear()
    is_valid = 0
    while not is_valid :
        try :
            choice = input('\n\n  Enter your project name :  ')
            is_valid = 1
        except ValueError as e :
            print(("'%s' is not a valid name." % e.args[0].split(": ")[1]))
    name = get_available_name(choice)
    print("Your project name is {0}".format)
    cf["name"] = name
    save_config("scan", "name", name)
    # Create directory, variable with this name
    conf = load_config("./scan.ini")
Beispiel #47
0
def create_file(filename):
    """Create a file on the server. The method receives two POST parameters:
        - filename : the filename
        - contents : the contents
    """
    #FIXME: handle directories
    filename = os.path.basename(filename)
    contents = request.forms.get('contents')
    
    # FIXME: possible race condition
    if not os.path.exists(filename) and filename not in files_info:
        fd = open(secure_path(cagibi_folder, filename), "wb")
        fd.write(contents)
        fd.close()
        files_info[filename] = {"rev": 1}
        save_config(files_info, filename="files.json")
        return "Ok."
    else:
        abort(400, "File already exists")
Beispiel #48
0
def filelist():
    """return a list of files with some metadata"""
    folder = {}
    files_info = load_config(filename="files.json")

    for file in os.listdir(cagibi_folder):
        folder[file] = {}
        folder[file]["mtime"] = os.path.getmtime(secure_path(cagibi_folder, file))

        if file not in files_info:
            # Automatically add new files
            files_info[file] = {}
            files_info[file]["rev"] = 1
            # FIXME: don't save the data for every new file.
            save_config(files_info, filename="files.json")
        
        folder[file]["rev"] = files_info[file]["rev"]


    return json.dumps(folder)
Beispiel #49
0
    def btnConfig(self, event=None):
        import configEditor as ce
        import config
        import organ_segmentation as los

        d = los.lisa_config_init()
        root = tk.Tk()
        conf = ce.apply(root, d, (0, 2, 0, 0), use_list=False)
        root.mainloop()
        newconf = {}
        for (k, v) in conf.iteritems():
            key = str(k)
            value = str(v.get())
            try:
                value = eval(value)
            except:
                pass
            newconf[key] = value

        config.save_config(newconf, os.path.join(newconf["output_datapath"], "organ_segmentation.config"))
        self.quit(event)
Beispiel #50
0
    def get_plays(self, config_name, user):
        if self.account != "" and self.password != "":
            self.__sign(self.account, self.password)
        playlist = load_config(config_name)
        for play in playlist:
            alluri = ""

            webpage = get_url(play["url"], self.headers)
            seasons = sort_plays(self.__get_play_from_webpage(webpage, play))

            for season in seasons:
                for episode in seasons[season]:
                    uri = seasons[season][episode]
                    alluri += uri + "\n\r"
                    play['season'] = season
                    play['episode'] = episode

            save_uri("zimuzu", alluri, user)
            save_config(playlist, config_name)

            time.sleep(10)
Beispiel #51
0
    def get_plays(self, config_name, user):
        playlist = load_config(config_name)

        for play in playlist:
            alluri = ""
            allname = ""

            seasons = sort_plays(self.get_play_from_webpage(play))

            for season in seasons:
                for episode in seasons[season]:
                    uri = seasons[season][episode]
                    alluri += uri + "\n\r"
                    allname += str(play['name']) + " ep:" + str(episode) + "\n\r"
                    # play['season'] = season
                    play['episode'] = episode

            save_uri("dmhy", alluri, user)
            save_config(playlist, config_name)

            sleep(15)
Beispiel #52
0
def update_file_hashes(filename):
    """Updates a file using the deltas received by a client"""
    deltas = decode_deltas(json.loads(request.forms.get("deltas")))

    unpatched = open(secure_path(cagibi_folder, filename), "rb")
    save_to = os.tmpfile()
    patchstream(unpatched, save_to, deltas)
    unpatched.close()
    os.unlink(secure_path(cagibi_folder, filename))
    save_to.seek(0)

    # FIXME: rename instead of copying ?
    file_copy = open(secure_path(cagibi_folder, filename), "w+b")
    file_copy.write(save_to.read())
    file_copy.close()
    save_to.close()
    
    files_info[filename] = {"rev": files_info[filename]["rev"] + 1}
    save_config(files_info, filename="files.json")

    return files_info[filename]
Beispiel #53
0
def main():
    # Handle configurations
    home_path = os.path.join(os.path.expanduser("~"), ".irk")
    config_path = os.path.join(home_path, "config")

    client_config_file = os.path.join(config_path, "client.conf")
    bot_config_file = os.path.join(config_path, "bot.conf")

    if not os.path.exists(home_path):
        os.mkdir(home_path)

    if not os.path.exists(config_path):
        os.mkdir(config_path)

    if not os.path.exists(client_config_file):
        client_config = config.interactive_build_config(default_client_config)
        config.save_config(client_config_file, client_config)
    else:
        client_config = config.load_config(client_config_file)

    if not os.path.exists(bot_config_file):
        bot_config = config.interactive_build_config(default_bot_config)
        config.save_config(bot_config_file, bot_config)
    else:
        bot_config = config.load_config(bot_config_file)

    # Retroactively patch home_path into configurations.
    client_config['home_path'] = home_path
    bot_config['home_path'] = home_path

    client_proc = Client(client_config)
    bot_proc = Bot(bot_config)
    client_proc.connect_queues(bot_proc)

    client_proc.start()
    bot_proc.start()

    client_proc.join()
    bot_proc.join()
Beispiel #54
0
    def btnConfig(self, event=None):
        import config
        import organ_segmentation as los
        import lisaConfigGui as lcg
        d = los.lisa_config_init()

        newconf = lcg.configGui(d)

        if newconf is None:
# reset config
            os.remove(
                os.path.join(
                    d['output_datapath'],
                    'organ_segmentation.config')
            )
        else:
            config.save_config(
                newconf,
                os.path.join(
                    newconf['output_datapath'],
                    'organ_segmentation.config')
            )
        
        self.quit(event)