def fzf(options): """Present an fzf style interface for given options.""" from pyfzf.pyfzf import FzfPrompt _fzf = FzfPrompt() result = _fzf.prompt(options) # print(result) return result
def search_by_name(json_input): name_list = [] for item in json_input: name_list.append((item["name"])) fzf = FzfPrompt() selection = fzf.prompt(name_list) return selection[0]
def draw_remaining(game_id): r = client.get(f"/api/games/{game_id}/") r.raise_for_status() game_data = r.json() player_count = len(game_data["player_stats"]) cards = set(get_ordered_cards(player_count)) for c in game_data["cards"]: cards.remove((c["value"], c["suit"])) if c["chug_duration_ms"]: c["chug_end_start_delta_ms"] = (c["chug_start_start_delta_ms"] + c["chug_duration_ms"]) else: del c["chug_start_start_delta_ms"] last_start_delta_ms = game_data["cards"][-1]["start_delta_ms"] fzf = FzfPrompt() while cards: player_index = -len(cards) % player_count player_name = game_data["player_stats"][player_index]["username"] card = ast.literal_eval( fzf.prompt(sorted(cards), f'--header "Card for {player_name}"')[0]) cards.remove(card) time_delta = get_ms("Time since last card (s): ") start_delta_ms = last_start_delta_ms + time_delta card_data = { "value": card[0], "suit": card[1], "start_delta_ms": start_delta_ms, } last_start_delta_ms = start_delta_ms if card[0] == 14: before_begin = get_ms("Time before begin (s): ") chug_time = get_ms("Chug time (s): ") start = start_delta_ms + before_begin end = start + chug_time card_data["chug_start_start_delta_ms"] = start card_data["chug_end_start_delta_ms"] = end last_start_delta_ms = end game_data["cards"].append(card_data) game_data["has_ended"] = True game_data["description"] = input("Description: ") game_data["player_ids"] = [p["id"] for p in game_data["player_stats"]] game_data["player_names"] = [ p["username"] for p in game_data["player_stats"] ] return game_data
def get_selection(seq, prompt, lines=5, case_insensitive=True, font=None): if in_xsession: return dmenu.show(seq, prompt=prompt, lines=lines, case_insensitive=case_insensitive, font=font) else: fzf = FzfPrompt() return fzf.prompt(seq, '--cycle')[0]
def rcv_init(): while True: input_print('Press enter to select network architecture...') fzf = FzfPrompt() network = fzf.prompt(nets,"--reverse") classes_list = open('classes_names.txt','r').read().split('\n') classes_dict = {} for i in range(len(classes_list)): classes_dict[classes_list[i]] = i input_print('Press enter to select class...') class_name = fzf.prompt(classes_list, "--reverse")[0] iterations = numInput("Select number of iterations (1-infinity): ") os.system("clear") confirm = input_print('Architecture: {}\nClass: {}\nIterations: {}\nConfirm(y/n)? '.format(network[0],class_name,iterations)) if(confirm == 'n'): os.system("clear") continue regularized_class_sample_generator.run_from_import(classes_dict[class_name],network[0],int(iterations),class_name) break
def get_smarts(reactants: str, line: str): delim = " + " successful_rxns = guess_rxn(reactants) rxns = [delim.join(x["names"]) for x in list(successful_rxns.values())] fzf = FzfPrompt() chosen_rxn = fzf.prompt(rxns, f'--prompt="Reaction {line}: "')[0].split(delim) for val in successful_rxns.values(): if chosen_rxn in val.values(): # TODO: also return the rxns, so that the csv can be updated return val["smarts"]
def remove_file(self): fzf = FzfPrompt() google_file_list = self.file_list() file_list = [ "title:" + gf["title"] + " create_date:" + gf["createdDate"] for gf in google_file_list ] file_dict = {} for count, file_name in enumerate(file_list): file_dict[file_name] = count target_file = fzf.prompt(file_dict)[0] file_id = google_file_list[file_dict[target_file]]["id"] file1 = self.drive.CreateFile({'id': file_id}) file1.Trash() # Move file to trash. file1.Delete() # Permanently delete the file.
def select_item(items): fzf = FzfPrompt() enumerated = (f"{n}.\t{item}" for (n, item) in enumerate(items)) try: selected_items = fzf.prompt(enumerated, "-i") except plumbum.commands.processes.ProcessExecutionError: selected_items = None if not selected_items: abort("Nothing selected", code=0) (selected_item, ) = selected_items selected_index = int(selected_item.split(".")[0]) return selected_index
def select_site_and_get_encrypted_password(query, profile): with tempfile.NamedTemporaryFile() as tmp: with open(os.path.join(HOME, CHROME, profile, LOGIN_DATA), 'rb') as f: tmp.write(f.read()) cursor = sqlite3.connect(tmp.name).cursor() cursor.execute('''SELECT origin_url, username_value, password_value FROM logins ORDER BY times_used desc''') passwords = [] for origin_url, account, password in cursor.fetchall(): password = base64.b64encode(password[3:]).decode('utf8') url = urlparse(origin_url) title = codecs.decode(url.netloc.encode('utf8'), 'idna') if title.lower().startswith('www.'): title = title[4:] if url.scheme == 'android': title = '%s://%s' % (url.scheme, title.split('@')[1]) passwords.append({ 'type': 'default', 'title': title, 'subtitle': account, 'arg': password, 'valid': 'true' if len(password) > 0 else 'false', 'autocomplete': title, }) sites = get_site(passwords) fzf = FzfPrompt() selected_site = fzf.prompt(sites) assert len(selected_site) > 0 assert selected_site[0].split("\t") sitename, username = selected_site[0].split("\t") target = None for p in passwords: new_sub = "NOUSER" if len(p["subtitle"]) == 0 else p["subtitle"] if (sitename == p["title"] and username == new_sub): target = p break if DEBUG: print("target: ", target) password_encrypted = target["arg"] return password_encrypted
def layer_vis(): input_print("Choose network: ") ##[ printf(nets[i] + ", ") for i in range(len(nets)-1)] ##printf(nets[-1] + ": ") fzf = FzfPrompt() a = fzf.prompt(nets, "--reverse")[0] print(a); l = numInput("Choose layer: 0-255: ") f = numInput("Choose filter: 0-55: ") #while True: #anim = input_print("Animate optimisation?(y/n): ") #if(anim == "y" or anim == 'yes'): #anim = True #break #elif(anim == "n" or anim == 'no'): #anim = False #break net = Net(a,l,f) net.write()
class Config: def __init__(self): self.model = Model() self.params = Params() self.screen = Screen() self.fzf = FzfPrompt() self.info = '' def manage(self): active = 'off' if self.params.get('active'): active = 'on' self.info = 'Show current tasks: [' + active + ']\n' done = 'off' if self.params.get('done'): done = 'on' self.info += 'Show done tasks: [' + done + ']\n' self.manage_menu() def manage_menu(self): about = ''' Short instruction ----------------- ? - help (this dialog) ! - toggle active tasks v - toggle done tasks t - manage time slots # - backup/restore < - back q - exit ''' self.screen.change_path('~config', '?!vt#<q', about, 'Managing configs', self.info) menu = self.screen.print() if menu == 'q': self.screen.bye() elif menu == '?': self.screen.activate_about() self.manage_menu() elif menu == '!': self.toggle_active() self.manage() elif menu == 'v': self.toggle_done() self.manage() elif menu == 't': self.manage_time_slot_menu() self.manage_menu() elif menu == '<': return else: self.screen.add_fail('This is not implemented...') self.manage_menu() def toggle_active(self): active = self.params.get('active') self.params.update('active', not active) self.screen.add_message('parameter "active" has been toggled') def toggle_done(self): done = self.params.get('done') self.params.update('done', not done) self.screen.add_message('parameter "done" has been toggled') def manage_time_slot_menu(self): tsData = self.model.get_all_time_slots() if tsData: self.info = ' | '.join( ['%s:%s' % (t['name'], t['description']) for t in tsData]) + '\n' else: self.info = None about = ''' Short instruction ----------------- ? - help (this dialog) + - add time slot - - remove time slot < - back q - exit ''' self.screen.change_path('~config/time_slot', '?+-<q', about, 'Managing time slots', self.info) menu = self.screen.print() if menu == 'q': self.screen.bye() elif menu == '?': self.screen.activate_about() self.manage_time_slot_menu() elif menu == '+': self.add_time_slot() elif menu == '-': self.remove_time_slot() elif menu == '<': return else: self.screen.add_fail('This is not implemented...') self.manage_time_slot_menu() def add_time_slot(self): self.screen.print_init('Adding time slot') name = input('Name (short): ') description = input('Description: ') self.model.create_time_slot(name, description) self.screen.add_message('time slot has been created') self.manage_time_slot_menu() def remove_time_slot(self): ts_id = self.select_time_slot() if ts_id is not None: self.model.remove_time_slot(ts_id) self.screen.add_message('time_slot has been deleted') else: self.screen.add_fail('Time slot was not selected...') self.manage_time_slot_menu() def select_time_slot(self): tsData = self.model.get_all_time_slots() if not tsData: self.screen.add_fail('Where is no time slots...') return ts_ids = {} ts = [] for t in tsData: ts.append('%s:%s' % (t['name'], t['description'])) ts_ids['%s:%s' % (t['name'], t['description'])] = t['id'] selected = self.fzf.prompt(ts) if selected: return ts_ids[selected[0]]
def main(): parser = argparse.ArgumentParser( description="AWS SSM console manager", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "--region", "-r", default="eu-west-1", help="Region to retrieve instances from", ) parser.add_argument( "--instanceId", "-i", required=False, help="Filter by instance id by applying .*arg.*", ) parser.add_argument( "--name", "-n", required=False, help="Filter by instance name by applying .*arg.*", ) parser.add_argument( "--address", "-a", required=False, help="IP address of the instance" ) parser.add_argument( "--dryrun", "-d", action="store_true", required=False, help="Dry run, do not connec to the instance just list matchs" ) args = parser.parse_args() instances = get_instances(args) if args.dryrun: print(json.dumps(instances, indent=4)) return if len(list(instances)) == 0: print( "Your search criteria did not match any running instance.\n" + "Exiting..." ) sys.exit(1) fzf = FzfPrompt() option = fzf.prompt(instances) instanceId = option[0].split(" - ")[0] os.execlp("aws", "aws", "ssm", "start-session", "--target", instanceId)
class Tag: def __init__(self): self.model = Model() self.fzf = FzfPrompt() self.screen = Screen() self.config = Config() self.header = '' self.info = None def manage_tag(self, tid=None): if tid: tag = self.model.get_tag(tid) self.header = 'Managing tag: ' + tag['name'] else: self.header = 'Managing tags' tagsData = self.model.get_all_tags() if not tagsData: self.add_tag() tagsData = self.model.get_all_tags() self.info = ' '.join([t['name'] for t in tagsData]) + '\n' self.manage_tag_menu(tid) def manage_tag_menu(self, tid=None): about = ''' Short instruction ----------------- ? - help (this dialog) / - search tag + - add tag - - remove tag @ - append to time slot 0 - list tags without time_slot & - search linked tasks < - back q - exit ''' self.screen.change_path('~tag', '?/+-&@0<q', about, self.header, self.info) menu = self.screen.print() if menu == 'q': self.screen.bye() elif menu == '/': self.search_tag(tid) self.manage_tag_menu(tid) elif menu == '?': self.screen.activate_about() self.manage_tag(tid) elif menu == '+': self.add_tag() elif menu == '-': self.remove_tag(tid) elif menu == '@': self.add_to_time_slot(tid) self.manage_tag(tid) elif menu == '<': return else: self.screen.add_fail('This is not implemented...') self.manage_tag_menu(tid) def add_tag(self): self.screen.print_init('Adding tag') name = input('Name: ') tid = self.model.create_tag(name) self.screen.add_message('tag has been created') self.manage_tag(tid) def search_tag(self, tid=None): tagsData = self.model.get_all_tags() if not tagsData: self.add_tag() tagsData = self.model.get_all_tags() tags = [] for t in tagsData: tags.append(t['name']) selected = self.fzf.prompt(tags) if selected: tag = self.model.get_tag_by_name(selected[0]) self.manage_tag(tag['id']) else: self.screen.add_fail('Tag was not selected...') def remove_tag(self, tid=None): tagsData = self.model.get_all_tags() if not tagsData: self.screen.add_fail('Where is no tags...') self.manage_tag_menu() tags = [] for t in tagsData: tags.append(t['name']) selected = self.fzf.prompt(tags) if selected: self.model.remove_tag_by_name(selected[0]) self.screen.add_message('tag has been deleted') self.manage_tag() else: self.screen.add_fail('Tag was not selected...') def add_to_time_slot(self, tid): if tid is None: self.screen.add_fail('Tag is not selected...') return ts_id = self.config.select_time_slot() if ts_id is None: self.screen.add_fail('Time slot was not selected...') return self.model.add_tag_to_time_slot(tid, ts_id)
class Task: def __init__(self): self.model = Model() self.fzf = FzfPrompt() self.screen = Screen() self.header = '' self.info = '' def search(self): tasks = [] tasksData = self.model.get_all_tasks() if not tasksData: self.add() tasksData = self.model.get_all_tasks() for t in tasksData: tasks.append('%s: %s [ %s ]' % (t['aid'], t['description'], t['tag_names'])) selected = self.fzf.prompt(tasks) if selected: m = re.search(r'^(.+):', selected[0]) aid = m.group(1) if aid: self.edit_task(aid) else: self.screen.add_fail('Task was not selected...') def add(self): self.screen.print_init('Adding task') description = input('Description: ') aid = self.model.create_task_draft(description) self.screen.add_message('task has been created') self.manage_task(aid) def manage_task(self, aid): task = self.model.get_task(aid) self.header = 'Managing task: [' + task['aid'] + '] ' + task[ 'description'] long_term = ' ' if task['long_term'] and task['long_term'] != 'FALSE': long_term = 'x' tags = '' if task['tags']: tags = ' '.join([t['name'] for t in task['tags']]) self.info = '''%s Description: %s Tags: [%s] Long Term: [%s] Created: %s ''' % (task['aid'], task['description'], tags, long_term, task['created_at']) if task['done'] and task['done'] != 'FALSE': self.info += bcolors.ENDC + bcolors.OKGREEN + '\nFinished: ' + task[ 'finished_at'] if task['active'] and task['active'] != 'FALSE': self.info += bcolors.ENDC + bcolors.WARNING + '\nACTIVE' self.manage_task_menu(aid) def manage_task_menu(self, aid): about = ''' Short instruction ----------------- ? - help (this dialog) e - edit content * - toggle long term + - add tag - - remove tag ! - toggle active v - toggle done x - delete task & - add child task > - go to child < - back q - exit ''' self.screen.change_path('~task', '?e*+-!v&><q', about, self.header, self.info) menu = self.screen.print() if menu == 'q': self.screen.bye() elif menu == '?': self.screen.activate_about() self.manage_task_menu(aid) elif menu == 'e': self.edit_task(aid) elif menu == '*': self.toggle_long_term(aid) elif menu == '+': self.add_tags(aid) elif menu == '-': self.remove_tags(aid) elif menu == '!': self.toggle_active(aid) elif menu == 'v': self.toggle_done(aid) elif menu == '<': return else: self.screen.add_fail('This is not implemented...') self.manage_task_menu(aid) def edit_task(self, aid): task = self.model.get_task(aid) long_term = ' ' if task['long_term'] and task['long_term'] != 'FALSE': long_term = 'x' tags = '' if task['tags']: tags = ' '.join([t['name'] for t in task['tags']]) content = '''%s Tags: [%s] Long Term: [%s] Created: %s ''' % (task['aid'], tags, long_term, task['created_at']) if task['done'] and task['done'] != 'FALSE': content += '\nFinished: ' + task['finished_at'] if task['active'] and task['active'] != 'FALSE': content += '\n**ACTIVE**' content += '\n\n# ' + task['description'] if task['content']: content += task['content'] with tempfile.NamedTemporaryFile(suffix='.md', mode='r+') as temp: f = open(temp.name, 'r+') f.write(content) f.close() subprocess.call(['nvim', temp.name]) f = open(temp.name, 'r') new_content = f.read() f.close() temp.close() found = False content = '' for row in new_content.splitlines(): if found: content += '\n' + row continue if row == '# ' + task['description']: found = True self.model.save_content(aid, content) self.screen.add_message('content has been saved') self.manage_task(aid) def toggle_long_term(self, aid): self.model.toggle_long_term(aid) self.screen.add_message('task has been updated') self.manage_task(aid) def toggle_active(self, aid): self.model.toggle_active(aid) self.screen.add_message('task has been activated') self.manage_task(aid) def toggle_done(self, aid): self.model.toggle_done(aid) self.screen.add_message('task has been updated') self.manage_task(aid) def add_tags(self, aid): task = self.model.get_task(aid) unlinked_tags = self.model.get_tags_not_in_task(task['id']) if type(unlinked_tags ) is sqlite3.Cursor and unlinked_tags.rowcount == 0: self.screen.add_fail('Where is no more unlinked tags left...') self.manage_task(aid) tags = [t['name'] for t in unlinked_tags] selected = self.fzf.prompt(tags, '--multi --cycle') if selected: self.model.link_tags_to_task(task['id'], selected) self.screen.add_message('tags have been linked') self.manage_task(aid) else: self.screen.add_fail('Tag was not selected...') def remove_tags(self, aid): task = self.model.get_task(aid) if not task['tags']: self.screen.add_fail('Where is no tags linked...') self.manage_task(aid) tags = [t['name'] for t in task['tags']] selected = self.fzf.prompt(tags, '--multi --cycle') if selected: self.model.unlink_tags_from_task(task['id'], selected) self.screen.add_message('tags have been unlinked') self.manage_task(aid) else: self.screen.add_fail('Tag was not selected...')