def select_scan(): global lightsheetPackages, lightsheetScanPaths, displayNames scanIndex = SelectionMenu.get_selection(displayNames) if scanIndex >= len(displayNames): return None scanName = displayNames[scanIndex] scan = lightsheetPackages[scanIndex] attribs = scan.get_filled_attr_dict() # TODO: Open the scan and spawn the GUI showing the metadata and thumbnail analysisList = ['3D Density Map', 'Stroke Volume', 'Vessel Diameter'] scanMenu = ConsoleMenu(scanName, exit_option_text="Close Scan") viewAttribsItem = FunctionItem("View Metadata", show_scan_metadata, [attribs]) viewMaxProjItem = FunctionItem("View Max-Proj", show_scan_maxproj, [attribs['maxProjPath'], attribs['name']]) #selectAnalysisPackageItem = FunctionItem("View Analysis", select_existing_analysis, [analysisList]) #createNewAnalysisPackageItem = FunctionItem("Import Analysis", perform_new_analysis, [analysisList]) downloadScanItem = FunctionItem("Download Copy", download_scan, [scan.get_uniqueID()]) scanMenu.append_item(viewAttribsItem) scanMenu.append_item(viewMaxProjItem) #scanMenu.append_item(selectAnalysisPackageItem) #scanMenu.append_item(createNewAnalysisPackageItem) scanMenu.append_item(downloadScanItem) scanMenu.show()
def test_init(self): function_item_1 = FunctionItem("function_item_1", fun1) function_item_2 = FunctionItem("function_item_2", fun1, ["-l", "-a", "~"], {"test": 12}, self.menu, True) function_item_3 = FunctionItem(text="function_item_3", function=fun2, args=[1, 2, 3], kwargs={ 1: "thing", 16: "other" }, menu=self.menu, should_exit=False) self.assertEqual(function_item_1.text, "function_item_1") self.assertEqual(function_item_2.text, "function_item_2") self.assertEqual(function_item_3.text, "function_item_3") self.assertIsNone(function_item_1.menu) self.assertEqual(function_item_2.menu, self.menu) self.assertEqual(function_item_3.menu, self.menu) self.assertFalse(function_item_1.should_exit) self.assertTrue(function_item_2.should_exit) self.assertFalse(function_item_3.should_exit) self.assertEqual(function_item_1.function, fun1) self.assertEqual(function_item_2.function, fun1) self.assertEqual(function_item_3.function, fun2) self.assertEqual(function_item_1.args, []) self.assertEqual(function_item_2.args, ["-l", "-a", "~"]) self.assertEqual(function_item_3.args, [1, 2, 3]) self.assertEqual(function_item_1.kwargs, {}) self.assertEqual(function_item_2.kwargs, {"test": 12}) self.assertEqual(function_item_3.kwargs, {1: "thing", 16: "other"})
def process_data(name, data, page, nested=None): if isinstance(data, Exception): Screen().input(f"DError: {data}") return subtitle = "".join(f"{i} " for i in columns[name]) arr = [f" Page {page - 1}", f" Page {page + 1}"] for en in data: arr.append(" ".join(map(str, en))) sel = SelectionMenu.get_selection(arr, subtitle) if sel in range(2, len(arr)): subtitle = "" for i in range(len(columns[name])): subtitle += f"{columns[name][i]}: {data[sel - 2][i]}; " menu = ConsoleMenu("Item actions", subtitle) if name == "Seller" and nested == None: menu.append_item( FunctionItem("Find products", find_products, [data[sel - 2][0], 1])) elif name == "Product" and nested == None: menu.append_item( FunctionItem("Find sellers", find_sellers, [data[sel - 2][0], 1])) menu.append_item( FunctionItem("Edit", update, [name, columns[name][0], data[sel - 2][0]])) menu.append_item( FunctionItem("Delete", delete, [name, columns[name][0], data[sel - 2][0]])) menu.show() elif sel < 2: return sel + 1
def __init__(self, modes): self.menu = ConsoleMenu("Scene Relighting Control") self.refresh_item = FunctionItem("Refresh frame info", lambda: self.force_main_menu_refresh) self.menu.append_item(self.refresh_item) # Camera controls: exposure and depth range. self.camera_menu = ConsoleMenu("Camera Control") self.camera_menu_item = SubmenuItem("Change camera settings", self.camera_menu, menu=self.menu) self.set_camera_exposure = FunctionItem("Set exposure", self.update_exposure) self.camera_menu.append_item(self.set_camera_exposure) self.exposure = 250 self.depth_range = [1.0, 1.25] self.set_min_depth_item = FunctionItem( "Set min depth [%f]" % self.depth_range[0], self.set_min_depth) self.set_max_depth_item = FunctionItem( "Set max depth [%f]" % self.depth_range[1], self.set_max_depth) self.camera_menu.append_item(self.set_min_depth_item) self.camera_menu.append_item(self.set_max_depth_item) self.menu.append_item(self.camera_menu_item) # Mode selection self.modes = modes self.mode_name = self.modes[0] self.mode_menu = ConsoleMenu("Demo Modes", "Active mode: %s" % self.mode_name) self.mode_menu_item = SubmenuItem("Change demo mode", self.mode_menu, menu=self.menu) self.mode_items = [] for key in self.modes: new_mode_item = FunctionItem("Set mode [%s]" % key, partial(self.set_mode, key)) self.mode_items.append(new_mode_item) self.mode_menu.append_item(new_mode_item) self.menu.append_item(self.mode_menu_item) # Enable/display meshcat vis self.meshcat_vis_active = True self.toggle_meshcat_vis_item = FunctionItem("Disable meshcat vis", self.toggle_meshcat_vis) self.menu.append_item(self.toggle_meshcat_vis_item) # Enable/disable face detection self.face_detection_active = True self.toggle_detector_item = FunctionItem("Disable face detector", self.toggle_face_detector) self.menu.append_item(self.toggle_detector_item) # Adjust image save rate self.image_save_rate = 0 self.set_image_save_rate_item = FunctionItem( "Set frame divider for image saving [curr %d]" % self.image_save_rate, self.set_image_save_rate) self.menu.append_item(self.set_image_save_rate_item) self.menu.start()
def _show_interactive_menu(test_session): """Display an interactive menu based on the current test session state. This will return when the user invokes one of the exit menu items. """ # A menu item for all menus, so that test_session.state is checked again refresh_test_session_state = FunctionItem("Refresh test session state", _no_op, should_exit=True) def _create_menu(desc, epilogue_text, menu_items): console_menu = ConsoleMenu("Test Session API Demo", desc, epilogue_text=epilogue_text) console_menu.append_item(refresh_test_session_state) for name, fn, args, opts in menu_items: menu_item = FunctionItem(name, fn, args, **opts) console_menu.append_item(menu_item) return console_menu # Set up the command line menus based on the current TestSessionState no_channel_to_log_text = ( "Configure at least one channel that can be logged (such as a DAQ input channel) and then " "refresh the test session state. ") invalid_configuration_text = ( "Review and address the errors in FlexLogger and then refresh the test session state." ) menus = { TestSessionState.IDLE: _create_menu( "The test session is idle.", "", [("Start Test", _start_test, [test_session], { "should_exit": True })], ), TestSessionState.RUNNING: _create_menu( "The test session is running.", "", [ ("Add Note", _add_note, [test_session], {}), ("Stop Test", _stop_test, [test_session], { "should_exit": True }), ], ), TestSessionState.NO_VALID_LOGGED_CHANNELS: _create_menu("The project has no channels to log.", no_channel_to_log_text, []), TestSessionState.INVALID_CONFIGURATION: _create_menu("The project has one or more errors.", invalid_configuration_text, []), } while True: state_menu = menus[test_session.state] state_menu.show() if state_menu.selected_item == state_menu.exit_item: break
def test_run(self): mock_function_1 = MagicMock(name="mock_function_1", return_value=5) mock_function_2 = MagicMock(name="mock_function_2", return_value=10) args = [1, 2, 3] kwargs = {"end": "\n", "sep": " "} function_item_1 = FunctionItem("function_item_1", mock_function_1) function_item_2 = FunctionItem("function_item_2", mock_function_2, args, kwargs) function_item_1.action() function_item_2.action() self.assertEqual(function_item_1.get_return(), 5) self.assertEqual(function_item_2.get_return(), 10) mock_function_1.assert_any_call() mock_function_2.assert_called_once_with(*args, **kwargs)
def utf_menu(): menu = ConsoleMenu("Decimal number convertor & File Decoder", "Created with Python") submenu = ConsoleMenu("About Us") submenu.prologue_text = "This is Decimal number convertor which takes a decimal number as a input and shows " \ "number's Unicode, UTF-8 and single character. Created by Vilnius Gediminas " \ "Technical University PRIfs 18/6 student - Rimvydas Kanapka." \ " This program is created for Architecture of Computers and Computer Networks." menu.append_item( FunctionItem("GET Unicode, UTF-8 & Char of a Decimal Number", get_info)) # First menu item menu.append_item(FunctionItem("Decode File", decode)) # Second menu item menu.append_item(SubmenuItem("About Us", submenu, menu=menu)) # Third menu item menu.show()
def _create_menu(desc, epilogue_text, menu_items): console_menu = ConsoleMenu( "Getting and Setting Channel Values API Demo", desc, epilogue_text=epilogue_text) for name, fn, args, opts in menu_items: menu_item = FunctionItem(name, fn, args, **opts) console_menu.append_item(menu_item) return console_menu
def setUp(self): super(TestMultiSelectMenu, self).setUp() self.menu = MultiSelectMenu("Root Menu", "This is a Multi-Select Menu") self.menu.append_item( FunctionItem("Action Item 1", self.detect_action, args=['one'])) self.menu.append_item( FunctionItem("Action Item 2", self.detect_action, args=['two'])) self.menu.append_item( FunctionItem("Action Item 3", self.detect_action, args=['three'])) self.menu.append_item( FunctionItem("Action Item 4", self.detect_action, args=['four'])) self.action_detector = dict() self.assertIsNone(self.action_detector.get('one')) self.assertIsNone(self.action_detector.get('two')) self.assertIsNone(self.action_detector.get('three')) self.assertIsNone(self.action_detector.get('four'))
def _create_menu(desc, epilogue_text, menu_items): console_menu = ConsoleMenu("Test Session API Demo", desc, epilogue_text=epilogue_text) console_menu.append_item(refresh_test_session_state) for name, fn, args, opts in menu_items: menu_item = FunctionItem(name, fn, args, **opts) console_menu.append_item(menu_item) return console_menu
def output_console_menu(): start_directory = os.getcwd() directory_content = get_directory_content(start_directory, False) file_selection_menu = ConsoleMenu("Select file from:", start_directory) for current_dir_item in directory_content: current_dir_item_path = start_directory + os.path.sep + current_dir_item if os.path.isfile(current_dir_item_path): file_selection_menu.append_item(FunctionItem(current_dir_item, get_statistic, [current_dir_item_path, tasks_list])) elif os.path.isdir(current_dir_item_path): current_sub_menu = ConsoleMenu("Select file from:", current_dir_item_path) for current_subdir_item in get_directory_content(current_dir_item_path, True): current_sub_menu.append_item(FunctionItem(current_subdir_item, get_statistic, [ current_dir_item_path + os.path.sep + current_subdir_item, tasks_list])) file_selection_menu.append_item(SubmenuItem(current_dir_item + os.path.sep, current_sub_menu)) file_selection_menu.show()
def vm_menu(): menu = ConsoleMenu("Virtual Machine", "Created with Python") submenu = ConsoleMenu("About Us") submenu.prologue_text = "This is Virtual Machine. Created by Vilnius Gediminas " \ "Technical University PRIfs 18/6 student - Rimvydas Kanapka." \ " This program is created for Architecture of Computers and Computer Networks." menu.append_item(FunctionItem("Start VM", main)) # First menu item menu.append_item(SubmenuItem("About Us", submenu, menu=menu)) # Second menu item menu.show()
def init_menu(self): titulo = "Menú principal" subtitulo = "Programa para cifrar ficheros con AES 256 GCM" prologue = "Para poder encriptar ficheros tiene que estar situados en la carpeta files."\ " Los ficheros *.encrypted y *.decrypted se situarán en la misma carpeta." if not os.path.exists("./my_keystore.jks"): prologue += " PARA HACER USO DE LAS FUNCIONES DE ENCRIPTADO Y DESENCRIPTADO, DEBE CREAR UN ALMACÉN DE CLAVES Y UNA CLAVE (3)." menu = ConsoleMenu(titulo, subtitulo, prologue_text=prologue) cifrado = FunctionItem("Cifrado del fichero", self.encrypt) descifrado = FunctionItem("Descifrado del fichero", self.decrypt) generado_claves = FunctionItem("Generar nueva clave privada", self.generate_key) menu.append_item(cifrado) menu.append_item(descifrado) menu.append_item(generado_claves) menu.show()
def action(self, spoken_text, arguments_list: list = []): # Create the root menu menu = MultiSelectMenu( "Database Menu", "This is a Multi-Select Menu", epilogue_text=("Please select one or more entries " "separated by commas, and/or a range " "of numbers. For example: 1,2,3 or " " 1-4 or 1,3-4"), exit_option_text='Close Databse Viewer') # Add all the items to the root menu menu.append_item( FunctionItem("Contacts db", self.show_table, args=['contacts'])) menu.append_item( FunctionItem("Routines db", self.show_table, args=['routines'])) menu.append_item( FunctionItem("Employers db", self.show_table, args=['employers'])) menu.append_item( FunctionItem("Zoom db", self.show_table, args=['zoom'])) menu.append_item( FunctionItem("Research db", self.show_table, args=['research'])) menu.append_item(FunctionItem("All dbs", self.show_table, args=['all'])) # Show the menu menu.start() menu.join()
def show_tasks_menu(menu_items: list): statistic_items_menu = MultiSelectMenu("Select items, you want to do:", exit_option_text='Continue') i = 0 tasks_to_do = [] for current_item in menu_items: statistic_items_menu.append_item(FunctionItem(current_item, lambda item: tasks_to_do.append(item), [i, ], should_exit=True)) i += 1 statistic_items_menu.show() return {True: [0, 1, 2, 3, 4], False: tasks_to_do}[tasks_to_do in [None, []]]
def tm_menu(): menu = ConsoleMenu("Turing Machine Simulator", "Created with Python") submenu = ConsoleMenu("About Us") submenu.prologue_text = "This is Turing Machine Simulator created by Vilnius Gediminas Technical University " \ "PRIfs 18/6 student - Rimvydas Kanapka." \ " This program is created for Architecture of Computers and Computer Networks." menu.append_item(FunctionItem("RUN Turing Machine", action)) # First menu item menu.append_item(SubmenuItem("About Us", submenu, menu=menu)) # Second menu item menu.show()
def manage_devices(devices): """ Enable/disable a device :param devices: A device object """ prologue_text = "\n".join([ "{} ({})".format(d.name, "Enabled" if d.is_enabled else "Disabled") for d in devices ]) menu = ConsoleMenu(title="Emulation > Devices", prologue_text=prologue_text) menu.append_item( FunctionItem("Enable", api.toggle_devices, args=[devices, True], should_exit=True)) menu.append_item( FunctionItem("Disable", api.toggle_devices, args=[devices, False], should_exit=True)) menu.show()
def main(): #List containing the choices of the user desired_properties: List[DesiredProperty] = [] #Load ontology amsterdam_neighbourhoods = pd.read_csv("data/amsterdam.csv") # Create the menu menu = ConsoleMenu("AreA", "An advisor on Amsterdam's residential areas") # Menu Items desired_prop_item = FunctionItem("Add desired property", desired_prorerty_submenu, [desired_properties]) view_sugg_item = FunctionItem( "Get suggestions", view_suggestions_func, [amsterdam_neighbourhoods, desired_properties]) # Once we're done creating them, we just add the items to the menu menu.append_item(desired_prop_item) menu.append_item(view_sugg_item) # start menu menu.show()
def main(): init() # Define main menu menu = ConsoleMenu( title="Music Library Manager", subtitle="Main Menu", ) # Define add menu addMenu = ConsoleMenu( title="Music Library Manager", subtitle="Where would you like to add a new track?", exit_option_text="Back" ) # Define main menu options opt_display = FunctionItem( "Display Music Library", wait_func, [displayLibrary]) opt_add = SubmenuItem("Add a new track", addMenu) # Define add menu options opt_add_start = FunctionItem( "At the beginning of the list", wait_func, [addTune]) # Add options to the main menu menu.append_item(opt_add) menu.append_item(opt_display) # Add options to the add menu addMenu.append_item(opt_add_start) # Display the menu and wait for user input menu.show() # Print when user runs the 'Exit' option print("Exiting...")
def create_task(name, main, *arg): print(f'[{name}]') args = [] for a in arg: args.append(input(a + ': ')) task = Thread(target=main, args=args) task_menu = FunctionItem(name, terminate_task, [task, name], should_exit=True) task_menu.args.append(task_menu) tasks_menu.append_item(task_menu) task.start() print('Started successfully.') input()
def main(): """ Run the intial setup script, check for an input file and show the main menu """ init_script() read_info_file() # Define Menu menu = ConsoleMenu( title="AWS EC2 and S3 Webserver Configuration Script", subtitle="Developer Operations Assignment 1 - Dylan Gore", ) # Define menu options and what they do opt_full_run = FunctionItem("Run automatic configuration", wait_func, [full_run]) opt_user_input = FunctionItem("Input custom settings", wait_func, [accept_user_input]) opt_active = FunctionItem("List running instances/active buckets", wait_func, [list_active]) opt_monitoring = FunctionItem("Display monitoring info", wait_func, [display_monitor]) # opt_website = FunctionItem("Check if web server is running", wait_func, [check_website]) # opt_iam = FunctionItem("Create IAM role & policy", wait_func, [check_for_iam_role, iam, sts_client]) opt_configure_aws = CommandItem("Configure AWS credentials and Settigns", "aws configure") opt_load_config_file = FunctionItem("Load configuration file", wait_func, [read_info_file]) opt_cleanup = FunctionItem("Cleanup AWS", wait_func, [cleanup]) opt_clear_logs = FunctionItem("Clear logs", wait_func, [clear_logs]) # Add options to menu menu.append_item(opt_full_run) menu.append_item(opt_user_input) menu.append_item(opt_active) menu.append_item(opt_monitoring) # menu.append_item(opt_website) # menu.append_item(opt_iam) menu.append_item(opt_configure_aws) menu.append_item(opt_load_config_file) menu.append_item(opt_cleanup) menu.append_item(opt_clear_logs) # Display the menu and wait for user input menu.show() # Print when user runs the 'Exit' option print("Exiting...")
def manually_mod_settings(set_dict): #quick and dirsty workaround - older settings files don't include rand, d. if 'RANDOM_DISABLE_CHANCE' not in set_dict.keys(): set_dict['RANDOM_DISABLE_CHANCE'] = RANDOM_DISABLE_CHANCE menu = ConsoleMenu("Tune parameters", "[original value] / <new value>") menu_items = [] for idx, (key, val) in enumerate(set_dict.items()): desc = f"{key}[{val}]" prompt = f"{key}[{val}] : " def prompt_func(text, set_key): value = input(text) if set_key in ['PID_ENABLED', 'COLLISION']: set_dict[set_key] = True if value.startswith( ('T', 't')) else False elif set_key == 'PID_PARAMS': set_dict[set_key] = [ float(x) for x in value.replace(' ', ',').split(',') ] elif isInt(float(value)): set_dict[set_key] = int(value) else: set_dict[set_key] = float(value) return value if key in ['PID_ENABLED', 'COLLISION']: prompt = f"{key}[{val}](F/T) : " if key == 'PID_PARAMS': prompt = "PID <P I D>: " menu_items.append(FunctionItemMod(desc, prompt_func, [prompt, key])) else: menu_items.append(FunctionItemMod(desc, prompt_func, [prompt, key])) menu.append_item(menu_items[idx]) def print_sett(): for key, item in set_dict.items(): print(f"{key} : {item}") input('\nPress any key to return!') menu.append_item(FunctionItem("PRINT CURRENT SETTINGS", print_sett)) menu.show() return set_dict
def manage_emulations(emulations): """ Start/stop/delete an emulation, or view its devices. :param emulations: List of emulations to manage """ prologue_text = "\n".join( ["{} ({})".format(e.name, e.status) for e in emulations]) menu = ConsoleMenu(title="Manage Emulations", prologue_text=prologue_text) menu.append_item( FunctionItem("Start", api.toggle_emulations, args=[emulations, "start"], should_exit=True)) menu.append_item( FunctionItem( "Start w/timer", api.toggle_emulations, args=[emulations, "start", True], should_exit=True, )) menu.append_item( FunctionItem( "Stop", api.toggle_emulations, args=[emulations, "suspend"], should_exit=True, )) menu.append_item( FunctionItem("Delete", api.toggle_emulations, args=[emulations, "stop"], should_exit=True)) # Present this option only when managing a single emulation to enable/disable devices if len(emulations) == 1: menu.append_item( FunctionItem("Show Devices", select_devices, args=[emulations[0].id])) # Present this option to enable/disable multiple devices on multiple emulations else: menu.append_item( FunctionItem( "Multi-Emulation Enable/Disable Devices", manage_devices_across_emulations, args=[emulations], )) menu.show()
def main(): if len(argv) < 2: menu = ConsoleMenu("Mechanism Types", "Choose which mechanism you are characterizing") for mechanism, tools in tool_dict.items(): tool_menu = ConsoleMenu(f"Characterization Tools: {mechanism}") for tool, function in tools.items(): tool_menu.append_item( FunctionItem(tool, function, menu=tool_menu)) menu.append_item(SubmenuItem(mechanism, tool_menu, menu)) menu.show() else: parser = argparse.ArgumentParser( description="FRC characterization tools CLI") parser.add_argument( "mech_type", choices=list(tool_dict.keys()), help="Mechanism type being characterized", ) parser.add_argument( "tool_type", choices=list(list(tool_dict.values())[0].keys()), help= "Create new project, start data recorder/logger, or start data analyzer", ) parser.add_argument( "project_directory", help= "Location for the project directory (if creating a new project)", nargs="?", default=None, ) argcomplete.autocomplete(parser) args = parser.parse_args() tool_dict[args.mech_type][args.tool_type]( directory=args.project_directory)
def build_menu(): global mastermeals # needed to modify mastermeals menu = ConsoleMenu("Meal Planning with Mary!") func_new_meal = FunctionItem("Add a new Meal!", mastermeals.append(new_meal())) func_print_meal = FunctionItem("Print all the meals", )
customer_menu = ConsoleMenu("Customer Menu") order_menu = ConsoleMenu("Order Menu") product_menu = ConsoleMenu("Product Menu") seller_menu = ConsoleMenu("Seller Menu") seller_product = ConsoleMenu("Seller to Product Menu") menus = [ (customer_menu, "Customer"), (order_menu, "Order"), (product_menu, "Product"), (seller_menu, "Seller"), (seller_product, "SellerProduct"), ] for menu, string in menus: menu.append_item(FunctionItem("Find All", find_all, [string])) menu.append_item(FunctionItem("Exact search", find_exact, [string])) menu.append_item(FunctionItem("Like search", find_like, [string])) menu.append_item(FunctionItem("Insert", insert, [string])) menu.append_item(FunctionItem("Delete", delete, [string])) menu.append_item(FunctionItem("Update", update, [string])) menu.append_item(FunctionItem("Generate", generate, [string])) menu.append_item(FunctionItem("Clear", clear, [string])) product_menu.append_item( FunctionItem("Find all sellers", find_exact, ["SellerProduct", "product_id"])) seller_menu.append_item( FunctionItem("Find all products", find_exact, ["SellerProduct", "seller_id"])) for menu, string in menus:
if 'grid' in response: msg = rx_callsign + ' ' + callsign + ' ' + grid elif 'signal' in response: snr = input("Signal strength: ") msg = rx_callsign + ' ' + callsign + ' ' + snr elif 'RR73' in response: msg = rx_callsign + ' ' + callsign + ' RR73' new_msg(msg) #Create the menus menu = ConsoleMenu("WJSTX Transceiver Control ", "FT8 and FT4") resp_submenu = ConsoleMenu("Respond with: ", "", exit_option_text="Go back") #Main menu cq_item = FunctionItem("Call CQ", call_cq, [False]) continue_cq_item = FunctionItem("Continue Call CQ", call_cq, [True]) retransmit_item = FunctionItem("Retransmit last", transmit, []) resp_new_item = FunctionItem("Respond to new callsign", resp_new, []) submenu_item = FunctionItem("Respond to last callsign", resp_last, []) chfreq_item = FunctionItem("Change TX frequency", change_freq, []) chft4_item = FunctionItem("Change mode to FT4", change_mode, []) chft8_item = FunctionItem("Change mode to FT8", change_mode, []) resp_grid_item = FunctionItem("Respond with grid", respond, ['grid']) resp_signal_item = FunctionItem("Respond with R + signal strenght", respond, ['signal']) resp_73_item = FunctionItem("Respond with RR73", respond, ['RR73']) resp_submenu.append_item(resp_grid_item) resp_submenu.append_item(resp_signal_item)
from consolemenu import ConsoleMenu from consolemenu.items import FunctionItem, SubmenuItem, CommandItem menu = ConsoleMenu(title='Menu Title', subtitle='Subtitle') command_item = CommandItem('Run a console command!', 'touch.txt') function_item = FunctionItem('call a function', input, ['enter input']) submenu = ConsoleMenu('a submenu') submenu_item = SubmenuItem('show a submenu', submenu, menu=menu) menu.append_item(command_item) menu.append_item(function_item) menu.append_item(submenu_item) # menu.start() # menu.join() menu.show()
def show_loaded_model_menu(model, net, jtree): # Record which models are in the models folder models_list = [ f for f in listdir(models_path) if isfile(join(models_path, f)) and str(f)[-4:] == ".dat" ] menu = ConsoleMenu("Main menu - " + model) describe_bnet = FunctionItem("Describe Bayesian Net", function=lambda net: print(str(net)), args=[net]) describe_jtree = FunctionItem("Describe Junction Tree", function=lambda jtree: print(str(jtree)), args=[jtree]) visualize = FunctionItem( "Visualize Bayesian Net and Junction Tree", function=lambda path: os.system("visualize.py " + path), args=[models_path + model]) propagate = FunctionItem( "Propagate evidence", function=lambda jtree: [jtree.sum_propagate(), print("Evidence propagated")], args=[jtree]) load_new_model = SelectionMenu(models_list, "Load New Model") load_new_model_item = SubmenuItem("Load a new model", load_new_model, menu=menu, should_exit=True) add_evidence = FunctionItem("Add evidence", function=add_evidence_option, args=[jtree]) get_probability = FunctionItem("Get probability of a variable", function=get_probability_option, args=[jtree]) reset_model = FunctionItem( "Reset Model", function=lambda net, jtree: [jtree.initialize_tables(net), print("Tables reinitialized")], args=[net, jtree]) menu.append_item(describe_bnet) menu.append_item(describe_jtree) menu.append_item(visualize) menu.append_item(add_evidence) menu.append_item(get_probability) menu.append_item(propagate) menu.append_item(reset_model) menu.append_item(load_new_model_item) menu.start() menu.join() if load_new_model.selected_option >= len(models_list): show_loaded_model_menu(model, net, jtree) return elif load_new_model.selected_option == -1: return selected_model = models_list[load_new_model.selected_option] net, jtree = util.load_model(models_path + selected_model) if net is not None and jtree is not None: jtree.initialize_tables(net) print("Model loaded succesfully") show_loaded_model_menu(selected_model, net, jtree) else: show_first_menu()
epilogue_text=lightsheetEpilogue, exit_option_text="Main Menu") lightsheetItem = SubmenuItem("Lightsheet Data", lightsheetMenu, mainMenu) ephysMenu = ConsoleMenu("EPhys Data [Not Implemented]", exit_option_text="Main Menu") ephysItem = SubmenuItem("Ephys Data", ephysMenu, mainMenu) confocalMenu = ConsoleMenu("Confocal Data [Not Implemented]", exit_option_text="Main Menu") confocalItem = SubmenuItem("Confocal Data", confocalMenu, mainMenu) behaviorMenu = ConsoleMenu("Behavior Data [Not Implemented]", exit_option_text="Main Menu") behaviorItem = SubmenuItem("Behavior Data", behaviorMenu, mainMenu) cellCultureMenu = ConsoleMenu("Cell Culture Data [Not Implemented]", exit_option_text="Main Menu") cellCultureItem = SubmenuItem("Cell Culture Data", cellCultureMenu, mainMenu) openScanMenuItem = FunctionItem("Open Scan", select_scan, [], menu=lightsheetMenu) importScanMenuItem = FunctionItem("Import Scan", create_scan, []) mainMenu.append_item(lightsheetItem) mainMenu.append_item(ephysItem) mainMenu.append_item(confocalItem) mainMenu.append_item(behaviorItem) mainMenu.append_item(cellCultureItem) lightsheetMenu.append_item(openScanMenuItem) lightsheetMenu.append_item(importScanMenuItem) mainMenu.show()