def __init__(self) : Backend.__init__(self) self.messages = {} self.contacts = {} # Dummy data self.messages = { 'peter' : [ Message(datetime.datetime(2008, 01, 01), 'peter', 'Reading some XMPP specs'), Message(datetime.datetime(2008, 01, 03), 'peter', '@kevin Tell me about it') ], 'kevin' : [ Message(datetime.datetime(2008, 01, 02), 'kevin', 'Too little time to do all the things I want to') ], 'remko' : [ Message(datetime.datetime(2008, 01, 04), 'remko', 'Woohoow, holidays!') ]} self.contacts = { 'remko' : ['kevin', 'peter'] } self.subscribers = { 'kevin' : ['remko'], 'peter' : ['remko'] } self.jidToUser = { '*****@*****.**' : 'remko', '*****@*****.**' : 'peter', '*****@*****.**' : 'kevin', } self.userToJID = { 'remko' : '*****@*****.**', 'peter' : '*****@*****.**', 'kevin' : '*****@*****.**' } self.userPresenceMonitoring = { 'kevin' : True, 'remko' : False, 'peter' : True, }
def __init__(self): Backend.__init__(self) self.prod_pu_to_kv = None self.load_pu_to_kv = None self.lines_or_pu_to_kv = None self.lines_ex_pu_to_kv = None self.p_or = None self.q_or = None self.v_or = None self.a_or = None self.p_ex = None self.q_ex = None self.v_ex = None self.a_ex = None self._pf_init = "flat" self._pf_init = "results" self._nb_bus_before = 0 self.thermal_limit_a = None self._iref_slack = -1 self._id_bus_added = -1 self._fact_mult_gen = -1 self._subs_to_table = None self._what_object_where = None self._number_true_line = -1 self._corresp_name_fun = {} self._get_vector_inj = {} self._dim_topo = -1 self._vars_action = Action.vars_action self._vars_action_set = Action.vars_action_set
async def test_time_updates(self): self.my_game_lister = ListGames() self.my_game_lister.cache_filepath = self.my_game_lister.cache_filepath + "-test_time_updates" self.my_tasks = [] self.configuration = DefaultConfig() self.backend = Backend() if os.path.exists(self.backend.cache_times_filepath): os.remove(self.backend.cache_times_filepath) self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) my_threads = [] my_thread = Mock() my_thread.is_alive = MagicMock(return_value=False) my_threads.append(my_thread) my_current_time = datetime.now() - timedelta(minutes=1) my_thread.name = "{\"time\":\"" + str( my_current_time) + "\", \"id\":\"12345A\"}" await time_tracking(self, my_threads) #local_time_cache = await self.my_game_lister.read_from_cache_filename(self.backend.cache_times_filepath) self.assertEqual(1, len(self.backend.local_time_cache)) my_timed_entry = self.backend.local_time_cache[0] self.assertGreaterEqual(my_timed_entry["run_time_total"], 1) self.assertEqual(my_timed_entry["last_time_played"], math.floor(my_current_time.timestamp())) self.assertEqual(my_timed_entry["hash_digest"], "12345A") if os.path.exists(self.backend.cache_times_filepath): os.remove(self.backend.cache_times_filepath)
def __init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test=False): """ Creates an instance of the vegas internals. """ # mode_number may be treated as a constant; the Player will # delete this backend object and create a new one on mode # change. Backend.__init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test) # Important to do this as soon as possible, so that status application # can change its data buffer format print "VEGAS finished init for Backend" self.write_status(BACKEND='VEGAS') print "after write_status" # In VEGAS mode, i_am_master means this particular backend # controls the switching signals. (self.bank is from base class.) self.i_am_master = self.bank.i_am_master # the switching signals builder self.ss = SwitchingSignals() # Parameters: self.setPolarization('SELF') self.setNumberChannels(self.mode.nchan) self.requested_integration_time = 1.0 # self.setValonFrequency(self.mode.frequency) # dependent values, computed from Parameters: self.nspectra = 1 self.nsubbands = 1 self.frequency_resolution = 0.0 self.fpga_clock = None self.fits_writer_process = None self.scan_length = 30.0 self.spec_tick = self.computeSpecTick() self.setHwExposr(self.mode.hwexposr) # setup the parameter dictionary/methods self.params["polarization"] = self.setPolarization self.params["nchan"] = self.setNumberChannels self.params["exposure"] = self.setIntegrationTime self.params["hwexposr"] = self.setHwExposr self.params["num_spectra"] = self.setNumberSpectra # the status memory key/value pair dictionary self.sskeys = {} self.ss.set_spec_tick(self.spec_tick) self.ss.set_hwexposr(self.hwexposr) self.fits_writer_program = "vegasFitsWriter"
def __init__(self,host,user=None,password=None,https=False,auth=None): """Initialises the backend host: the hostname to the Exchange server auth: is the authorisation string for basic authorisation (may be specified instead of user/pass) """ Backend.__init__(self) self.conn = SoapConn(host,https=https,user=user,password=password, auth=auth) self.query = SoapQuery(self.conn)
def __init__(self, root, *args, **kwargs): tk.Canvas.__init__(self, *args, width=600, height=600, bg = "white", bd=1, relief='raised') Backend.__init__(self) self.root = root self.tag_bind("Draggable","<ButtonPress-1>",self.onClickPress) self.tag_bind("Draggable","<ButtonPress-2>",self.onRightClick) self.tag_bind("Draggable", "<ButtonRelease-1>",self.onClickRelease) self.tag_bind("Draggable","<B1-Motion>",self.handleMotion) self.tag_bind("Draggable","<Double-Button-1>",self.onDoubleClick) self.textSize = 36 self.equivalenceLines = [] self.guiExpressions = {} self.numbers = {} # currentAction can be None, "Drag", "DragFromEquationVar", "DragFromExp" self.currentAction = None self.currentDragLine = None # self.clickData["variable"] = None # self.dragStartExpressionVar = None # self.clickData["coords"] = None self.clickData = {"clickedObject" : None, # Expression, Equation, etc "variable" : None, # or "EK" or whatever "coords" : None } # This is the menu when you click on a variable in an equation self.eqVarPopup = tk.Menu(root, tearoff=0) self.eqVarPopup.add_command(label="Find expression", command = self.findGUIExpressionRightClick) self.eqVarPopup.add_separator() self.eqVarPopup.add_command(label="Delete equation", command= self.deleteEquation) # This is the menu when you click on something else in an equation self.eqOtherPopup = tk.Menu(root, tearoff=0) self.eqOtherPopup.add_command(label="Delete equation", command= self.deleteEquation) self.font = "Courier New"
def __init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test = False): """ Creates an instance of the vegas internals. """ # mode_number may be treated as a constant; the Player will # delete this backend object and create a new one on mode # change. Backend.__init__(self, theBank, theMode, theRoach , theValon, hpc_macs, unit_test) # Important to do this as soon as possible, so that status application # can change its data buffer format self.write_status(BACKEND='VEGAS') # In VEGAS mode, i_am_master means this particular backend # controls the switching signals. (self.bank is from base class.) self.i_am_master = self.bank.i_am_master # the switching signals builder self.ss = SwitchingSignals() # Parameters: self.setPolarization('SELF') self.setNumberChannels(self.mode.nchan) self.requested_integration_time = 1.0 # self.setValonFrequency(self.mode.frequency) # dependent values, computed from Parameters: self.nspectra = 1 self.nsubbands = 1 self.frequency_resolution = 0.0 self.fpga_clock = None self.fits_writer_process = None self.scan_length = 30.0 self.spec_tick = self.computeSpecTick() self.setHwExposr(self.mode.hwexposr) # setup the parameter dictionary/methods self.params["polarization" ] = self.setPolarization self.params["nchan" ] = self.setNumberChannels self.params["exposure" ] = self.setIntegrationTime self.params["hwexposr" ] = self.setHwExposr self.params["num_spectra" ] = self.setNumberSpectra # the status memory key/value pair dictionary self.sskeys = {} self.ss.set_spec_tick(self.spec_tick) self.ss.set_hwexposr(self.hwexposr) self.fits_writer_program = "vegasFitsWriter"
async def test_start_and_stop_library(self): #loop = asyncio.new_event_loop() #self.my_library_started = False self.keep_ticking = True self.my_tasks = [] self.my_library_started = False self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) logging.debug("starting") self.started_async_tick = True asyncio.get_event_loop() my_task = asyncio.create_task(tick_async(self)) self.my_tasks.append(my_task) self.my_library_thread = threading.Thread(target=library_thread, args=(self, )) self.my_library_thread.daemon = True self.my_library_thread.start() asyncio.get_event_loop() my_task = asyncio.create_task( update_local_games(self, "test_user", self.backend.my_game_lister)) self.my_tasks.append(my_task) #self.assertEqual(True, self.my_library_thread.is_alive()) #self.assertEqual(True, self.my_library_started) self.assertEqual(True, self.backend.library_run) await shutdown_library(self) await shutdown_tasks(self, self.my_tasks) #self.assertEqual(False, self.my_library_thread.is_alive()) self.assertEqual(False, self.backend.library_run)
async def test_added_backend(self): self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) systems = await setup_folders_for_testing(self, "TestDirectory11") insert_file_into_folder(self, systems, "gbc0", "mygame.gb", "") insert_file_into_folder(self, systems, "gbc0", "game.gb", "") insert_file_into_folder(self, systems, "dos0", "game.exe", "mygame") new_local = await systems.list_all_recursively("test_user") for entry in new_local: logging.debug("Check") if ("local_game_state" not in entry): logging.debug("should") entry["local_game_state"] = LocalGameState.Installed myresult = await get_state_changes([], new_local) await added_games(self, new_local, myresult["old"], myresult["new"]) self.assertEqual( 3, self.backend.my_queue_update_local_game_status._qsize()) game_update_from_queue = self.backend.my_queue_update_local_game_status.get( ) self.assertEqual(game_update_from_queue.local_game_state, LocalGameState.Installed) self.assertEqual(3, self.backend.my_queue_add_game._qsize())
def load_config(self): is_init_last = self.is_init self.is_init = False # make sure update_mix doesn't fail when the config is cleared out self.be = Backend(self.config_file) selected_recipe = self.ui.recipe_box.currentText() self.populate_recipe_box(selected_recipe) self.is_init = is_init_last self.update_mix()
async def test_launch_thread(self): self.my_game_lister = ListGames() self.local_game_cache = await self.my_game_lister.list_all_recursively( "test_user") self.my_authenticated = "test_user" self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) self.my_threads = []
def add_header(): c = Backend(self.game_size, self.game_diff) c.generate_header() self.answer_board = c.my_matrix j = self.canvas_row[0] h = self.canvas_col[0] for i in range(self.game_size): label1 = Label(master, text=c.row_header[i], bg='pink') label1.grid(row=j, column=self.canvas_col[0] - 1) label2 = Label(master, text=c.column_header[i], bg='pink', anchor=N) label2.grid(row=self.canvas_row[0] - 1, column=h) self.header_list.append(label1) self.header_list.append(label2) j += 1 h += 1
def __init__(self, detailed_infos_for_cascading_failures=False): Backend.__init__(self, detailed_infos_for_cascading_failures= detailed_infos_for_cascading_failures) self.prod_pu_to_kv = None self.load_pu_to_kv = None self.lines_or_pu_to_kv = None self.lines_ex_pu_to_kv = None self.p_or = None self.q_or = None self.v_or = None self.a_or = None self.p_ex = None self.q_ex = None self.v_ex = None self.a_ex = None self.load_p = None self.load_q = None self.load_v = None self.prod_p = None self.prod_q = None self.prod_v = None self._pf_init = "flat" self._pf_init = "results" self._nb_bus_before = 0 self.thermal_limit_a = None self._iref_slack = None self._id_bus_added = None self._fact_mult_gen = -1 self._what_object_where = None self._number_true_line = -1 self._corresp_name_fun = {} self._get_vector_inj = {} self.dim_topo = -1 self._vars_action = Action.vars_action self._vars_action_set = Action.vars_action_set
def _getSettings(self): self.backend = Backend(self) # Load Styling CSS = self.backend.info.data['Player']['style'] with open( os.path.join('resources','css',CSS + '.css'), 'r') as f: self.setStyleSheet( f.read() ) # Get version with open("VERSION.txt",'r') as f: self.version = f.read()
def __init__(self, reader, writer, token): self.configuration = DefaultConfig() super().__init__( Platform(self.configuration.my_platform_to_gog ), # choose platform from available list "0.1", # version reader, writer, token) self.backend = Backend() self.my_library_thread = None self.my_library_started = False self.my_threads = [] self.my_tasks = [] self.started_async_tick = False self.keep_ticking = True if (self.configuration.minimize_logging): logging.getLogger().setLevel(logging.WARNING) else: logging.getLogger().setLevel(logging.DEBUG)
def __init__(self): Backend.__init__(self) self.messages = {} self.contacts = {} # Dummy data self.messages = { 'peter': [ Message(datetime.datetime(2008, 01, 01), 'peter', 'Reading some XMPP specs'), Message(datetime.datetime(2008, 01, 03), 'peter', '@kevin Tell me about it') ], 'kevin': [ Message(datetime.datetime(2008, 01, 02), 'kevin', 'Too little time to do all the things I want to') ], 'remko': [ Message(datetime.datetime(2008, 01, 04), 'remko', 'Woohoow, holidays!') ] } self.contacts = {'remko': ['kevin', 'peter']} self.subscribers = {'kevin': ['remko'], 'peter': ['remko']} self.jidToUser = { '*****@*****.**': 'remko', '*****@*****.**': 'peter', '*****@*****.**': 'kevin', } self.userToJID = { 'remko': '*****@*****.**', 'peter': '*****@*****.**', 'kevin': '*****@*****.**' } self.userPresenceMonitoring = { 'kevin': True, 'remko': False, 'peter': True, }
async def test_do_auth(self): self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) self.store_credentials = Mock(return_value=None) authenticated_user = await do_auth(self, "test_user") self.assertEqual(Authentication('importer_user', "test_user"), authenticated_user) self.assertEqual(self.backend.my_authenticated, True) user_data = {} user_data['username'] = "******" self.store_credentials.assert_called_with(user_data)
def __init__(self): self.__lock = threading.Lock() self.__db_file = self.__find_db() self.__db = Backend(self.__db_file) if (os.path.basename(self.__db_file).startswith("states")): self.__db.set_file(self.__CONFIG_FILE) self.__dirty = False # flush the cache every 5 seconds import gobject gobject.timeout_add(5 * 1000, self.__flush)
async def test_prepare_to_send_my_updates(self): self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) systems = await setup_folders_for_testing(self, "TestDirectory3") insert_file_into_folder(self, systems, "gbc0", "mygame.gb", "") insert_file_into_folder(self, systems, "gbc0", "game.gb", "") insert_file_into_folder(self, systems, "dos0", "game.exe", "mygame") new_local = await systems.list_all_recursively("test_user") for entry in new_local: logging.debug("Check") if ("local_game_state" not in entry): logging.debug("should") entry["local_game_state"] = LocalGameState.Installed await prepare_to_send_my_updates(self, new_local, [])
async def test_created_time_update(self): self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) systems = await setup_folders_for_testing(self, "TestDirectory8") insert_file_into_folder(self, systems, "gbc0", "mygame.gb", "") new_local = await systems.list_all_recursively("test_user") my_time = datetime.now() for entry in new_local: logging.debug("Check") if ("local_game_state" not in entry): logging.debug("should") entry["local_game_state"] = LocalGameState.Installed updated_Time = await created_update(new_local[0], 1, my_time) #New self.assertEqual(math.floor(my_time.timestamp()), updated_Time["last_time_played"]) self.assertEqual(1, updated_Time["run_time_total"]) updated_Time = await created_update(updated_Time, 1, my_time) #Updated self.assertEqual(math.floor(my_time.timestamp()), updated_Time["last_time_played"]) self.assertEqual(2, updated_Time["run_time_total"])
async def test_changed_backend(self): self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) systems = await setup_folders_for_testing(self, "TestDirectory12") insert_file_into_folder(self, systems, "gbc0", "mygame.gb", "") insert_file_into_folder(self, systems, "gbc0", "game.gb", "") insert_file_into_folder(self, systems, "dos0", "game.exe", "mygame") new_local = await systems.list_all_recursively("test_user") for entry in new_local: logging.debug("Check") if ("local_game_state" not in entry): logging.debug("should") entry["local_game_state"] = LocalGameState.Installed myresult = await get_state_changes(new_local, new_local) myresult["old"][list( myresult["old"].keys())[0]] = LocalGameState.Running await state_changed(self, myresult["old"], myresult["new"]) self.assertEqual( False, self.backend.my_queue_update_local_game_status.empty()) self.assertEqual( 1, self.backend.my_queue_update_local_game_status._qsize())
game_gui.clear_screen() game_gui.draw_game_end(self.message) temp = game_backend.process_game_end() if temp != 4: self.cur_state = temp if temp != -1: game_sounds.backwards() game_sounds.stop_game_music() return None pygame.display.update() if __name__ == "__main__": # create elementary game objects game_controller = MainController(0) game_gui = GUI() game_backend = Backend() game_sounds = Sounds() # main loop for main controller while game_controller.cur_state != -1: if game_controller.cur_state == 0: game_controller.game_menu() elif game_controller.cur_state == 1: game_controller.game_play() elif game_controller.cur_state == 2: game_controller.game_instructions() elif game_controller.cur_state == 3: game_controller.game_credits() elif game_controller.cur_state == 4: game_controller.game_end()
def __init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test=False): """ Creates an instance of the class. """ # Only one HPC Player will be controlling a roach in the CODD # mode family. Therefore figure out if we are the one; if not, # set the parameters 'theRoach' and 'theValon' to None, even if # this HPC does control a roach in other modes. if theMode.cdd_master_hpc == theBank.name: Backend.__init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test) self.progdev() self.net_config() if self.mode.roach_kvpairs: self.write_registers(**self.mode.roach_kvpairs) self.reset_roach() else: Backend.__init__(self, theBank, theMode, None, None, None, unit_test) # This needs to happen on construction so that status monitors can # change their data buffer format. self.set_status(BACKEND="GUPPI") # The default switching in the Backend ctor is a static SIG, NOCAL, and no blanking self.max_databuf_size = 128 # in MBytes self.scale_p0 = 1.0 self.scale_p1 = 1.0 self.only_i = 0 self.bandwidth = self.frequency self.dm = 0.0 self.rf_frequency = 1430.0 self.overlap = 0 self.tfold = 1.0 self.nbin = 256 # Most all receivers are dual polarization self.nrcvr = 2 self.nchan = self.mode.nchan # total number of channels in the design, not per node self.num_nodes = 8 self.feed_polarization = "LIN" self.obs_mode = "COHERENT_SEARCH" bank_names = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7} self.node_number = bank_names[self.bank.name[-1]] self.integration_time = 40.96e-6 self.scan_length = 30.0 if self.dibas_dir is not None: self.pardir = self.dibas_dir + "/etc/config" else: self.pardir = "/tmp" self.parfile = "example.par" self.datadir = "/lustre/gbtdata/JUNK" # Needs integration with projectid # register set methods # self.params["bandwidth" ] = self.set_bandwidth self.params["dm"] = self.set_dm self.params["integration_time"] = self.set_integration_time self.params["nbin"] = self.set_nbin self.params["num_channels"] = self.set_nchannels self.params["obs_frequency"] = self.set_obs_frequency self.params["obs_mode"] = self.set_obs_mode self.params["par_file"] = self.set_par_file self.params["scale_p0"] = self.set_scale_P0 self.params["scale_p1"] = self.set_scale_P1 self.params["tfold"] = self.set_tfold self.params["only_i"] = self.set_only_i self.params["feed_polarization"] = self.setFeedPolarization self.params["_node_number"] = self.setNodeNumber # Fill-in defaults if they exist if "OBS_MODE" in self.mode.shmkvpairs.keys(): self.set_param("obs_mode", self.mode.shmkvpairs["OBS_MODE"]) if "ONLY_I" in self.mode.shmkvpairs.keys(): self.set_param("only_i", int(self.mode.shmkvpairs["ONLY_I"])) if "SCALE_P0" in self.mode.roach_kvpairs.keys(): self.set_param("scale_p0", float(self.mode.roach_kvpairs["SCALE_P0"])) if "SCALE_P1" in self.mode.roach_kvpairs.keys(): self.set_param("scale_p1", float(self.mode.roach_kvpairs["SCALE_P1"])) if self.hpc_process is None: self.start_hpc() if self.cdd_master(): self.arm_roach()
async def generatePage(self): self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) logger.info("Loading data:") systems = ListGames() data_read = await systems.read_from_cache() if (len(data_read) > 0): outputFile = open("cache.html", "w") outputFile.write( str("<html>\n\ <head>\n\ <meta charset='UTF-8'>\n\ <title>Cache</title>\n\ \n\ <style>\n\ .axes {\n\ padding: 1em;\n\ }\n\ \n\ .buttons {\n\ margin-left: 1em;\n\ }\n\ \n\ /*meter*/.axis {\n\ min-width: 200px;\n\ margin: 1em;\n\ }\n\ \n\ .button {\n\ display: inline-block;\n\ width: 1em;\n\ text-align: center;\n\ padding: 1em;\n\ border-radius: 20px;\n\ border: 1px solid black;\n\ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAAxJREFUCNdjYPjPAAACAgEAqiqeJwAAAABJRU5ErkJggg==);\n\ background-size: 0% 0%;\n\ background-position: 50% 50%;\n\ background-repeat: no-repeat;\n\ }\n\ \n\ .pressed {\n\ border: 1px solid red;\n\ }\n\ \n\ .touched::after {\n\ content: 'touch';\n\ display: block;\n\ position: absolute;\n\ margin-top: -0.2em;\n\ margin-left: -0.5em;\n\ font-size: 0.8em;\n\ opacity: 0.7;\n\ }\n\ </style>\n\ </head>\n\ <body>\n\ <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>\n\ <link rel='stylesheet' type='text/css' href='https://cdn.datatables.net/1.11.0/css/jquery.dataTables.css'>\n\ <script type='text/javascript' charset='utf8' src='https://cdn.datatables.net/1.11.0/js/jquery.dataTables.js'></script>\n\ <script type='text/javascript' charset='utf8' src='https://cdn.datatables.net/select/1.3.3/js/dataTables.select.js'></script>\n\ <link rel='stylesheet' type='text/css' href='https://cdn.datatables.net/select/1.3.3/css/select.dataTables.css'>\n\ <script>\n\ function myOpenGalaxyFunction() {\n\ window.open('goggalaxy://openGameView/test_'+$('#mytable').DataTable().row({ selected: true }).data()[11],'_self');\n\ }\n\ </script>\n\ \n\ <script>\n\ function myTableUpdatesFunction(){\n\ //Update table changes of stuff\n\ //if (controllers[0].axes[0].toFixed(4)==1)//right\n\ if (controllers!=null && controllers[0]!=undefined && myStartTime +175 < Date.now()) {\n\ if (controllers[0].axes[1].toFixed(4)==1)//down\n\ {\n\ var nextval = $('#mytable').DataTable().row({ selected: true }).next();\n\ if (null!= nextval){\n\ nextval.select()\n\ var myNodeLocation = $('#mytable').DataTable().rows({order: 'current'}).nodes().indexOf($('#mytable').DataTable().row({ selected: true }).node());\n\ var myPage = Math.floor(myNodeLocation/$('#mytable').DataTable().page.len());\n\ $('#mytable').DataTable().page(myPage).draw(false);\n\ //$('#mytable').DataTable().page( 'next' ).draw( 'page' );\n\ myStartTime = Date.now();\n\ }\n\ }\n\ if (controllers[0].axes[1].toFixed(4)==-1)//up\n\ {\n\ var prevval = $('#mytable').DataTable().row({ selected: true }).prev()\n\ if (null!= prevval){\n\ prevval.select()\n\ var myNodeLocation = $('#mytable').DataTable().rows({order: 'current'}).nodes().indexOf($('#mytable').DataTable().row({ selected: true }).node());\n\ var myPage = Math.floor(myNodeLocation/$('#mytable').DataTable().page.len());\n\ $('#mytable').DataTable().page(myPage).draw(false);\n\ //$('#mytable').DataTable().page( 'previous' ).draw( 'page' );\n\ myStartTime = Date.now();\n\ }\n\ }\n\ //Copy to clipboard (x)\n\ if (controllers[0].buttons[2].touched)\n\ {\n\ navigator.clipboard.writeText($('#mytable').DataTable().row({ selected: true }).data()[17]);\n\ myStartTime = Date.now();\n\ }\n\ \n\ //Open in galaxy (a)\n\ if (controllers[0].buttons[0].touched)\n\ {\n\ //If this doesn't provide the open dialogue you need to click on the page with the mouse again\n\ myOpenGalaxyFunction();\n\ myStartTime = Date.now();\n\ }\n\ //alert command to open galaxy page (y)\n\ if (controllers[0].buttons[3].touched)\n\ {\n\ alert('goggalaxy://openGameView/test_'+$('#mytable').DataTable().row({ selected: true }).data()[11]);\n\ myStartTime = Date.now();\n\ }\n\ \n\ }\n\ }\n\ </script>\n\ \n\ <button onclick='myOpenGalaxyFunction()' id ='openGalaxyButton'>Open selected in galaxy</button>\n\ \n\ <table id='mytable' class='display'>\n")) outputFile.write(str("<thead>\n<tr>\n")) for headerKey in data_read[0]: outputFile.write(str("<th>" + str(headerKey) + "</th>\n")) # Have it a second time for without the link if (headerKey == "hash_digest"): outputFile.write(str("<th>" + str(headerKey) + "</th>\n")) outputFile.write(str("<th>derived execution</th>\n")) outputFile.write(str("</tr>\n</thead>\n<tbody>\n")) for entry in data_read: logger.info(entry) outputFile.write(str("<tr>")) myHashId = "" for key in entry: if (key == "hash_digest"): outputFile.write( str("<td><a href='https://gamesdb.gog.com/platforms/test/external_releases/" + str(entry[key]) + "'>" + str(entry[key]) + "</td>")) myHashId = entry[key] outputFile.write(str("<td>" + str(entry[key]) + "</td>")) outputFile.write(str("<td>")) if (myHashId != ""): #logger.info(myHashId) myCommand = await get_exe_command(myHashId, data_read) #logger.info(myCommand) outputFile.write(str(myCommand)[1:-1]) outputFile.write(str("</td>")) outputFile.write(str("</tr>")) outputFile.write( str("</tbody>\n\ </table>\n\ <h2 id='start'>Press a button on your controller to show</h2>\n\ <script type='text/javascript'>\n\ $(document).ready( \n\ function () {\n\ var myDataTable = $('#mytable').DataTable(\n\ {\n\ select: {style: 'single'},\n\ columnDefs: [\n\ {visible: false, targets: [11] }\n\ ]\n\ }\n\ );\n\ }\n\ );\n\ </script>\n\ <script type='text/javascript'>\n\ $.fn.dataTable.Api.register('row().next()', function() {\n\ // Current row position\n\ var nrp = this.table().rows()[0].indexOf( this.index() ) + 1;\n\ // Exists ?\n\ if( nrp < 0 ) {\n\ return null;\n\ }\n\ // Next row index by position\n\ var nri = this.table().rows()[0][ nrp ];\n\ // Return next row by its index\n\ return this.table().row( nri );\n\ });\n\ $.fn.dataTable.Api.register('row().prev()', function() {\n\ // Next row position\n\ var prp = this.table().rows()[0].indexOf( this.index() ) - 1;\n\ // Exists ?\n\ if( prp < 0 ) {\n\ return null;\n\ }\n\ // Previous row index by position\n\ var pri = ( this.table().rows()[0][ prp ] );\n\ // Return previous row by its index\n\ return this.table().row( pri );\n\ });\n\ \ </script>\n\ <script type='text/javascript'>\n\ var haveEvents = 'GamepadEvent' in window;\n\ var haveWebkitEvents = 'WebKitGamepadEvent' in window;\n\ var controllers = {};\n\ var prevTimestamps = [];\n\ var rAF = window.mozRequestAnimationFrame ||\n\ window.webkitRequestAnimationFrame ||\n\ window.requestAnimationFrame;\n\ \n\ function connecthandler(e) {\n\ addgamepad(e.gamepad);\n\ }\n\ function addgamepad(gamepad) {\n\ controllers[gamepad.index] = gamepad;\n\ var d = document.createElement('div');\n\ d.setAttribute('id', 'controller' + gamepad.index);\n\ var t = document.createElement('h1');\n\ t.appendChild(document.createTextNode('gamepad: ' + gamepad.id));\n\ d.appendChild(t);\n\ var b = document.createElement('div');\n\ b.className = 'buttons';\n\ for (var i=0; i<gamepad.buttons.length; i++) {\n\ var e = document.createElement('span');\n\ e.className = 'button';\n\ //e.id = 'b' + i;\n\ e.innerHTML = i;\n\ b.appendChild(e);\n\ }\n\ d.appendChild(b);\n\ var a = document.createElement('div');\n\ a.className = 'axes';\n\ for (i=0; i<gamepad.axes.length; i++) {\n\ e = document.createElement('meter');\n\ e.className = 'axis';\n\ //e.id = 'a' + i;\n\ e.setAttribute('min', '-1');\n\ e.setAttribute('max', '1');\n\ e.setAttribute('value', '0');\n\ e.innerHTML = i;\n\ a.appendChild(e);\n\ }\n\ d.appendChild(a);\n\ document.getElementById('start').style.display = 'none';\n\ document.body.appendChild(d);\n\ rAF(updateStatus);\n\ }\n\ \n\ function disconnecthandler(e) {\n\ removegamepad(e.gamepad);\n\ }\n\ \n\ function removegamepad(gamepad) {\n\ var d = document.getElementById('controller' + gamepad.index);\n\ document.body.removeChild(d);\n\ delete controllers[gamepad.index];\n\ }\n\ \n\ function updateStatus() {\n\ \ scangamepads();\n\ for (j in controllers) {\n\ var controller = controllers[j];\n\ var d = document.getElementById('controller' + j);\n\ var buttons = d.getElementsByClassName('button');\n\ for (var i=0; i<controller.buttons.length; i++) {\n\ var b = buttons[i];\n\ var val = controller.buttons[i];\n\ var pressed = val == 1.0;\n\ var touched = false;\n\ if (typeof(val) == 'object') {\n\ pressed = val.pressed;\n\ if ('touched' in val) {\n\ touched = val.touched;\n\ }\n\ val = val.value;\n\ }\n\ var pct = Math.round(val * 100) + '%';\n\ b.style.backgroundSize = pct + ' ' + pct;\n\ b.className = 'button';\n\ if (pressed) {\n\ b.className += ' pressed';\n\ }\n\ if (touched) {\n\ b.className += ' touched';\n\ }\n\ }\n\ \n\ var axes = d.getElementsByClassName('axis');\n\ for (var i=0; i<controller.axes.length; i++) {\n\ var a = axes[i];\n\ a.innerHTML = i + ': ' + controller.axes[i].toFixed(4);\n\ a.setAttribute('value', controller.axes[i]);\n\ }\n\ }\n\ rAF(updateStatus);\n\ }\n\ \n\ function scangamepads() {\n\ var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);\n\ for (var i = 0; i < gamepads.length; i++) {\n\ if (gamepads[i] && (gamepads[i].index in controllers)) {\n\ controllers[gamepads[i].index] = gamepads[i];\n\ }\n\ }\n\ if (gamepads[0]){\n\ if(!( gamepads[0].timestamp && \n\ (gamepads[0].timestamp === prevTimestamps[i]))) {\n\ prevTimestamps[0] = gamepads[0].timestamp;\n\ myTableUpdatesFunction();\n\ }\n\ }\n\ }\n\ \n\ var myStartTime = Date.now();\n\ if (haveEvents) {\n\ window.addEventListener('gamepadconnected', connecthandler);\n\ window.addEventListener('gamepaddisconnected', disconnecthandler);\n\ } else if (haveWebkitEvents) {\n\ window.addEventListener('webkitgamepadconnected', connecthandler);\n\ window.addEventListener('webkitgamepaddisconnected', disconnecthandler);\n\ } else {\n\ setInterval(scangamepads, 500);\n\ }\n\ </script>\n\ </body>\n\ </html>"))
class StateSaverServer(object): """ This class provides a singleton server object for saving program state in a database. The path of the database file contains random elements in order to not be attackable by "known-location attacks". """ __STATES_FILE = os.path.join(REGISTRY_PATH, "states" + hex(random.randrange(0xffffffL, 0xffffffffL)) + ".db") __CONFIG_FILE = os.path.join(REGISTRY_PATH, "config" + hex(random.randrange(0xffffffL, 0xffffffffL)) + ".db") __SEPARATOR = ' ' def __init__(self): self.__lock = threading.Lock() self.__db_file = self.__find_db() self.__db = Backend(self.__db_file) if (os.path.basename(self.__db_file).startswith("states")): self.__db.set_file(self.__CONFIG_FILE) self.__dirty = False # flush the cache every 5 seconds import gobject gobject.timeout_add(5 * 1000, self.__flush) def __flush(self): if (self.__dirty): self.__db.sync() self.__dirty = False return True def __find_db(self): files = os.listdir(REGISTRY_PATH) legacy_dbs = [ f for f in files if f.startswith("states") ] dbs = [ f for f in files if f.startswith("config") ] if (dbs): pos = dbs[-1].find(".db") return os.path.join(REGISTRY_PATH, dbs[-1][0:pos+3]) elif (legacy_dbs): pos = legacy_dbs[-1].find(".db") return os.path.join(REGISTRY_PATH, legacy_dbs[-1][0:pos+3]) else: return self.__CONFIG_FILE def __check_key(self, key): assert key assert key[0] not in string.digits for c in key: assert c in (string.ascii_letters + string.digits + '-_.[]') def set_key(self, ident, key, value): self.__check_key(key) self.__lock.acquire() try: pk = ident + self.__SEPARATOR + key self.__db[pk] = value self.__dirty = True finally: self.__lock.release() def get_key(self, ident, key, default): self.__check_key(key) self.__lock.acquire() try: pk = ident + self.__SEPARATOR + key return self.__db.get(pk, default) finally: self.__lock.release() def remove(self, ident): self.__lock.acquire() try: self.__dirty = True for k in self.__db.keys(): if k.startswith(ident + self.__SEPARATOR): del self.__db[k] finally: self.__lock.release() def list(self, ident): self.__db.sync() return [k[len(ident) + 1:] for k in self.__db.keys() \ if k.startswith(ident + self.__SEPARATOR)]
class PyRadio(QWidget): status = Signal(str) def __init__(self): super(PyRadio, self).__init__() self.initUI() # ~ Initialize services without making GUI hang self.s_delay = StartDelay() self.connect(self.s_delay, SIGNAL("start_app()"), self.initStart) def _createBottom(self): self.layout.addStretch(1) bottom_layout = QHBoxLayout() # Set Status Label self.status_bar = StatusLabel() self.status.connect(self.updateStatus) bottom_layout.addWidget(self.status_bar) # Set Version Label bottom_layout.addStretch(1) bottom_layout.addWidget(VersionLabel("version: "+self.version)) self.layout.addLayout(bottom_layout) def initUI(self): self.resize( WIDTH, HEIGHT ) self.setMaximumWidth( WIDTH ) self.setMaximumHeight( HEIGHT ) self.setMinimumWidth( WIDTH ) self.setMinimumHeight( HEIGHT ) self.setWindowTitle("PyRadio") self.layout = QVBoxLayout() self.setLayout(self.layout) self._getSettings() self._createWindows() self._createBottom() # Get application global app self.app = app # Handle Close event self.connect(self, SIGNAL('triggered()'), self.closeEvent) def closeEvent(self, event): # save all data self.backend.info.commit() self.backend.stop() # delete resources del self.mainwin del self.viewscene del self.backend del self.optscene self.destroy() self.app.quit() def _getSettings(self): self.backend = Backend(self) # Load Styling CSS = self.backend.info.data['Player']['style'] with open( os.path.join('resources','css',CSS + '.css'), 'r') as f: self.setStyleSheet( f.read() ) # Get version with open("VERSION.txt",'r') as f: self.version = f.read() def _createWindows(self): # Create Windows self.mainwin = MainWindow(self) self.viewscene = ViewScene(self) self.optscene = OptionScene(self) # For organization self.views = [self.mainwin, self.viewscene, self.optscene] self.createNavigationBar() # Display home screen first for frame in self.views: if frame == self.mainwin: frame.show() else: frame.hide() # allow windows to communicate with backend frame.setBackend(self.backend) self.layout.addWidget(frame) def createNavigationBar(self): self.nav_bar = NavigationBar() self.home_icon = ImageButton() self.list_icon = ImageButton() self.conf_icon = ImageButton() self.git_icon = ImageButton() self.home_icon.setImage('resources/pictures/home.png',[44,44],False) self.list_icon.setImage('resources/pictures/listing.png',[36,36]) self.conf_icon.setImage('resources/pictures/settings.png',[36,36]) self.git_icon.setImage('resources/pictures/github.png',[36,36]) self.home_icon.setReturnString('home') self.list_icon.setReturnString('list') self.conf_icon.setReturnString('conf') self.home_icon.clicked.connect(self.changeWindow) self.list_icon.clicked.connect(self.changeWindow) self.conf_icon.clicked.connect(self.changeWindow) self.git_icon.clicked.connect(self.visit_github) self.nav_bar.addWidget(self.home_icon) self.nav_bar.addWidget(self.list_icon) self.nav_bar.addWidget(self.conf_icon) self.nav_bar.addStretch(1) self.nav_bar.addWidget(self.git_icon) self.layout.addLayout(self.nav_bar) ### Actions ### def changeWindow(self, win=None): # Window Switcher if win == "home": self.mainwin.show() self.viewscene.hide() self.optscene.hide() elif win == "list": self.mainwin.hide() self.viewscene.show() self.optscene.hide() else: self.mainwin.hide() self.viewscene.hide() self.optscene.show() def visit_github(self, *args): # Cross-platform URL Opener link = "https://github.com/king1600/PyRadio" if 'nt' in os.name: cmd = "start " + link else: cmd = "xdg-open " + link subprocess.call(cmd,shell=True) def updateStatus(self, message): # Custom QStatus msg = str(message) self.status_bar.setText(msg) def initStart(self): # start a daemon Thread t = threading.Thread(target=self._Start) t.daemon = True t.start() def _Start(self): # Seperate thread to start services self.backend.initServices() # wait for GStreamer to init while not self.backend.done: time.sleep(0.1) self.viewscene.initFetcher() ''' Not needed ''' # Wait for list to be scanned #while not self.viewscene.done: # time.sleep(0.1) time.sleep(0.5) # start playing music self.mainwin.startStream() self.status.emit("Ready!")
def rewriteUsingExpression(self,var,varToRemove,varToUse): Backend.rewriteUsingExpression(self,var,varToRemove,varToUse) self.guiExpressions[var].draw()
def __init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test = False): """ Creates an instance of the vegas internals. GuppiBackend( bank ) Where bank is the instance of the player's Bank. """ Backend.__init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test) # This needs to happen on construct so that status monitors can # switch their data buffer format self.progdev() self.net_config() if self.mode.roach_kvpairs: self.write_registers(**self.mode.roach_kvpairs) self.reset_roach() self.write_status(BACKEND="GUPPI") # The default switching in the Backend ctor is a static SIG, NOCAL, and no blanking # defaults self.max_databuf_size = 128 # in MBytes [Not sure where this ties in. Value from the manager] self.obs_mode = 'SEARCH' """Parameter 'obs_mode': GUPPI observation mode""" self.nchan = self.mode.nchan """Parameter 'nchan': Number of channels""" self.integration_time = 40.96E-6 """Parameter 'integration_time': Lenght of integration, in seconds.""" self.overlap = 0 self.scale_i = 1 self.scale_q = 1 self.scale_u = 1 self.scale_v = 1 self.offset_i = 0 self.offset_q = 0 self.offset_u = 0 self.offset_v = 0 self.only_i = 0 self.chan_dm = 0.0 self.rf_frequency = 2000.0 self.nbin = 256 self.tfold = 1.0 self.dm = 0.0 # Almost all receivers are dual polarization self.nrcvr = 2 self.feed_polarization = 'LIN' self.bandwidth = self.frequency if self.dibas_dir is not None: self.pardir = self.dibas_dir + '/etc/config' else: self.pardir = '/tmp' self.parfile = 'example.par' # self.params["bandwidth" ] = self.set_bandwidth self.params["integration_time" ] = self.set_integration_time self.params["nbin" ] = self.set_nbin self.params["obs_frequency" ] = self.set_obs_frequency self.params["obs_mode" ] = self.set_obs_mode self.params["only_i" ] = self.set_only_i self.params["scale" ] = self.set_scale self.params["scale_i" ] = self.set_scale_I self.params["scale_q" ] = self.set_scale_Q self.params["scale_u" ] = self.set_scale_U self.params["scale_v" ] = self.set_scale_V self.params["tfold" ] = self.set_tfold self.params["feed_polarization" ] = self.setFeedPolarization self.params["par_file" ] = self.set_par_file self._fft_params_dep() if self.hpc_process is None: self.start_hpc() self.arm_roach()
from Backend import Backend import mysql_setup.coronavirus as coronavirus import mysql_setup.coronavirus_location as coronavirus_location import datetime if __name__ == "__main__": backend = Backend() backend.start_connection() # backend.update_coronavirus_data() # cube = backend.get_cube(coronavirus.table_name,1) # cube.show() # location_cube = backend.get_cube(coronavirus_location.table_name,1) # location_cube.show() # cube.push("date") # joined = cube.join(location_cube) # joined.show() # joined.show() # corona_joined = backend.get_cube("corona_joined") # corona_joined.show() # cube = cube.push("date") # cube.show() # cube = cube.push("country_region") # cube.show() # cube = cube.pull("date") # cube.show() # predicate_func = lambda x:x=="Washington" # cube = cube.restriction("province_state", predicate_func) # cube.show() # cube = cube.destroy("date") # cube.show() # cube = cube.destroy("province_state")
def rewriteUsingEquation(self,var,varToRemove,equation): Backend.rewriteUsingEquation(self,var,varToRemove,equation) self.guiExpressions[var].draw()
class YaccMain(QtGui.QMainWindow): def __init__(self, parent=None): self.is_init = False QtGui.QWidget.__init__(self, parent) self.ui = Ui_yacc_main_window() self.ui.setupUi(self) # extra UI setup: cross-platform monospace font mfont = self.get_monospace_font() self.ui.output_box.setFont(mfont) # set up backend and load recipes self.config_file = CONFIG_FILE self.load_config() # Fill in UI defaults self.ui.totalvol_box.setText('10') self.ui.nic_box.setText('3') self.ui.vg_box.setText('70') # add combo box options self.ui.mix_box.addItem('Juice from Ingredients', 'from_ingredients') self.ui.mix_box.addItem('Juice from Concentrate', 'from_concentrate') self.ui.mix_box.addItem('Concentrate', 'concentrate') # status bar self.status_config_message_label = QtGui.QLabel() self.ui.status_bar.addPermanentWidget(self.status_config_message_label) # recipe editor self.recipe_editor = None # saved values of nic/vg for switching in and out of concentrate mode self.save_nic = None self.save_vg = None # signals/slots self.ui.actionExit.triggered.connect(self.exit) self.ui.update_button.clicked.connect(self.update_mix) self.ui.recipe_box.currentIndexChanged.connect(self.update_mix) self.ui.recipe_box.currentIndexChanged.connect(self.update_recipe_status) self.ui.mix_box.currentIndexChanged.connect(self.handle_mixtype_change) self.ui.totalvol_box.textChanged.connect(self.update_mix) self.ui.nic_box.textChanged.connect(self.update_mix) self.ui.vg_box.textChanged.connect(self.update_mix) self.ui.reload_button.clicked.connect(self.load_config) self.ui.redit_button.clicked.connect(self.launch_redit) self.ui.actionAdd_Recipes.triggered.connect(self.launch_redit) self.is_init = True self.update_mix_type() self.update_mix() self.update_config_status() self.update_recipe_status() def get_monospace_font(self): preferred_fonts_windows = ['Courier New', 'Lucida Console'] preferred_fonts_linux = ['Noto Mono', 'Monospace'] if 'Windows' in platform.system(): pfonts = preferred_fonts_windows else: pfonts = preferred_fonts_linux for fontname in pfonts: font = QFont(fontname) font.setPointSize(12) info = QFontInfo(font) if info.fixedPitch(): return font print('Warning: no font in preferred list %s found!'%pfonts) font = QFont() font.setStyleHint(QFont.Monospace) info = QFontInfo(font) print('Selected font family: %s'%info.family()) def update_mix(self): if not self.is_init: return mix_inputs = self.check_inputs() if mix_inputs is None: return mix = self.be.calculate_mix(**mix_inputs) if mix is None: # calculate_mix returns None if the recipe can't be found, so just bail # This shouldn't really happen since recipe_box is only populated by items that # backend.get_recipes returns mix = 'Backend Error!' self.ui.output_box.setPlainText(mix) def update_mix_type(self): if not self.is_init: return mix_type = self.ui.mix_box.itemData(self.ui.mix_box.currentIndex()) if mix_type == 'concentrate': # making concentrate, so disable nic and VG self.save_nic = self.ui.nic_box.text() self.save_vg = self.ui.vg_box.text() self.ui.nic_box.setText('') self.ui.nic_box.setEnabled(False) self.ui.vg_box.setText('') self.ui.vg_box.setEnabled(False) else: # default, unlock nic and vg boxes self.ui.nic_box.setEnabled(True) if self.save_nic is not None: self.ui.nic_box.setText(self.save_nic) self.save_nic = None self.ui.vg_box.setEnabled(True) if self.save_vg is not None: self.ui.vg_box.setText(self.save_vg) self.save_vg = None def update_config_status(self): cfg = self.be.get_config() self.status_config_message_label.setText('Nicotine: %d mg/mL %s; Recipes Loaded: %d'%( cfg['nic_strength'], cfg['nic_base'].upper(), cfg['n_recipes'])) def load_config(self): is_init_last = self.is_init self.is_init = False # make sure update_mix doesn't fail when the config is cleared out self.be = Backend(self.config_file) selected_recipe = self.ui.recipe_box.currentText() self.populate_recipe_box(selected_recipe) self.is_init = is_init_last self.update_mix() def populate_recipe_box(self, selected_recipe=None): is_init_last = self.is_init self.is_init = False self.ui.recipe_box.clear() for recipe in self.be.get_recipes(): self.ui.recipe_box.addItem(recipe) if selected_recipe is not None: selected_index = self.ui.recipe_box.findText(selected_recipe) if selected_index != -1: self.ui.recipe_box.setCurrentIndex(selected_index) self.is_init = is_init_last def update_recipe_status(self): if not self.is_init: return current_recipe = str(self.ui.recipe_box.currentText()) total_flav = self.be.get_total_flavor(current_recipe) if total_flav is None: self.ui.status_bar.showMessage('Recipe %s not found!'%current_recipe) else: total_flav = total_flav * 100.0 self.ui.status_bar.showMessage('Recipe: %s; Total Flavor: %.1f%%; Max VG: %.1f%%'%( current_recipe, total_flav, 100.0-total_flav)) def check_inputs(self): """ Read the mix parameters from the UI elements and convert numbers to type float. If float() returns a value error, mark that input box red and return None, otherwise return a tuple of parameters that can be passed directly to backend.calculate_mix() """ # We can always make these strings, and strings are expected anyway so no error checking # calculate_mix will make sure that the selected recipe exists recipe = str(self.ui.recipe_box.currentText()) mix = str(self.ui.mix_box.itemData(self.ui.mix_box.currentIndex())) # NOTE: names here must match the inputs of Backend.calculate_mix inputs_out = {'recipe_name': recipe, 'mix': mix} inputs_check = [('totalvol', self.ui.totalvol_box)] if mix != 'concentrate': inputs_check += [('nic', self.ui.nic_box), ('vg', self.ui.vg_box)] err = False for (field, box) in inputs_check: try: inputs_out[field] = float(box.text()) if inputs_out[field] < 0: raise ValueError box.setStyleSheet('') except ValueError: box.setStyleSheet('background-color: rgb(255, 102, 102);') err = True return None if err else inputs_out def launch_redit(self): if self.recipe_editor is None: self.recipe_editor = RecipeEditor(self, self.be) self.recipe_editor.signal_exit.connect(self.handle_redit_exit) self.recipe_editor.signal_backend_updated.connect(self.handle_redit_backend_update) self.recipe_editor.show() def handle_mixtype_change(self): # wrapper here for change event on mix type box # Do this rather than assigning 2 slots so it executes in definite order self.update_mix_type() self.update_mix() @pyqtSlot() def handle_redit_backend_update(self): selected_recipe = self.ui.recipe_box.currentText() self.populate_recipe_box(selected_recipe) self.update_recipe_status() self.update_mix() @pyqtSlot(str) def handle_redit_exit(self, text): self.ui.output_box.setPlainText('RBUILD EXIT:' + text) self.recipe_editor = None def exit(self): QtCore.QCoreApplication.instance().quit()
class GenericEmulatorPlugin(Plugin): def __init__(self, reader, writer, token): self.configuration = DefaultConfig() super().__init__( Platform(self.configuration.my_platform_to_gog ), # choose platform from available list "0.1", # version reader, writer, token) self.backend = Backend() self.my_library_thread = None self.my_library_started = False self.my_threads = [] self.my_tasks = [] self.started_async_tick = False self.keep_ticking = True if (self.configuration.minimize_logging): logging.getLogger().setLevel(logging.WARNING) else: logging.getLogger().setLevel(logging.DEBUG) #Wait for the backend to setup to help reduce the amount of issues with galaxy and race conditions def handshake_complete(self): logging.info("Handshake complete") self.backend.my_handshook = True if not self.backend.backend_setup and self.configuration.force_batch_mode_initial_seed: self.backend.setup(self.configuration) # required api interface to authenticate the user with the platform async def authenticate(self, stored_credentials=None): logging.debug("authenticate called") my_auth = await do_auth(self, self.configuration.my_user_to_gog) return my_auth # required api interface async def pass_login_credentials(self, step, credentials, cookies): logging.debug("pass_login_credentials called") my_auth = await do_auth(self, self.configuration.my_user_to_gog) return my_auth # required api interface to return the owned games async def get_owned_games(self): logging.debug( "get local games will wait for library to setup if necessary") if not self.backend.backend_setup: await self.backend.setup(self.configuration) logging.debug("get owned") list_to_galaxy = [] found_games = self.backend.local_game_cache for game in found_games: this_game = await create_game(game) list_to_galaxy.append(this_game) logging.debug(len(list_to_galaxy)) self.backend.my_imported_owned = True return list_to_galaxy # api interface to install games # Only placeholder so the get_local_games feature is recognized async def install_game(self, game_id): logging.debug("install called") logging.debug(game_id) async def get_game_time(self, game_id, context): logging.debug("getting play time") logging.debug(game_id) for current_game in self.backend.local_time_cache: if escapejson(current_game["hash_digest"]) == game_id: logging.debug(current_game["last_time_played"]) logging.debug(current_game["run_time_total"]) return GameTime(game_id, current_game["run_time_total"], current_game["last_time_played"]) #not in cache so never played logging.debug("never played") return GameTime(game_id, 0, None) # api interface to uninstall games # Only placeholder so the get_local_games feature is recognized async def uninstall_game(self, game_id): logging.debug("uninstall called") logging.debug(game_id) # api interface to update game library data with tags # assumes that library has already been imported async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: logging.debug("Updating library " + game_id) my_current_game_selected = {} #call function to update for current_game_checking in self.backend.local_game_cache: my_escaped_id = escapejson(current_game_checking["hash_digest"]) if (my_escaped_id == game_id): my_current_game_selected = current_game_checking break game_tags = my_current_game_selected["tags"] logging.debug(game_tags) game_settings = GameLibrarySettings(game_id, game_tags, False) return game_settings # api interface to return locally installed games # appears that get_owned_games will always run first async def get_local_games(self): logging.debug( "get local games will wait for library to setup if necessary") if not self.backend.backend_setup: await self.backend.setup(self.configuration) logging.debug("get local") localgames = [] for local_game in self.backend.local_game_cache: if local_game["gameShouldBeInstalled"]: localgames.append( LocalGame(local_game["hash_digest"], local_game["local_game_state"])) else: logging.debug("Only Owned:") logging.debug(local_game) logging.debug(len(localgames)) self.backend.my_imported_local = True return localgames # mod of api interface to periodically run processes such as rescanning for library changes def tick(self): if not self.started_async_tick: logging.debug("Setup ticking") self.started_async_tick = True asyncio.get_event_loop() my_task = asyncio.create_task(tick_async(self)) self.my_tasks.append(my_task) logging.debug( "tick setup will initialize backend setup if necessary") if not self.backend.backend_setup: logging.debug("Backend setup was necessary") my_task_update = asyncio.create_task( self.backend.setup(self.configuration)) self.my_tasks.append(my_task_update) else: logging.debug("Backend was setup already") logging.debug("starting library thread up for the first time") self.my_library_thread = threading.Thread(target=library_thread, args=(self, )) self.my_library_thread.daemon = True self.my_library_thread.start() #Lets just send the game data once just incase my_task_owned = asyncio.create_task(self.get_owned_games()) self.my_tasks.append(my_task_owned) my_task_local = asyncio.create_task(self.get_local_games()) self.my_tasks.append(my_task_local) logging.debug("end setup ticking") # api interface shutdown nicely async def shutdown(self): logging.debug("shutdown called") self.keep_ticking = False await shutdown_tasks(self, self.my_tasks) await shutdown_library(self) tasks = [ t for t in asyncio.all_tasks() if t is not asyncio.current_task() ] for my_task in tasks: logging.info("still running") logging.info(my_task) #loop = asyncio.get_event_loop() #loop.close() #await asyncio.sleep(3) logging.debug("all done shutdown") # api interface to startup game # requires get_local_games to have listed the game async def launch_game(self, game_id): logging.debug("launch program") execution_command = await get_exe_command( game_id, self.backend.local_game_cache) my_current_time = datetime.now() logging.debug(execution_command) my_thread = threading.Thread(target=run_my_selected_game_here, args=( execution_command, logging, )) self.my_threads.append(my_thread) my_thread.name = json.dumps({ "time": my_current_time.isoformat(), "id": game_id }) logging.debug(my_thread.name) my_thread.daemon = True my_thread.start()
def __init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test=False): """ Creates an instance of the vegas internals. GuppiBackend( bank ) Where bank is the instance of the player's Bank. """ Backend.__init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test) # This needs to happen on construct so that status monitors can # switch their data buffer format self.progdev() self.net_config() if self.mode.roach_kvpairs: self.write_registers(**self.mode.roach_kvpairs) self.reset_roach() self.write_status(BACKEND="GUPPI") # The default switching in the Backend ctor is a static SIG, NOCAL, and no blanking # defaults self.max_databuf_size = 128 # in MBytes [Not sure where this ties in. Value from the manager] self.obs_mode = 'SEARCH' """Parameter 'obs_mode': GUPPI observation mode""" self.nchan = self.mode.nchan """Parameter 'nchan': Number of channels""" self.integration_time = 40.96E-6 """Parameter 'integration_time': Lenght of integration, in seconds.""" self.overlap = 0 self.scale_i = 1 self.scale_q = 1 self.scale_u = 1 self.scale_v = 1 self.offset_i = 0 self.offset_q = 0 self.offset_u = 0 self.offset_v = 0 self.only_i = 0 self.chan_dm = 0.0 self.rf_frequency = 2000.0 self.nbin = 256 self.tfold = 1.0 self.dm = 0.0 # Almost all receivers are dual polarization self.nrcvr = 2 self.feed_polarization = 'LIN' self.bandwidth = self.frequency if self.dibas_dir is not None: self.pardir = self.dibas_dir + '/etc/config' else: self.pardir = '/tmp' self.parfile = 'example.par' # self.params["bandwidth" ] = self.set_bandwidth self.params["integration_time"] = self.set_integration_time self.params["nbin"] = self.set_nbin self.params["obs_frequency"] = self.set_obs_frequency self.params["obs_mode"] = self.set_obs_mode self.params["only_i"] = self.set_only_i self.params["scale"] = self.set_scale self.params["scale_i"] = self.set_scale_I self.params["scale_q"] = self.set_scale_Q self.params["scale_u"] = self.set_scale_U self.params["scale_v"] = self.set_scale_V self.params["tfold"] = self.set_tfold self.params["feed_polarization"] = self.setFeedPolarization self.params["par_file"] = self.set_par_file self._fft_params_dep() if self.hpc_process is None: self.start_hpc() self.arm_roach()
def __init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test=False): """ Creates an instance of the class. """ # Only one HPC Player will be controlling a roach in the CODD # mode family. Therefore figure out if we are the one; if not, # set the parameters 'theRoach' and 'theValon' to None, even if # this HPC does control a roach in other modes. if theMode.cdd_master_hpc == theBank.name: Backend.__init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test) self.progdev() self.net_config() if self.mode.roach_kvpairs: self.write_registers(**self.mode.roach_kvpairs) self.reset_roach() else: Backend.__init__(self, theBank, theMode, None, None, None, unit_test) # This needs to happen on construction so that status monitors can # change their data buffer format. self.set_status(BACKEND="GUPPI") # The default switching in the Backend ctor is a static SIG, NOCAL, and no blanking self.max_databuf_size = 128 # in MBytes self.scale_p0 = 1.0 self.scale_p1 = 1.0 self.only_i = 0 self.bandwidth = self.frequency self.dm = 0.0 self.rf_frequency = 1430.0 self.overlap = 0 self.tfold = 1.0 self.nbin = 256 # Most all receivers are dual polarization self.nrcvr = 2 self.nchan = self.mode.nchan # total number of channels in the design, not per node self.num_nodes = 8 self.feed_polarization = 'LIN' self.obs_mode = 'COHERENT_SEARCH' bank_names = { 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7 } self.node_number = bank_names[self.bank.name[-1]] self.integration_time = 40.96E-6 self.scan_length = 30.0 if self.dibas_dir is not None: self.pardir = self.dibas_dir + '/etc/config' else: self.pardir = '/tmp' self.parfile = 'example.par' self.datadir = '/lustre/gbtdata/JUNK' # Needs integration with projectid # register set methods # self.params["bandwidth" ] = self.set_bandwidth self.params["dm"] = self.set_dm self.params["integration_time"] = self.set_integration_time self.params["nbin"] = self.set_nbin self.params["num_channels"] = self.set_nchannels self.params["obs_frequency"] = self.set_obs_frequency self.params["obs_mode"] = self.set_obs_mode self.params["par_file"] = self.set_par_file self.params["scale_p0"] = self.set_scale_P0 self.params["scale_p1"] = self.set_scale_P1 self.params["tfold"] = self.set_tfold self.params["only_i"] = self.set_only_i self.params["feed_polarization"] = self.setFeedPolarization self.params["_node_number"] = self.setNodeNumber # Fill-in defaults if they exist if 'OBS_MODE' in self.mode.shmkvpairs.keys(): self.set_param('obs_mode', self.mode.shmkvpairs['OBS_MODE']) if 'ONLY_I' in self.mode.shmkvpairs.keys(): self.set_param('only_i', int(self.mode.shmkvpairs['ONLY_I'])) if 'SCALE_P0' in self.mode.roach_kvpairs.keys(): self.set_param('scale_p0', float(self.mode.roach_kvpairs['SCALE_P0'])) if 'SCALE_P1' in self.mode.roach_kvpairs.keys(): self.set_param('scale_p1', float(self.mode.roach_kvpairs['SCALE_P1'])) if self.hpc_process is None: self.start_hpc() if self.cdd_master(): self.arm_roach()
async def test_no_updates_send(self): self.configuration = DefaultConfig() self.backend = Backend() await self.backend.setup(self.configuration) self.backend.my_handshook = True await send_events(self)
def __init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test=False, instance_id=None): """ Creates an instance of BeamformerBackend """ self.roach_simulator = True print "BFBE: ROACH SIMULATOR MODE" self.name = theMode.backend_name.lower() self.current_mode = theMode.name self.bank_name = theBank.name.upper() # Read in the additional parameters from the configuration file #config_file = './dibas.conf' config_file = os.getenv("DIBAS_DIR") + '/etc/config/dibas.conf' dibas_parser = DibasParser(dibas_conf_file=config_file) dibas_info = dibas_parser.get_dibas_info() self.roaches = [] self.configures_roaches = False self.RD = None self.pkt_gen = dibas_info['pkt_gen'] roach_names = dibas_info['roaches'] if theBank.name == dibas_info['isDoctor']: self.RD = RoachDoctor(roach_host_list=roach_names, dibas_info=dibas_info) self.configures_roaches = True self.roaches = self.RD.get_roaches() #self.RD.configure(fft_shift=0xffffffff, quan_gain=0x00000014) self.RD.configure(simulator=self.roach_simulator) self.read_parameters(theBank, theMode) # init the super, clear shmem and init shmem Backend.__init__(self, theBank, theMode, theRoach, theValon, hpc_macs, unit_test) self.clear_shared_memory() self.status = FlagPole(instance_id=self.instance) # Set some default parameter values self.requested_weight_file = '' self.weifile_new = '' self.requested_channel = 0 self.requested_integration_time = 1.0 self.fits_writer_process = None # Add additional dealer-controlled parameters self.params["int_length"] = self.setIntegrationTime self.params["weight_file"] = self.setNewWeightFilename self.params["channel_select"] = self.setChannel # TODO: will we need use roach_kvpairs if self.mode.roach_kvpairs: self.write_registers(**self.mode.roach_kvpairs) # TODO: will we need to use reset_roach - this is defined in diabs.conf, a sequence of commands to execute #self.reset_roach() self.prepare() # super class backend says this is backend dependent and I dont think our backend needs this #self.clear_switching_states() #self.add_switching_state(1.0, blank = False, cal = False, sig_ref_1 = False) self.start_hpc() self.fits_writer_program = self.fits_writer_program_bf self.start_fits_writer()
def run_data_update(): global corona_joined, county_cases, location_cube, country_location_cube, sex, age try: backend = Backend() backend.start_connection() corona_joined = backend.get_cube("corona_joined") county_cases = backend.get_cube("county_cases") location_cube = backend.get_cube(coronavirus_location.table_name) country_location_cube = country_location() sex = backend.get_cube("sex") age = backend.get_cube("age") except Exception as e: logger.error("Error fetching database: %s", e) schedule = datetime.datetime.now() while True: if datetime.datetime.now() >= schedule: logger.info("Updating database.") try: backend = Backend() backend.start_connection() backend.update_coronavirus_data() midnight_today = datetime.datetime.combine( datetime.date.today(), datetime.datetime.min.time()) schedule = midnight_today + datetime.timedelta( days=1, hours=UPDATE_TIME) corona_joined = backend.get_cube("corona_joined") county_cases = backend.get_cube("county_cases") location_cube = backend.get_cube( coronavirus_location.table_name) country_location_cube = country_location() sex = backend.get_cube("sex") age = backend.get_cube("age") logger.info("Update succeed. Scheduled for %s UTC", schedule) except Exception as e: logger.error("Error updating database: %s", e) time.sleep(3600)