def get(self): service = app_identity.get_application_id() version = modules.get_current_version_name() instance_id = hash(modules.get_current_instance_id()) % 10 endpoint = MONACQ_ENDPOINT config.initialize(job_name=version, instance=instance_id, service_name=service, endpoint=endpoint) self.response.set_status(200, 'Initialized instance of ts_mon.')
def run(): config.initialize() #startPos = 5000 #numSamples = 100 #generateSolutionsFromTrainingSet(startPos, numSamples) #print "Result: %f" % scoreTrainingSolutions(startPos, numSamples) generateTestResults()
def handler(mod_python_req, fields = None, is_profiling = False): # Create an object that contains all data about the request and # helper functions for creating valid HTML. Parse URI and # store results in the request object for later usage. __builtin__.html = html_mod_python(mod_python_req, fields) response_code = apache.OK try: config.initialize() init_profiling(is_profiling) html.init_modes() # Make sure all plugins are avaiable as early as possible. At least # we need the plugins (i.e. the permissions declared in these) at the # time before the first login for generating auth.php. modules.load_all_plugins() # Get page handler. handler = modules.get_handler(html.myfile, page_not_found) # Some pages do skip authentication. This is done by adding # noauth: to the page hander, e.g. "noauth:run_cron" : ... # TODO: Eliminate those "noauth:" pages. Eventually replace it by call using # the now existing default automation user. if handler == page_not_found: handler = modules.get_handler("noauth:" + html.myfile, page_not_found) if handler != page_not_found: try: handler() except Exception, e: html.write(str(e)) if config.debug: html.write(html.attrencode(traceback.format_exc())) raise FinalizeRequest() # Ensure the user is authenticated. This call is wrapping all the different # authentication modes the Check_MK GUI supports and initializes the logged # in user objects. if not login.authenticate(mod_python_req): handle_not_authenticated() # Initialize the multiste i18n. This will be replaced by # language settings stored in the user profile after the user # has been initialized previous_language = i18n.get_current_language() i18n.localize(html.var("lang", config.user.language())) # All plugins might have to be reloaded due to a language change. Only trigger # a second plugin loading when the user is really using a custom localized GUI. # Otherwise the load_all_plugins() at the beginning of the request is sufficient. if i18n.get_current_language() != previous_language: modules.load_all_plugins() ensure_general_access() handler()
def run(filename, **params): config.initialize(filename, **params) importer = config.data.importer mainModule = importer.getIdent(0) mir = mainModule.getMIR() if config.data.dump_mir: ti.mir.dumpMir(mir, config.data.dump_mir) if config.data.mir_only: return scope = config.data.currentScope config.data.currentScope = mainModule.getScope() ti.mir.walkChain(mir, config.data.currentScope) config.data.currentScope = scope
def change_dim(value): if dim_select.value == '1D': config.dim, config.csd_profile, config.kCSD, config.visibility_map = \ config.initialize(dim_select.value) elif dim_select.value == '2D': config.dim, config.csd_profile, config.kCSD, config.visibility_map = \ config.initialize(dim_select.value) else: config.dim, config.csd_profile, config.kCSD, config.visibility_map = \ config.initialize(dim_select.value) update_csd_types() update_kcsd_types() update_accordion()
def main(): options = get_options() options = initialize(options) options = create_dataset(options, train=True) options = create_dataset(options, train=False) model = get_model(options) optimizer = get_optimizer(options, model) scheduler = get_scheduler(options, optimizer) # Criterions are like `torch.nn.CrossEntropyLoss()` criterion = get_criterion(options, model) metrics = get_metrics(options) model = convert_dtype(options.dtype, model) criterion = convert_dtype(options.dtype, criterion) if options.use_cuda: model.cuda() criterion.cuda() options = checkpoint.maybe_resume(options, model, optimizer, scheduler) controlflow = get_controlflow(options) controlflow(model=model, optimizer=optimizer, criterion=criterion, metrics=metrics, scheduler=scheduler, options=options)
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop. """ log.debug("Core starting") try: # Windows >= Vista ctypes.windll.user32.SetProcessDPIAware() except AttributeError: pass import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath=config.getUserDefaultConfigPath(useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info("Config dir: %s"%os.path.abspath(globalVars.appArgs.configPath)) log.debug("loading config") import config config.initialize() if not globalVars.appArgs.minimal and config.conf["general"]["playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\start.wav") except: pass logHandler.setLogLevelFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s"%lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s"%lang) import versionInfo log.info("NVDA version %s" % versionInfo.version) log.info("Using Windows version %s" % winVersion.winVersionText) log.info("Using Python version %s"%sys.version) log.info("Using comtypes version %s"%comtypes.__version__) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing add-ons system") addonHandler.initialize() if globalVars.appArgs.disableAddons: log.info("Add-ons are disabled. Restart NVDA to enable them.") import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time()-globalVars.startTime)>5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time()-globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx log.info("Using wx version %s"%wx.version()) class App(wx.App): def OnAssert(self,file,line,cond,msg): message="{file}, line {line}:\nassert {cond}: {msg}".format(file=file,line=line,cond=cond,msg=msg) log.debugWarning(message,codepath="WX Widgets",stack_info=True) app = App(redirect=False) # We do support QueryEndSession events, but we don't want to do anything for them. app.Bind(wx.EVT_QUERY_END_SESSION, lambda evt: None) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal and config.conf["general"]["playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav",async=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) import braille log.debug("Initializing braille") braille.initialize() log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() import audioDucking if audioDucking.isAudioDuckingSupported(): # the GUI mainloop must be running for this to work so delay it wx.CallAfter(audioDucking.initialize) # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR. # NVDA uses the main frame to check for and quit another instance of NVDA. # To remain compatible with older versions of NVDA, create our own wxWindowClassNR. # We don't need to do anything else because wx handles WM_QUIT for all windows. import windowUtils class MessageWindow(windowUtils.CustomWindow): className = u"wxWindowClassNR" messageWindow = MessageWindow(unicode(versionInfo.name)) # initialize wxpython localization support locale = wx.Locale() lang=languageHandler.getLanguage() wxLang=locale.FindLanguageInfo(lang) if not wxLang and '_' in lang: wxLang=locale.FindLanguageInfo(lang.split('_')[0]) if hasattr(sys,'frozen'): locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(),"locale")) if wxLang: try: locale.Init(wxLang.Language) except: log.error("Failed to initialize wx locale",exc_info=True) else: log.debugWarning("wx does not support language %s" % lang) import api import winUser import NVDAObjects.window desktopObject=NVDAObjects.window.Window(windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except NotImplementedError: log.warning("UIA not available") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install or globalVars.appArgs.installSilent: import wx import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall,startAfterInstall=not globalVars.appArgs.installSilent) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: gui.LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject # Doing this here is a bit ugly, but we don't want these modules imported # at module level, including wx. log.debug("Initializing core pump") class CorePump(wx.Timer): "Checks the queues and executes functions." def Notify(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: A pump was requested, but the timer was ignored by a modal loop # because timers aren't re-entrant. # Therefore, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True) global _pump _pump = CorePump() requestPump() log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck=None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: _terminate(updateCheck) _terminate(watchdog) _terminate(globalPluginHandler, name="global plugin handler") _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject,"event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) if not globalVars.appArgs.minimal and config.conf["general"]["playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav",async=False) except: pass # #5189: Destroy the message window as late as possible # so new instances of NVDA can find this one even if it freezes during exit. messageWindow.destroy() log.debug("core done")
os.chdir(SOURCE_DIR) # The path to this package might be relative, so make it absolute, # since we just changed directory. __path__[0] = UNIT_DIR # We don't want logging for now, # though we may optionally want this in future; see #7045. import logging from logHandler import log log.addHandler(logging.NullHandler()) # There's no point in logging anything at all, since it'll go nowhere. log.setLevel(100) # Much of this should eventually be replaced by stuff which gets reset before each test # so the tests are isolated. import config config.initialize() # Initialize languageHandler so that translatable strings work. import languageHandler languageHandler.setLanguage("en") # NVDAObjects need appModuleHandler to be initialized. import appModuleHandler appModuleHandler.initialize() # Anything which notifies of cursor updates requires braille to be initialized. import braille braille.initialize() # For braille unit tests, we need to construct a fake braille display as well as enable the braille handler # Give the display 40 cells braille.handler.displaySize=40 braille.handler.enabled = True # The focus and navigator objects need to be initialized to something. from objectProvider import PlaceholderNVDAObject,NVDAObjectWithRole
def main(): """ Zarp entry point """ # set up configuration config.initialize() # set up database database.initialize() # load modules loader = LoadedModules() loader.load() Msg("Loaded %d modules." % loader.total) # handle command line options first if len(argv) > 1: parse_cmd.parse(argv, loader) # menus main_menu = ["Poisoners", "DoS Attacks", "Sniffers", "Scanners", "Parameter", "Services", "Attacks", "Sessions"] running = True choice = -1 while running: header() choice = print_menu(main_menu) if choice == 0: # check if they've got running sessions! cnt = stream.get_session_count() if cnt > 0: choice = raw_input( color.YELLOW + "You have %d sessions running. Are you sure? [Y/n] " % cnt + color.END ) if "y" in choice.lower() or choice == "": Msg("Shutting all sessions down...") stream.stop_session("all", -1) running = False # recheck that all sessions are down cnt = stream.get_session_count() if cnt <= 0: # some libs dont clean up their own threads, so # we need to hard quit those to avoid hanging; FIXME _exit(1) else: debug("Exiting with session count: %d" % (cnt)) Msg("Exiting...") running = False elif choice == 1: while True: choice = print_menu([x().which for x in loader.poison]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.poison): continue else: stream.initialize(loader.poison[choice - 1]) elif choice == 2: while True: choice = print_menu([x().which for x in loader.dos]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.dos): continue else: stream.initialize(loader.dos[choice - 1]) elif choice == 3: while True: choice = print_menu([x().which for x in loader.sniffers]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.sniffers): continue else: stream.initialize(loader.sniffers[choice - 1]) elif choice == 4: while True: choice = print_menu([x().which for x in loader.scanner]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.scanner): continue else: stream.initialize(loader.scanner[choice - 1]) elif choice == 5: while True: choice = print_menu([x().which for x in loader.parameter]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.parameter): continue else: stream.initialize(loader.parameter[choice - 1]) elif choice == 6: while True: choice = print_menu([x().which for x in loader.services]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.services): continue else: stream.initialize(loader.services[choice - 1]) elif choice == 7: while True: choice = print_menu([x().which for x in loader.attacks]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.attacks): continue else: stream.initialize(loader.attacks[choice - 1]) elif choice == 8: session_manager.menu() elif choice == -1: pass
def main(): # handle command line options first if len(sys.argv) > 1: parse_cmd.parse(sys.argv) # set up configuration config.initialize() # menus main_menu = [ 'Poisoners', 'DoS Attacks', 'Sniffers', 'Scanners', 'Parameter','Services','Sessions'] poison_menu = [ 'ARP Poison', 'DNS Poison', 'DHCP Poison', 'NBNS Spoof'] dos_menu = [ 'NDP', 'Nestea', 'LAND', 'TCP SYN', 'SMB2', 'DHCP Starve' ] sniffer_menu = [ 'HTTP Sniffer', 'Password Sniffer', 'Traffic Sniffer'] service_menu = [ 'HTTP Server', 'SSH Server', 'FTP Server', 'SMB Listener', 'Access Point' ] scanner_menu = [ 'NetMap', 'Service Scan', 'AP Scan'] parameter_menu = [ 'WEP Crack', 'WPA2 Crack', 'WPS Crack', 'Router Pwn', 'Pass-The-Hash' ] running = True choice = -1 while running: header() choice = print_menu(main_menu) if choice == 0: # check if they've got running sessions! cnt = stream.get_session_count() if cnt > 0: Msg('You have %d sessions running. Are you sure?'%cnt) choice = raw_input('> ') if 'y' in choice.lower(): stream.stop_session('all', -1) running = False else: debug("Exiting with session count: %d"%(cnt)) Msg("Exiting...") running = False elif choice == 1: while True: choice = print_menu(poison_menu) if choice == 0: break elif choice == 1: stream.initialize('arp') elif choice == 2: stream.initialize('dns') elif choice == 3: stream.initialize('dhcp') elif choice == 4: stream.initialize('nbns') elif choice == -1: pass elif choice == 2: while True: choice = print_menu(dos_menu) if choice == 1: stream.initialize('ndp') elif choice == 2: stream.initialize('nestea') elif choice == 3: stream.initialize('land') elif choice == 4: stream.initialize('tcp_syn') elif choice == 5: stream.initialize('smb2') elif choice == 6: stream.initialize('dhcp_starv') elif choice == 0: break elif choice == -1: pass else: os.system('clear') elif choice == 3: while True: choice = print_menu(sniffer_menu) if choice == 0: break elif choice == 1: stream.initialize('http_sniffer') elif choice == 2: stream.initialize('password_sniffer') elif choice == 3: stream.initialize('traffic_sniffer') elif choice == -1: pass elif choice == 4: while True: choice = print_menu(scanner_menu) if choice == 0: break elif choice == 1: stream.initialize('net_map') elif choice == 2: stream.initialize('service_scan') elif choice == 3: stream.initialize('ap_scan') elif choice == -1: pass elif choice == 5: while True: choice = print_menu(parameter_menu) if choice == 0: break elif choice == 1: stream.initialize('wep_crack') elif choice == 2: stream.initialize('wpa_crack') elif choice == 3: stream.initialize('wps_crack') elif choice == 4: stream.initialize('router_pwn') elif choice == 5: util.Error('Module not yet implemented') #stream.initialize('pass_the_hash') elif choice == -1: pass elif choice == 6: while True: choice = print_menu(service_menu) if choice == 0: break elif choice == 1: stream.initialize('http_server') elif choice == 2: stream.initialize('ssh_server') elif choice == 3: stream.initialize('ftp_server') elif choice == 4: stream.initialize('smb') elif choice == 5: stream.initialize('access_point') elif choice == -1: pass elif choice == 7: session_manager.menu() elif choice == -1: pass
# print "MY HOPS: " + str(my_hops_by_path_id) request_details = {"my_nodes_by_interface" : my_nodes_by_interface, "my_links" : my_links, "my_hops_by_path_id" : my_hops_by_path_id} return error_string, error_code, request_details # Restore stitching state from archive def restoreStitchingState(self, sliver_urn, tag, link): self._reservations[sliver_urn] = {'vlan_tag' : tag, 'link' : link} self._edge_points[link]._vlans.allocate(tag) if __name__ == '__main__': config.initialize('/Users/mbrinn/stitch_testing/config.json') stitching = Stitching() for ep in stitching._edge_points: print str(ep) advert = stitching.generateAdvertisement() print advert.toprettyxml() request_filename = "/Users/mbrinn/stitch_testing/bos-cal-request-rspec.xml" request_raw = None try: f = open(request_filename, 'r'); request_raw = f.read() f.close() except Exception, e: print "Can't read request file " + request_filename + " " + str(e) sys.exit(0)
host.AddMethod(TargetLibrary, "TargetLibrary") host.AddMethod(UseLibraries, "UseLibraries") host.AddMethod(UseServers, "UseServers") host.AddMethod(TargetInstall, "TargetInstall") host.Append(ROOTFS = '#${BUILDROOT}/rootfs') host.Append(ROOTFS_FILES = []) host.Append(bin = '${ROOTFS}/bin', etc = '${ROOTFS}/etc', server = '${ROOTFS}/server', boot = '${ROOTFS}/boot') target = host.Clone(tools = ["default", "bootimage", "iso", "binary", "linn", "phony"], #), toolpath = ["support/scons"]) #site_scons"]) # Apply configuration config.initialize(target, host, ARGUMENTS) config.write_header(target) config.write_header(host) # Enables verbose compilation command output. if not target['VERBOSE']: target['CXXCOMSTR'] = host['CXXCOMSTR'] = " CXX $TARGET" target['CCCOMSTR'] = host['CCCOMSTR'] = " CC $TARGET" target['ASCOMSTR'] = host['ASCOMSTR'] = " AS $TARGET" target['ASPPCOMSTR'] = host['ASPPCOMSTR'] = " AS $TARGET" target['ARCOMSTR'] = host['ARCOMSTR'] = " AR $TARGET" target['RANLIBCOMSTR'] = host['RANLIBCOMSTR'] = " LIB $TARGET" target['LINKCOMSTR'] = host['LINKCOMSTR'] = " LD $TARGET" target['COPYSTR'] = host['COPYSTR'] = " COPY $SOURCE => $TARGET" # Verify the configured CFLAGS.
def main(): """ Zarp entry point """ # set up configuration config.initialize() # set up database database.initialize() # load modules loader = LoadedModules() loader.load() Msg('Loaded %d modules.' % loader.total) # handle command line options first if len(argv) > 1: parse_cmd.parse(argv, loader) # menus main_menu = ['Poisoners', 'DoS Attacks', 'Sniffers', 'Scanners', 'Parameter', 'Services', 'Attacks', 'Sessions'] running = True choice = -1 while running: header() choice = print_menu(main_menu) if choice == 0: # check if they've got running sessions! cnt = stream.get_session_count() if cnt > 0: choice = raw_input(color.YELLOW + 'You have %d sessions running. Are you sure? [Y/n] ' % cnt + color.END) if 'y' in choice.lower() or choice == '': Msg('Shutting all sessions down...') stream.stop_session('all', -1) running = False else: debug("Exiting with session count: %d" % (cnt)) Msg("Exiting...") running = False elif choice == 1: while True: choice = print_menu([x().which for x in loader.poison]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.poison): continue else: stream.initialize(loader.poison[choice - 1]) elif choice == 2: while True: choice = print_menu([x().which for x in loader.dos]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.dos): continue else: stream.initialize(loader.dos[choice - 1]) elif choice == 3: while True: choice = print_menu([x().which for x in loader.sniffers]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.sniffers): continue else: stream.initialize(loader.sniffers[choice - 1]) elif choice == 4: while True: choice = print_menu([x().which for x in loader.scanner]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.scanner): continue else: stream.initialize(loader.scanner[choice - 1]) elif choice == 5: while True: choice = print_menu([x().which for x in loader.parameter]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.parameter): continue else: stream.initialize(loader.parameter[choice - 1]) elif choice == 6: while True: choice = print_menu([x().which for x in loader.services]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.services): continue else: stream.initialize(loader.services[choice - 1]) elif choice == 7: while True: choice = print_menu([x().which for x in loader.attacks]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.attacks): continue else: stream.initialize(loader.attacks[choice - 1]) elif choice == 8: session_manager.menu() elif choice == -1: pass
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop. """ log.debug("Core starting") ctypes.windll.user32.SetProcessDPIAware() import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath = config.getUserDefaultConfigPath( useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info(f"Config dir: {globalVars.appArgs.configPath}") log.debug("loading config") import config config.initialize() if globalVars.appArgs.configPath == config.getUserDefaultConfigPath( useInstalledPathIfExists=True): # Make sure not to offer the ability to copy the current configuration to the user account. # This case always applies to the launcher when configPath is not overridden by the user, # which is the default. # However, if a user wants to run the launcher with a custom configPath, # it is likely that he wants to copy that configuration when installing. # This check also applies to cases where a portable copy is run using the installed configuration, # in which case we want to avoid copying a configuration to itself. # We set the value to C{None} in order for the gui to determine # when to disable the checkbox for this feature. globalVars.appArgs.copyPortableConfig = None if config.conf['development']['enableScratchpadDir']: log.info("Developer Scratchpad mode enabled") if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile( os.path.join(globalVars.appDir, "waves", "start.wav")) except: pass logHandler.setLogLevelFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s" % lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s" % lang) log.info(f"Windows version: {winVersion.getWinVer()}") log.info("Using Python version %s" % sys.version) log.info("Using comtypes version %s" % comtypes.__version__) import configobj log.info("Using configobj version %s with validate version %s" % (configobj.__version__, configobj.validate.__version__)) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing add-ons system") addonHandler.initialize() if globalVars.appArgs.disableAddons: log.info("Add-ons are disabled. Restart NVDA to enable them.") import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() log.debug("Initializing tones") import tones tones.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time() - globalVars.startTime) > 5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time() - globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx # wxPython 4 no longer has either of these constants (despite the documentation saying so), some add-ons may rely on # them so we add it back into wx. https://wxpython.org/Phoenix/docs/html/wx.Window.html#wx.Window.Centre wx.CENTER_ON_SCREEN = wx.CENTRE_ON_SCREEN = 0x2 import six log.info("Using wx version %s with six version %s" % (wx.version(), six.__version__)) class App(wx.App): def OnAssert(self, file, line, cond, msg): message = "{file}, line {line}:\nassert {cond}: {msg}".format( file=file, line=line, cond=cond, msg=msg) log.debugWarning(message, codepath="WX Widgets", stack_info=True) def InitLocale(self): # Backport of `InitLocale` from wx Python 4.1.2 as the current version tries to set a Python # locale to an nonexistent one when creating an instance of `wx.App`. # This causes a crash when running under a particular version of Universal CRT (#12160) import locale locale.setlocale(locale.LC_ALL, "C") app = App(redirect=False) # We support queryEndSession events, but in general don't do anything for them. # However, when running as a Windows Store application, we do want to request to be restarted for updates def onQueryEndSession(evt): if config.isAppX: # Automatically restart NVDA on Windows Store update ctypes.windll.kernel32.RegisterApplicationRestart(None, 0) app.Bind(wx.EVT_QUERY_END_SESSION, onQueryEndSession) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile(os.path.join(globalVars.appDir, "waves", "exit.wav"), asynchronous=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import braille log.debug("Initializing braille") braille.initialize() import vision log.debug("Initializing vision") vision.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() import audioDucking if audioDucking.isAudioDuckingSupported(): # the GUI mainloop must be running for this to work so delay it wx.CallAfter(audioDucking.initialize) # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR. # NVDA uses the main frame to check for and quit another instance of NVDA. # To remain compatible with older versions of NVDA, create our own wxWindowClassNR. # We don't need to do anything else because wx handles WM_QUIT for all windows. import windowUtils class MessageWindow(windowUtils.CustomWindow): className = u"wxWindowClassNR" # Windows constants for power / display changes WM_POWERBROADCAST = 0x218 PBT_APMPOWERSTATUSCHANGE = 0xA UNKNOWN_BATTERY_STATUS = 0xFF AC_ONLINE = 0X1 NO_SYSTEM_BATTERY = 0X80 #States for screen orientation ORIENTATION_NOT_INITIALIZED = 0 ORIENTATION_PORTRAIT = 1 ORIENTATION_LANDSCAPE = 2 def __init__(self, windowName=None): super(MessageWindow, self).__init__(windowName) self.oldBatteryStatus = None self.orientationStateCache = self.ORIENTATION_NOT_INITIALIZED self.orientationCoordsCache = (0, 0) self.handlePowerStatusChange() def windowProc(self, hwnd, msg, wParam, lParam): post_windowMessageReceipt.notify(msg=msg, wParam=wParam, lParam=lParam) if msg == self.WM_POWERBROADCAST and wParam == self.PBT_APMPOWERSTATUSCHANGE: self.handlePowerStatusChange() elif msg == winUser.WM_DISPLAYCHANGE: self.handleScreenOrientationChange(lParam) def handleScreenOrientationChange(self, lParam): import ui import winUser # Resolution detection comes from an article found at https://msdn.microsoft.com/en-us/library/ms812142.aspx. #The low word is the width and hiword is height. width = winUser.LOWORD(lParam) height = winUser.HIWORD(lParam) self.orientationCoordsCache = (width, height) if width > height: # If the height and width are the same, it's actually a screen flip, and we do want to alert of those! if self.orientationStateCache == self.ORIENTATION_LANDSCAPE and self.orientationCoordsCache != ( width, height): return #Translators: The screen is oriented so that it is wider than it is tall. ui.message(_("Landscape")) self.orientationStateCache = self.ORIENTATION_LANDSCAPE else: if self.orientationStateCache == self.ORIENTATION_PORTRAIT and self.orientationCoordsCache != ( width, height): return #Translators: The screen is oriented in such a way that the height is taller than it is wide. ui.message(_("Portrait")) self.orientationStateCache = self.ORIENTATION_PORTRAIT def handlePowerStatusChange(self): #Mostly taken from script_say_battery_status, but modified. import ui import winKernel sps = winKernel.SYSTEM_POWER_STATUS() if not winKernel.GetSystemPowerStatus( sps) or sps.BatteryFlag is self.UNKNOWN_BATTERY_STATUS: return if sps.BatteryFlag & self.NO_SYSTEM_BATTERY: return if self.oldBatteryStatus is None: #Just initializing the cache, do not report anything. self.oldBatteryStatus = sps.ACLineStatus return if sps.ACLineStatus == self.oldBatteryStatus: #Sometimes, this double fires. This also fires when the battery level decreases by 3%. return self.oldBatteryStatus = sps.ACLineStatus if sps.ACLineStatus & self.AC_ONLINE: #Translators: Reported when the battery is plugged in, and now is charging. ui.message( _("Charging battery. %d percent") % sps.BatteryLifePercent) else: #Translators: Reported when the battery is no longer plugged in, and now is not charging. ui.message( _("Not charging battery. %d percent") % sps.BatteryLifePercent) import versionInfo messageWindow = MessageWindow(versionInfo.name) # initialize wxpython localization support locale = wx.Locale() wxLang = getWxLangOrNone() if hasattr(sys, 'frozen'): locale.AddCatalogLookupPathPrefix( os.path.join(globalVars.appDir, "locale")) if wxLang: try: locale.Init(wxLang.Language) except: log.error("Failed to initialize wx locale", exc_info=True) finally: # Revert wx's changes to the python locale languageHandler.setLocale(languageHandler.curLang) log.debug("Initializing garbageHandler") garbageHandler.initialize() import api import winUser import NVDAObjects.window desktopObject = NVDAObjects.window.Window( windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() log.info("Java Access Bridge support initialized") except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing legacy winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except RuntimeError: log.warning("UIA disabled in configuration") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install or globalVars.appArgs.installSilent: import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall, copyPortableConfig=globalVars.appArgs.copyPortableConfig, startAfterInstall=not globalVars.appArgs.installSilent) elif globalVars.appArgs.portablePath and ( globalVars.appArgs.createPortable or globalVars.appArgs.createPortableSilent): import gui.installerGui wx.CallAfter( gui.installerGui.doCreatePortable, portableDirectory=globalVars.appArgs.portablePath, silent=globalVars.appArgs.createPortableSilent, startAfterCreate=not globalVars.appArgs.createPortableSilent) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: from gui.startupDialogs import LauncherDialog LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject # Doing this here is a bit ugly, but we don't want these modules imported # at module level, including wx. log.debug("Initializing core pump") class CorePump(gui.NonReEntrantTimer): "Checks the queues and executes functions." def run(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() vision.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: Another pump was requested during this pump execution. # As our pump is not re-entrant, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True) global _pump _pump = CorePump() requestPump() log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck = None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") # Queue the firing of the postNVDAStartup notification. # This is queued so that it will run from within the core loop, # and initial focus has been reported. queueHandler.queueFunction(queueHandler.eventQueue, postNvdaStartup.notify) log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: _terminate(updateCheck) _terminate(watchdog) _terminate(globalPluginHandler, name="global plugin handler") _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject, "event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="Legacy winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(tones) _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(vision) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) _terminate(garbageHandler) # DMP is only started if needed. # Terminate manually (and let it write to the log if necessary) # as core._terminate always writes an entry. try: import diffHandler diffHandler._dmp._terminate() except Exception: log.exception("Exception while terminating DMP") if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile(os.path.join(globalVars.appDir, "waves", "exit.wav"), asynchronous=False) except: pass # #5189: Destroy the message window as late as possible # so new instances of NVDA can find this one even if it freezes during exit. messageWindow.destroy() log.debug("core done")
os.chdir(SOURCE_DIR) # The path to this package might be relative, so make it absolute, # since we just changed directory. __path__[0] = UNIT_DIR # We don't want logging for now, # though we may optionally want this in future; see #7045. import logging from logHandler import log log.addHandler(logging.NullHandler()) # There's no point in logging anything at all, since it'll go nowhere. log.setLevel(100) # Much of this should eventually be replaced by stuff which gets reset before each test # so the tests are isolated. import config config.initialize() # Initialize languageHandler so that translatable strings work. import languageHandler languageHandler.setLanguage("en") # NVDAObjects need appModuleHandler to be initialized. import appModuleHandler appModuleHandler.initialize() # Anything which notifies of cursor updates requires braille to be initialized. import braille braille.initialize() # For braille unit tests, we need to construct a fake braille display as well as enable the braille handler # Give the display 40 cells braille.handler.displaySize = 40 braille.handler.enabled = True # The focus and navigator objects need to be initialized to something. from objectProvider import PlaceholderNVDAObject, NVDAObjectWithRole
# # For the OS environment: ensure the 'ENV' environment variable does not exist, # to avoid internal SCons exception while running the autoconf tests. # # Additionally, remove the PWD and OLDPWD variables since they can change when # using scons -u, which causes an undesirable (near) full rebuild. # for i in ['ENV', 'PWD', 'OLDPWD']: if i in os.environ: del os.environ[i] args = os.environ.copy() args.update(ARGUMENTS) # Apply configuration config.initialize(target, host, args) config.write_header(target) config.write_header(host) # Enables verbose compilation command output. if not target['VERBOSE']: target['CXXCOMSTR'] = " CXX $TARGET" target['CCCOMSTR'] = " CC $TARGET" target['ASCOMSTR'] = " AS $TARGET" target['ASPPCOMSTR'] = " AS $TARGET" target['ARCOMSTR'] = " AR $TARGET" target['RANLIBCOMSTR'] = " LIB $TARGET" target['LINKCOMSTR'] = " LD $TARGET" target['COPYSTR'] = " COPY $SOURCE => $TARGET" if not host['VERBOSE']:
def main(): """ Zarp entry point """ # set up configuration config.initialize() # set up database database.initialize() # load modules loader = LoadedModules() loader.load() Msg('Loaded %d modules.' % loader.total) # handle command line options first if len(argv) > 1: parse_cmd.parse(argv, loader) # menus main_menu = [ 'Poisoners', 'DoS Attacks', 'Sniffers', 'Scanners', 'Parameter', 'Services', 'Attacks', 'Sessions' ] running = True choice = -1 while running: header() choice = print_menu(main_menu) if choice == 0: # check if they've got running sessions! cnt = stream.get_session_count() if cnt > 0: choice = raw_input( color.YELLOW + 'You have %d sessions running. Are you sure? [Y/n] ' % cnt + color.END) if 'y' in choice.lower() or choice == '': Msg('Shutting all sessions down...') stream.stop_session('all', -1) running = False # recheck that all sessions are down cnt = stream.get_session_count() if cnt <= 0: # some libs dont clean up their own threads, so # we need to hard quit those to avoid hanging; FIXME _exit(1) else: debug("Exiting with session count: %d" % (cnt)) Msg("Exiting...") running = False elif choice == 1: while True: choice = print_menu([x().which for x in loader.poison]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.poison): continue else: stream.initialize(loader.poison[choice - 1]) elif choice == 2: while True: choice = print_menu([x().which for x in loader.dos]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.dos): continue else: stream.initialize(loader.dos[choice - 1]) elif choice == 3: while True: choice = print_menu([x().which for x in loader.sniffers]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.sniffers): continue else: stream.initialize(loader.sniffers[choice - 1]) elif choice == 4: while True: choice = print_menu([x().which for x in loader.scanner]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.scanner): continue else: stream.initialize(loader.scanner[choice - 1]) elif choice == 5: while True: choice = print_menu([x().which for x in loader.parameter]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.parameter): continue else: stream.initialize(loader.parameter[choice - 1]) elif choice == 6: while True: choice = print_menu([x().which for x in loader.services]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.services): continue else: stream.initialize(loader.services[choice - 1]) elif choice == 7: while True: choice = print_menu([x().which for x in loader.attacks]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.attacks): continue else: stream.initialize(loader.attacks[choice - 1]) elif choice == 8: session_manager.menu() elif choice == -1: pass
# # Copyright (c) 2014 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Pixelated. If not, see <http://www.gnu.org/licenses/>. from config import initialize if __name__ == '__main__': initialize()
def _setField(field, value, final=False): for line in fileinput.input('/etc/gram/config.json', inplace=1): if field in line: if not final: line = line.replace(line, ' "' + field + '": "' + value + '",\n') else: line = line.replace(line, ' "' + field + '": "' + value + '"\n') sys.stdout.write(line) if __name__ == "__main__": # Get the namespace name config.initialize('/etc/gram/config.json') ns = _getMgmtNamespace() pub_ip = _getPublicIp(ns) # edit config.json to update the namespace if ns: _setField('mgmt_ns', ns, True) else: print 'Failed to set namespace' # set the public ip address if pub_ip: _setField('public_ip', pub_ip) else: print 'Failed to set public IP address'
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop. """ log.debug("Core starting") try: # Windows >= Vista ctypes.windll.user32.SetProcessDPIAware() except AttributeError: pass import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath = config.getUserDefaultConfigPath( useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info("Config dir: %s" % os.path.abspath(globalVars.appArgs.configPath)) log.debug("loading config") import config config.initialize() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\start.wav") except: pass logHandler.setLogLevelFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s" % lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s" % lang) import versionInfo log.info("NVDA version %s" % versionInfo.version) log.info("Using Windows version %s" % winVersion.winVersionText) log.info("Using Python version %s" % sys.version) log.info("Using comtypes version %s" % comtypes.__version__) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing add-ons system") addonHandler.initialize() if globalVars.appArgs.disableAddons: log.info("Add-ons are disabled. Restart NVDA to enable them.") import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time() - globalVars.startTime) > 5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time() - globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx log.info("Using wx version %s" % wx.version()) class App(wx.App): def OnAssert(self, file, line, cond, msg): message = "{file}, line {line}:\nassert {cond}: {msg}".format( file=file, line=line, cond=cond, msg=msg) log.debugWarning(message, codepath="WX Widgets", stack_info=True) app = App(redirect=False) # We do support QueryEndSession events, but we don't want to do anything for them. app.Bind(wx.EVT_QUERY_END_SESSION, lambda evt: None) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) import braille log.debug("Initializing braille") braille.initialize() log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() import audioDucking if audioDucking.isAudioDuckingSupported(): # the GUI mainloop must be running for this to work so delay it wx.CallAfter(audioDucking.initialize) # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR. # NVDA uses the main frame to check for and quit another instance of NVDA. # To remain compatible with older versions of NVDA, create our own wxWindowClassNR. # We don't need to do anything else because wx handles WM_QUIT for all windows. import windowUtils class MessageWindow(windowUtils.CustomWindow): className = u"wxWindowClassNR" messageWindow = MessageWindow(unicode(versionInfo.name)) # initialize wxpython localization support locale = wx.Locale() lang = languageHandler.getLanguage() wxLang = locale.FindLanguageInfo(lang) if not wxLang and '_' in lang: wxLang = locale.FindLanguageInfo(lang.split('_')[0]) if hasattr(sys, 'frozen'): locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(), "locale")) if wxLang: try: locale.Init(wxLang.Language) except: log.error("Failed to initialize wx locale", exc_info=True) else: log.debugWarning("wx does not support language %s" % lang) import api import winUser import NVDAObjects.window desktopObject = NVDAObjects.window.Window( windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except NotImplementedError: log.warning("UIA not available") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install or globalVars.appArgs.installSilent: import wx import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall, startAfterInstall=not globalVars.appArgs.installSilent) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: gui.LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject # Doing this here is a bit ugly, but we don't want these modules imported # at module level, including wx. log.debug("Initializing core pump") class CorePump(wx.Timer): "Checks the queues and executes functions." def Notify(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: A pump was requested, but the timer was ignored by a modal loop # because timers aren't re-entrant. # Therefore, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True) global _pump _pump = CorePump() requestPump() log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck = None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: _terminate(updateCheck) _terminate(watchdog) _terminate(globalPluginHandler, name="global plugin handler") _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject, "event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass # #5189: Destroy the message window as late as possible # so new instances of NVDA can find this one even if it freezes during exit. messageWindow.destroy() log.debug("core done")
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop. """ log.debug("Core starting") ctypes.windll.user32.SetProcessDPIAware() import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath=config.getUserDefaultConfigPath(useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info("Config dir: %s"%os.path.abspath(globalVars.appArgs.configPath)) log.debug("loading config") import config config.initialize() if not globalVars.appArgs.minimal and config.conf["general"]["playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\start.wav") except: pass logHandler.setLogLevelFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s"%lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s"%lang) import versionInfo log.info("NVDA version %s" % versionInfo.version) log.info("Using Windows version %s" % winVersion.winVersionText) log.info("Using Python version %s"%sys.version) log.info("Using comtypes version %s"%comtypes.__version__) import configobj log.info("Using configobj version %s with validate version %s"%(configobj.__version__,configobj.validate.__version__)) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing add-ons system") addonHandler.initialize() if globalVars.appArgs.disableAddons: log.info("Add-ons are disabled. Restart NVDA to enable them.") import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time()-globalVars.startTime)>5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time()-globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx # wxPython 4 no longer has either of these constants (despite the documentation saying so), some add-ons may rely on # them so we add it back into wx. https://wxpython.org/Phoenix/docs/html/wx.Window.html#wx.Window.Centre wx.CENTER_ON_SCREEN = wx.CENTRE_ON_SCREEN = 0x2 log.info("Using wx version %s"%wx.version()) class App(wx.App): def OnAssert(self,file,line,cond,msg): message="{file}, line {line}:\nassert {cond}: {msg}".format(file=file,line=line,cond=cond,msg=msg) log.debugWarning(message,codepath="WX Widgets",stack_info=True) app = App(redirect=False) # We support queryEndSession events, but in general don't do anything for them. # However, when running as a Windows Store application, we do want to request to be restarted for updates def onQueryEndSession(evt): if config.isAppX: # Automatically restart NVDA on Windows Store update ctypes.windll.kernel32.RegisterApplicationRestart(None,0) app.Bind(wx.EVT_QUERY_END_SESSION, onQueryEndSession) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal and config.conf["general"]["playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav",async=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import braille log.debug("Initializing braille") braille.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() import audioDucking if audioDucking.isAudioDuckingSupported(): # the GUI mainloop must be running for this to work so delay it wx.CallAfter(audioDucking.initialize) # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR. # NVDA uses the main frame to check for and quit another instance of NVDA. # To remain compatible with older versions of NVDA, create our own wxWindowClassNR. # We don't need to do anything else because wx handles WM_QUIT for all windows. import windowUtils class MessageWindow(windowUtils.CustomWindow): className = u"wxWindowClassNR" #Just define these constants here, so we don't have to import win32con WM_POWERBROADCAST = 0x218 WM_DISPLAYCHANGE = 0x7e PBT_APMPOWERSTATUSCHANGE = 0xA UNKNOWN_BATTERY_STATUS = 0xFF AC_ONLINE = 0X1 NO_SYSTEM_BATTERY = 0X80 #States for screen orientation ORIENTATION_NOT_INITIALIZED = 0 ORIENTATION_PORTRAIT = 1 ORIENTATION_LANDSCAPE = 2 def __init__(self, windowName=None): super(MessageWindow, self).__init__(windowName) self.oldBatteryStatus = None self.orientationStateCache = self.ORIENTATION_NOT_INITIALIZED self.orientationCoordsCache = (0,0) self.handlePowerStatusChange() def windowProc(self, hwnd, msg, wParam, lParam): post_windowMessageReceipt.notify(msg=msg, wParam=wParam, lParam=lParam) if msg == self.WM_POWERBROADCAST and wParam == self.PBT_APMPOWERSTATUSCHANGE: self.handlePowerStatusChange() elif msg == self.WM_DISPLAYCHANGE: self.handleScreenOrientationChange(lParam) def handleScreenOrientationChange(self, lParam): import ui import winUser # Resolution detection comes from an article found at https://msdn.microsoft.com/en-us/library/ms812142.aspx. #The low word is the width and hiword is height. width = winUser.LOWORD(lParam) height = winUser.HIWORD(lParam) self.orientationCoordsCache = (width,height) if width > height: # If the height and width are the same, it's actually a screen flip, and we do want to alert of those! if self.orientationStateCache == self.ORIENTATION_LANDSCAPE and self.orientationCoordsCache != (width,height): return #Translators: The screen is oriented so that it is wider than it is tall. ui.message(_("Landscape" )) self.orientationStateCache = self.ORIENTATION_LANDSCAPE else: if self.orientationStateCache == self.ORIENTATION_PORTRAIT and self.orientationCoordsCache != (width,height): return #Translators: The screen is oriented in such a way that the height is taller than it is wide. ui.message(_("Portrait")) self.orientationStateCache = self.ORIENTATION_PORTRAIT def handlePowerStatusChange(self): #Mostly taken from script_say_battery_status, but modified. import ui import winKernel sps = winKernel.SYSTEM_POWER_STATUS() if not winKernel.GetSystemPowerStatus(sps) or sps.BatteryFlag is self.UNKNOWN_BATTERY_STATUS: return if sps.BatteryFlag & self.NO_SYSTEM_BATTERY: return if self.oldBatteryStatus is None: #Just initializing the cache, do not report anything. self.oldBatteryStatus = sps.ACLineStatus return if sps.ACLineStatus == self.oldBatteryStatus: #Sometimes, this double fires. This also fires when the battery level decreases by 3%. return self.oldBatteryStatus = sps.ACLineStatus if sps.ACLineStatus & self.AC_ONLINE: #Translators: Reported when the battery is plugged in, and now is charging. ui.message(_("Charging battery. %d percent") % sps.BatteryLifePercent) else: #Translators: Reported when the battery is no longer plugged in, and now is not charging. ui.message(_("Not charging battery. %d percent") %sps.BatteryLifePercent) messageWindow = MessageWindow(unicode(versionInfo.name)) # initialize wxpython localization support locale = wx.Locale() lang=languageHandler.getLanguage() wxLang=locale.FindLanguageInfo(lang) if not wxLang and '_' in lang: wxLang=locale.FindLanguageInfo(lang.split('_')[0]) if hasattr(sys,'frozen'): locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(),"locale")) # #8064: Wx might know the language, but may not actually contain a translation database for that language. # If we try to initialize this language, wx will show a warning dialog. # Therefore treat this situation like wx not knowing the language at all. if not locale.IsAvailable(wxLang.Language): wxLang=None if wxLang: try: locale.Init(wxLang.Language) except: log.error("Failed to initialize wx locale",exc_info=True) else: log.debugWarning("wx does not support language %s" % lang) import api import winUser import NVDAObjects.window desktopObject=NVDAObjects.window.Window(windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except NotImplementedError: log.warning("UIA not available") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install or globalVars.appArgs.installSilent: import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall,startAfterInstall=not globalVars.appArgs.installSilent) elif globalVars.appArgs.portablePath and (globalVars.appArgs.createPortable or globalVars.appArgs.createPortableSilent): import gui.installerGui wx.CallAfter(gui.installerGui.doCreatePortable,portableDirectory=globalVars.appArgs.portablePath, silent=globalVars.appArgs.createPortableSilent,startAfterCreate=not globalVars.appArgs.createPortableSilent) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: gui.LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject # Doing this here is a bit ugly, but we don't want these modules imported # at module level, including wx. log.debug("Initializing core pump") class CorePump(gui.NonReEntrantTimer): "Checks the queues and executes functions." def run(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: Another pump was requested during this pump execution. # As our pump is not re-entrant, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True) global _pump _pump = CorePump() requestPump() log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck=None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") postNvdaStartup.notify() log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: _terminate(updateCheck) _terminate(watchdog) _terminate(globalPluginHandler, name="global plugin handler") _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject,"event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) if not globalVars.appArgs.minimal and config.conf["general"]["playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav",async=False) except: pass # #5189: Destroy the message window as late as possible # so new instances of NVDA can find this one even if it freezes during exit. messageWindow.destroy() log.debug("core done")
import config import open_stack_interface import manage_ssh_proxy import optparse parser = optparse.OptionParser() parser.add_option("--config", help="JSON config file", default="/etc/gram/config.json") [opts, slices] = parser.parse_args() if len(slices) < 1 : print 'Usage: cleanup [--config configfile] <slicename>...<slicename>' sys.exit(0) config.initialize(opts.config) tenant_pwd = config.tenant_admin_pwd for slice in slices: print 'Cleaning up slice %s' % slice if ':' in slice: tenant_name = slice # Assume it is a URN else: tenant_name = 'geni:gpo:gcf+slice+' + slice tenant_admin = 'admin-' + tenant_name # Figure out the uuid of this tenant
print "Checking that all ports defined on br-int are associated with quantum/neutron ports" # Get list of all currently defined quantum/neutron ports port_data = osi._getPortsForTenant(None) short_port_names = {} for port_name in port_data.keys(): short_name = port_name[:11] short_port_names[short_name] = port_name # print short_port_names # print port_data hosts = osi._listHosts(onlyForService='compute') for host in hosts: switch_data = compute_node_command(host, ComputeNodeInterfaceHandler.COMMAND_OVS_OFCTL); switch_data_lines = switch_data.split('\n') for i in range(len(switch_data_lines)): line = switch_data_lines[i] if line.find('qvo') >= 0: line_parts = line.split('(') port_name_part = line_parts[1] port_name = port_name_part.split(')')[0] short_name = port_name[3:] print port_name + " " + host + " *** " if __name__ == "__main__": config.initialize('/etc/gram/config.json') check_openstack_consistency() check_port_consistency()
def main(): """ Zarp entry point """ # set up configuration config.initialize() # set up database database.initialize() # load modules loader = LoadedModules() loader.load() util.Msg('Loaded %d modules.' % loader.total) # handle command line options first if len(argv) > 1: parse_cmd.parse(argv, loader) # menus main_menu = ['Poisoners', 'DoS Attacks', 'Sniffers', 'Scanners', 'Parameter', 'Services', 'Attacks', 'Sessions'] running = True choice = -1 while running: util.header() choice = util.print_menu(main_menu) if choice == 0: # check if they've got running sessions! cnt = stream.get_session_count() if cnt > 0: display = color.B_YELLOW + 'You have %d sessions running. ' + \ 'Are you sure? ' + color.B_GREEN + '[' + color.B_YELLOW + \ 'Y' + color.B_GREEN + '/' + color.B_YELLOW + 'n' + \ color.B_GREEN + '] ' + color.END choice = raw_input(display % cnt) if 'y' in choice.lower() or choice == '': util.Msg('Shutting all sessions down...') stream.stop_session('all', -1) running = False else: util.debug("Exiting with session count: %d" % (cnt)) util.Msg("Exiting...") running = False # remove zarp temporary directory util.init_app('rm -fr /tmp/.zarp/') # recheck that all sessions are down cnt = stream.get_session_count() if cnt <= 0: # some libs dont clean up their own threads, so # we need to hard quit those to avoid hanging; FIXME _exit(1) elif choice == 1: while True: choice = util.print_menu([x().which for x in loader.poison]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.poison): continue else: stream.initialize(loader.poison[choice - 1]) elif choice == 2: while True: choice = util.print_menu([x().which for x in loader.dos]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.dos): continue else: stream.initialize(loader.dos[choice - 1]) elif choice == 3: while True: choice = util.print_menu([x().which for x in loader.sniffers]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.sniffers): continue else: stream.initialize(loader.sniffers[choice - 1]) elif choice == 4: while True: choice = util.print_menu([x().which for x in loader.scanner]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.scanner): continue else: stream.initialize(loader.scanner[choice - 1]) elif choice == 5: while True: choice = util.print_menu([x().which for x in loader.parameter]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.parameter): continue else: stream.initialize(loader.parameter[choice - 1]) elif choice == 6: while True: choice = util.print_menu([x().which for x in loader.services]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.services): continue else: stream.initialize(loader.services[choice - 1]) elif choice == 7: while True: choice = util.print_menu([x().which for x in loader.attacks]) if choice == 0: break elif choice == -1: pass elif choice > len(loader.attacks): continue else: stream.initialize(loader.attacks[choice - 1]) elif choice == 8: session_manager.menu() elif choice == -1: pass
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and installs the core pump timer, which checks the queues and executes functions every 1 ms. Finally, it starts the wx main loop. """ log.debug("Core starting") try: # Windows >= Vista ctypes.windll.user32.SetProcessDPIAware() except AttributeError: pass import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath = config.getUserDefaultConfigPath( useInstalledPathIfExists=globalVars.appArgs.launcher ) # Initialize the config path (make sure it exists) config.initConfigPath() log.info("Config dir: %s" % os.path.abspath(globalVars.appArgs.configPath)) log.debug("loading config") import config config.initialize() if not globalVars.appArgs.minimal: try: nvwave.playWaveFile("waves\\start.wav") except: pass logHandler.setLogLevelFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s" % lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s" % lang) import versionInfo log.info("NVDA version %s" % versionInfo.version) log.info("Using Windows version %r" % (sys.getwindowsversion(),)) log.info("Using Python version %s" % sys.version) log.info("Using comtypes version %s" % comtypes.__version__) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing addons system.") addonHandler.initialize() import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time() - globalVars.startTime) > 5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time() - globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx log.info("Using wx version %s" % wx.version()) app = wx.App(redirect=False) # HACK: wx currently raises spurious assertion failures when a timer is stopped but there is already an event in the queue for that timer. # Unfortunately, these assertion exceptions are raised in the middle of other code, which causes problems. # Therefore, disable assertions for now. app.SetAssertMode(wx.PYAPP_ASSERT_SUPPRESS) # We do support QueryEndSession events, but we don't want to do anything for them. app.Bind(wx.EVT_QUERY_END_SESSION, lambda evt: None) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) import braille log.debug("Initializing braille") braille.initialize() log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() # initialize wxpython localization support locale = wx.Locale() lang = languageHandler.getLanguage() if "_" in lang: wxLang = lang.split("_")[0] else: wxLang = lang if hasattr(sys, "frozen"): locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(), "locale")) try: locale.Init(lang, wxLang) except: pass import api import winUser import NVDAObjects.window desktopObject = NVDAObjects.window.Window(windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except NotImplementedError: log.warning("UIA not available") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install: import wx import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: gui.LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject class CorePump(wx.Timer): "Checks the queues and executes functions." def __init__(self, *args, **kwargs): log.debug("Core pump starting") super(CorePump, self).__init__(*args, **kwargs) def Notify(self): try: JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.alive() log.debug("starting core pump") pump = CorePump() pump.Start(1) log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck = None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: _terminate(updateCheck) _terminate(watchdog) _terminate(globalPluginHandler, name="global plugin handler") _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject, "event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) if not globalVars.appArgs.minimal: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass log.debug("core done")
network.emit_configuration() except e: print(e) _emit_component_configurations('core') _emit_component_configurations('components', components=components) if outfile: with open(outfile, 'w') as ofile: print(config.template.to_json(), file=ofile) else: print(config.template.to_json()) if __name__ == '__main__': arg_parser = _create_parser() args = arg_parser.parse_args() print('Creating cloudformation template using config file: {0} '.format(args.config), file=sys.stderr) if args.config: print("Initializing with external YAML configuration", file=sys.stderr) with open(args.config, 'r') as yfile: ymlfile = yaml.load(yfile) config.initialize(ymlfile) else: raise Exception("You must supply a configuration file that includes the 'components' field") generate_cloudformation_template(args.outfile, ymlfile["components"])