def exit(self): try: self.client.stopListening() except: pass os.environ['JYTHON_RUNNING'] = 'NO' System.exit(0)
def quit(self, event=None): ''' 1. Check if file has unsaved changes 2. Exit ''' if self.handleUnsaved(): System.exit(0)
def run(self): b, s = (Bindings(), Show()) global w w = gfxapi.createWindow() # w.setLocation(0,0,1600,1200) w.setLocation(0, 0, 1024, 768) scr = vob.Screen(w, b, s) try: if loop: while 1: try: loadScenes() except SnapshotLoop: print "Continuing" continue break else: loadScenes() except: typ, val, tra = sys.exc_info() l = traceback.format_list(traceback.extract_tb(tra)) print "ERROR WHILE LOAD/EXEC! %s\n%s\n" % (str(typ), str(val)), l System.exit(0) vob.AbstractUpdateManager.addWindow(scr) vob.AbstractUpdateManager.chg()
def exit(self): try: self.client.stopListening() except: pass os.environ["JYTHON_RUNNING"] = "NO" System.exit(0)
def login(): fixFormPanelResourceLoader() login = LoginDialog() login.showDialog("Login") if login.cancelled(): System.exit(1)
def keystroke(self, s): global showHelp, currentScene # print "KEY: '%s'"%s if usingNormalBindings: if s == "q" or s == "Q" or s == "Ctrl-Q": System.exit(43) elif s == "r" or s == "R" or s == "Ctrl-R": loadScenes() elif s == "?": showHelp = 1-showHelp vob.AbstractUpdateManager.setNoAnimation() elif globalSceneMap.has_key(s): currentScene = globalSceneMap[s] vob.AbstractUpdateManager.setNoAnimation() showHelp = 0 elif not globalkey(s): logger.key(currentScene, s) #currentScene.key(s) else: if s == "Ctrl-R": loadScenes() elif currentScene: logger.key(currentScene, s) #currentScene.key(s) elif s == "Ctrl-Q": System.exit(43) if not chgAfterKeyEvent: return vob.AbstractUpdateManager.chg()
def main(): """ The main entry point for the discoverDomain tool. :param args: the command-line arguments """ _method_name = 'main' __logger.entering(class_name=_class_name, method_name=_method_name) for index, arg in enumerate(sys.argv): __logger.finer('sys.argv[{0}] = {1}', str(index), str(arg), class_name=_class_name, method_name=_method_name) _outputdir = None try: model_context = __process_args(sys.argv, __logger) _outputdir = model_context.get_kubernetes_output_dir() model1 = model_context.get_model_file() # for f in [ model1 ]: # if not os.path.exists(f): # raise CLAException("Model %s does not exists" % f) # if os.path.isdir(f): # raise CLAException("Model %s is a directory" % f) obj = PrepareModel(model1, model_context, __logger, _outputdir) rc = obj.walk() System.exit(rc) except CLAException, ex: exit_code = 2 if exit_code != CommandLineArgUtil.HELP_EXIT_CODE: __logger.severe('WLSDPLY-20008', _program_name, ex.getLocalizedMessage(), error=ex, class_name=_class_name, method_name=_method_name) cla_helper.clean_up_temp_files() sys.exit(exit_code)
def shutdown(): logger.debug('Cleaning up traced instances') _cleanup() c_call(None, 'terminus') if jython: from java.lang import System # @UnresolvedImport System.exit(0)
def keystroke(self, s): global showHelp, currentScene # print "KEY: '%s'"%s if s == "Ctrl-Q": System.exit(43) elif s == "Ctrl-R": loadScenes() else: vob.putil.usertestutil._key(s)
def __init__(self, jsonFilePath): self.filePath = jsonFilePath checkFile = File(self.filePath) if not checkFile.isFile(): self.CMUConfigParserLogger.infoMessage( '__init__', 'Unable to find file: %s' % jsonFilePath) System.exit(1)
def dieNow(): import sys,traceback e=sys.exc_info() # All bets are off d_log("Failed to execute:",str(e)) print >> sys.stderr, traceback.format_exc(e) # no point wasting time trying to continue # TODO dump stack traces of all threads in a nice # way when this happens. System.exit(1)
def __init__(self, pathToJSON, serverType): try: clientManager = IdcClientManager() idcConnectionURL = "idc://%s:4444" % CMUConfigParser(pathToJSON).returnObject(serverType, "hostname").split(":")[0] instanceName = CMUConfigParser(pathToJSON).returnObject(serverType, "instance") Username = CMUConfigParser(pathToJSON).returnObject(serverType, "username") Password = CMUConfigParser(pathToJSON).returnObject(serverType, "password") except Exception, err: self.SetupUCMConnectionLogger.infoMessage('__init__', 'Unable to read config file: %s' % err) System.exit(1)
def quit(self, event): ''' 1. Check if file has unsaved changes 2. Exit ''' if self.handleUnsaved(): self.log("NammuController: Exiting...") self.log(" OK\n") self.log("Bye! :)") System.exit(0)
def run(self): global ThePaperMill, w from vob.paper.papermill import ThePaperMill # w = gfxapi.createWindow() # pbuffer w = gfxapi.createStableOffscreen(1536, 1536) #w.setLocation(0,0,384,384) vs = w.createVobScene() print "Working directory:", basedir if not loop: for seed in sys.argv[1:]: genBgFileFromSeed(w, vs, long(seed), jpeg) else: print """ Entering into looping server mode. Requests will be read from foo.request files within directory %s. Please, replace foo with some 64bit integer value. """ % (basedir) sleep = 0 while 1: requests = listdir(basedir, 'request') tmp = open(basedir + 'bgfilegen.watchdog', 'w') tmp.close() if len(requests) > 0: sleep = 0 for seed in requests: if seed.find('-') != -1: id = seed.split('.')[0] scale = id.split('-')[1].split('x')[0] filepath = genBgFileFromSeed( w, vs, long(id.split('-')[0]), jpeg, int(scale)) else: filepath = genBgFileFromSeed( w, vs, long(seed.split('.')[0]), jpeg) if notify: os.system(notify + ' ' + filepath \ + ' ' + seed.split('.')[0]) os.system('rm ' + basedir + seed) else: if not sleep: print time.strftime('%y/%m/%d %H:%M:%S'), \ "No more requests, sleeping..." sleep = 1 time.sleep(1) if os.path.isfile(basedir + 'stop_bgfilegen'): print time.strftime('%y/%m/%d %H:%M:%S'), "Exiting..." break System.exit(0)
def run(self): before_time = None after_time = None time_diff = None sleep_time = None over_sleep_time = 0 no_delays = 0 excess = 0 game_start_time = System.nanoTime() prev_stats_time = game_start_time before_time = game_start_time running = True while running: self.game_update() self.game_render() self.paint_screen() after_time = System.nanoTime() time_diff = after_time - before_time sleep_time = (self.period - time_diff) - over_sleep_time if sleep_time > 0: try: Thread.sleep(sleep_time) except InterruptedException as e: pass over_sleep_time = (System.nanoTime() - after_time) - sleep_time else: excess -= sleep_time over_sleep_time = 0 if (no_delays + 1) >= self.NO_DELAYS_PER_YIELD: Thread.yield() no_delays = 0 before_time = System.nanoTime() skips = 0 while excess > self.period and skips < self.MAX_FRAME_SKIPS: excess -= self.period self.game_update() skips += 1 self.frames_skipped += skips self.store_stats() self.print_stats() System.exit(0)
def start_config(self): os_name = System.getProperty('os.name') self.os_sep = File.separator self.has_dir = True self.ticks = 30 #default self.first_start = False self.has_started = False app_name = 'Yay' filename = 'config.pkl' LOG.debug('Operating System: %s.' % os_name) if os_name.find('Windows') != -1: self.config_dir = os.environ["APPDATA"] + self.os_sep + app_name + self.os_sep self.os = 'win' else: self.config_dir = os.path.expanduser("~") + self.os_sep + '.' + app_name + self.os_sep self.os = 'other' self.config_path = self.config_dir + filename #'server_config.ini' self.dir = '' if not os.path.exists(self.config_dir): self.first_start = True os.makedirs(self.config_dir) self.has_dir = False self.create_config_file() else: try: f = open(self.config_path,'rb') except IOError: LOG.debug('Config file doesn\'t exist, creating it.') self.first_start = True self.create_config_file() self.dir = self.get_config('browse_folder') self.ticks = self.get_config('speed') if self.dir == '': ## this should be a dialog alert... LOG.debug('Exitting program.') #sys.exit() System.exit(0) else: LOG.debug('Image folder: %s.' % self.dir) self._stopevent = threading.Event() self._sleepperiod = 1.0 threading.Thread.__init__(self,name='GoGo') self.file_count = 0; self.countsec = 0 self.is_paused = True self.loadup() self.last_off() self.updateLabel()
def checkAssetExists(self, WebAssetList, serverData, noSkip=True): if noSkip: self.GeneralHandlerLogger.infoMessage( 'checkAssetExists', 'Starting checkAssetExists method with params: [WebAssetList: %s] [noSkip: %s]' % (WebAssetList, noSkip)) safeItemList = [] checkClient = serverData[0] checkUserContext = serverData[1] checkServerInfo = serverData[2] checkServerInstance = serverData[3] for eachWebAsset in WebAssetList.split(','): if "|" in eachWebAsset: webAssetName = eachWebAsset.split('|')[0] webAssetRevision = eachWebAsset.split('|')[1] try: checkDataBinder = checkClient.createBinder() checkDataBinder.putLocal('IdcService', 'DOC_INFO_SIMPLE_BYREV') checkDataBinder.putLocal('dDocName', webAssetName) checkDataBinder.putLocal('dRevLabel', webAssetRevision) serverResponse = checkClient.sendRequest( checkUserContext, checkDataBinder) responseData = serverResponse.getResponseAsBinder() for eachDocRow in responseData.getResultSet( "DOC_INFO").getRows(): if eachDocRow.get('dDocName'): safeItemList.append( '%s|%s' % (webAssetName, webAssetRevision)) except ServiceException, err: if noSkip: self.GeneralHandlerLogger.infoMessage( 'checkAssetExists', 'Unable to get information about document %s with revision %s. Check document name spelling. Error: [%s]' % (webAssetName, webAssetRevision, err)) except Exception, err: self.GeneralHandlerLogger.infoMessage( 'checkAssetExists', 'Unable to get information about document %s. Error: [%s]' % (webAssetName, err)) System.exit(1) else: self.GeneralHandlerLogger.infoMessage( 'checkAssetExists', 'Found %s. With revision %s.' % (webAssetName, webAssetRevision))
def main(): try: obj = ModelFileDiffer(sys.argv[1], sys.argv[2]) rc = obj.compare() rcfh = open('/tmp/model_diff_rc', 'w') rcfh.write(",".join(map(str, changed_items))) rcfh.close() System.exit(0) except: exc_type, exc_obj, exc_tb = sys.exc_info() eeString = traceback.format_exception(exc_type, exc_obj, exc_tb) print eeString System.exit(-1)
def encrypt_file(clear_text, password, outputfile): try: pwd = String(password) x = EncryptionUtils.encryptString(clear_text, pwd.toCharArray()) encrypted_text = String(x) fh = open(outputfile, "w") fh.write(str(encrypted_text)) fh.close() System.exit(0) except EncryptionException, e: # Catch the exact exception to get the real cause trace("SEVERE", "Error in encrypting file: %s" % e.getCause()) System.exit(-1)
def getPassphrase(self, arg1, arg2=None): print("@getPassphrase(%s,%s) will return %s" % (arg1, arg2, self.theKey)) if self.passwordCalls: print( "@@ Second call to getPassphrase()... Assuming bad password, so aborting....." ) System.exit(0) # this stops the popup message and infinite loop... self.passwordCalls += 1 return self.theKey
def encrypt_file(clear_text, password, outputfile): try: pwd = String(password) x = EncryptionUtils.encryptString(clear_text, pwd.toCharArray()) encrypted_text = String(x) fh = open(outputfile, "w") fh.write(str(encrypted_text)) fh.close() System.exit(0) except: exc_type, exc_obj, exc_tb = sys.exc_info() eeString = traceback.format_exception(exc_type, exc_obj, exc_tb) print eeString System.exit(-1)
def __init__(self, pathToJSON): self.pathToJSON = pathToJSON try: print "================================" sourceServerData = SetupUCMConnection(self.pathToJSON, 'sourceServer') self.sourceClient = sourceServerData.outData[0] self.sourceUserContext = sourceServerData.outData[1] self.sourceServerInfo = sourceServerData.outData[2] except Exception, err: self.GeneralHandlerLogger.infoMessage( '__init__', 'Unable to get information about source server: %s' % err) System.exit(1)
def quit(self, event): ''' 1. Check if file has unsaved changes 2. Exit ''' self.handleUnsaved() self.consoleController.addText("NammuController: Exiting...") self.consoleController.addText(" OK\n") self.consoleController.addText("Bye! :)") System.exit(0)
def main(args): import traceback _method_name = 'main' generator_wlst.wlst_functions = globals() __logger.entering(class_name=CLASS_NAME, method_name=_method_name) system_exit = 0 kwargs = all_utils.kwargs_map(args) all_utils.populate_test_files_location(kwargs) # all_utils.setup_logger_overrides(__logger) all_utils.set_domain_home_arg(kwargs, domain_home) offline_model_context = all_utils.populate_model_context( 'generate_offline', WlstModes.OFFLINE, kwargs) try: generator_wlst.wlst_silence() offline_dictionary = generate_offline(offline_model_context, get_dictionary()) if len(offline_dictionary) == 0: __logger.severe('Nothing generated in online - ending with rc={0}', system_exit, class_name=CLASS_NAME, method_name=_method_name) System.exit(1) except: __logger.severe('Unhandled exception occurred', system_exit, class_name=CLASS_NAME, method_name=_method_name) print dir(traceback) traceback.print_exc() System.exit(2) __logger.exiting(class_name=CLASS_NAME, method_name=_method_name) System.exit(0)
def runPurge(self,partition,jobId,workDir): global purgeStatus purgeThread = JobThread(partition,jobId,workDir) purgeThread.setName('Purge Client Thread partition ' + str(partition.getId())) purgeThread.setDaemon(False) purgeThread.start() start = time.time() while True: # check for hang every hangCheckInterval minutes purgeThread.join(self.hangCheckInterval * 60) if purgeThread.isAlive(): diff = time.time() - start if diff > self.timeout: log('Purge: timed out after',diff,'seconds waiting for purge to complete for partition',partition.getId(),'and purge id',jobId) System.exit(99) if self.isHung(): log('Purge: timed out after',diff,'seconds because hang detected for partition',partition.getId(),'and purge id',jobId) System.exit(99) else: # see EMSDEV-10100 if purgeStatus is ps_SHOULDDELETE: log('Purge: detected previous graceful failure. Clearing job dir for partition',partition.getId(),'due to purge id',jobId) self.clearJobDirectory(workDir) System.exit(99) diff = time.time() - start print time.asctime(),'Purge completed for partition',partition.getId(),'in',diff,'seconds' # expecting a boolean to be returned rc = None if purgeStatus == ps_SUCCESS: rc = True else: rc = False purgeStatus = None return rc
def run(self): main.running = 1 # attempt to install a shutdown hook #if hasattr(java.lang.Runtime, 'addShutdownHook'): # shutdownThread = java.lang.Thread(RunShutdown()) # java.lang.Runtime.getRuntime().addShutdownHook(shutdownThread) while 1: # run the delayeds timeout = None for delayed in main.delayeds: delayed.runUntilCurrent() newTimeout = delayed.timeout() if ((newTimeout is not None) and ((timeout is None) or (newTimeout < timeout))): timeout = newTimeout # wait at most `timeout` seconds for action to be added to queue try: self.q.wait(timeout) except timeoutqueue.TimedOut: pass # run actions in queue for i in range(self.q.qsize()): meth, arg = self.q.get() meth(arg) # check if we should shutdown if not main.running: for callback in main.shutdowns: try: callback() except: traceback.print_exc(file=log.logfile) System.exit(0)
def returnObject(self, objectStructure, objectType, objectParams=False, noSkip=True): reader = FileReader(self.filePath) jsonParser = JSONParser() jsonObject = jsonParser.parse(reader) try: structure = jsonObject.get(objectStructure) if not structure: raise Exception except: self.CMUConfigParserLogger.infoMessage( 'returnObject', "Unable to find structure: %s in JSON file." % objectStructure) System.exit(1) try: returnObject = structure.get(objectType) except: self.CMUConfigParserLogger.infoMessage( 'returnObject', "Unable to find value %s in structure %s" % (objectStructure, objectType)) else: if objectParams: try: returnObjectParam = returnObject.get(objectParams) except: self.CMUConfigParserLogger.infoMessage( 'returnObject', "Unable to find param %s in value %s in structure %s" % (objectParams, objectStructure, objectType), noSkip) else: return returnObjectParam else: return returnObject
def main(self): while True: dir = None try: mc = ManagementContainer.getInstance() pm = mc.getPartitionManager() partitions = pm.getLocalPartitions() if partitions is not None: for p in pm.getLocalPartitions(): dir = os.path.join(self.publishDir,str(p.getId())) log('Checking for work in',dir) self.checkForJob(dir) else: log('There are no local partitions defined for this server') System.exit(0) except Error: if dir is not None: self.clearJobDirectory(dir) # let's restart log('Exception caught in main loop is ERROR. Exiting.',sys.exc_info(),traceback.print_exc(file=sys.stderr)) System.exit(99) except Exception: log('Exception caught in main loop',sys.exc_info(),traceback.print_exc(file=sys.stderr))
class SetupUCMConnection: """ Object: SetupUCMConnection Requires: path to configuration file, type of server (source/target or whatever is defined in JSON) returns: list of objects [client, userContext, serverInfo, instanceName] cleint = clientManager to server userContext = username/password serverInfo = hostname / username / password instanceName = content server name """ SetupUCMConnectionLogger = log4j("SetupUCMConnection") def __init__(self, pathToJSON, serverType): try: clientManager = IdcClientManager() idcConnectionURL = "idc://%s:4444" % CMUConfigParser(pathToJSON).returnObject(serverType, "hostname").split(":")[0] instanceName = CMUConfigParser(pathToJSON).returnObject(serverType, "instance") Username = CMUConfigParser(pathToJSON).returnObject(serverType, "username") Password = CMUConfigParser(pathToJSON).returnObject(serverType, "password") except Exception, err: self.SetupUCMConnectionLogger.infoMessage('__init__', 'Unable to read config file: %s' % err) System.exit(1) client = clientManager.createClient(idcConnectionURL) userContext = IdcContext(Username, Password) serverInfo = "Hostname: %s, user name: %s, password: %s" % (idcConnectionURL, Username, Password) try: dataBinder = client.createBinder() dataBinder.putLocal("IdcService", "PING_SERVER") serverResponse = client.sendRequest(userContext, dataBinder) responseData = serverResponse.getResponseAsBinder() except ProtocolException, err: self.SetupUCMConnectionLogger.infoMessage('__init__', 'Unable to initialize socket connection to Content Server. %s [%s]' % (serverInfo, err)) for stackTrace in err.getStackTrace(): print stackTrace #print dir(err) System.exit(1)
def main(args): """ Entry point for generate_online :param args: kwargs from the command line """ import traceback _method_name = 'main' generator_wlst.wlst_functions = globals() generator_wlst.connect('weblogic', 'welcome1', 't3://localhost:7001') ls_list = generator_wlst.lsc() print ls_list generator_wlst.disconnect() __logger.entering(class_name=CLASS_NAME, method_name=_method_name) system_exit = 0 kwargs = all_utils.kwargs_map(args) all_utils.populate_test_files_location(kwargs) # all_utils.setup_logger_overrides(__logger) online_model_context = all_utils.populate_model_context( 'generate_online', WlstModes.ONLINE, kwargs) try: generator_wlst.wlst_silence() online_dictionary = generate_online(online_model_context) if len(online_dictionary) == 0: __logger.severe('Nothing generated in online - ending with rc={0}', system_exit, class_name=CLASS_NAME, method_name=_method_name) System.exit(1) except: __logger.severe('Unhandled exception occurred', system_exit, class_name=CLASS_NAME, method_name=_method_name) print dir(traceback) traceback.print_exc() System.exit(2) __logger.exiting(class_name=CLASS_NAME, method_name=_method_name) System.exit(0)
def windowClosed(self, evt): import java.lang.System as System System.exit(0)
def onQuit(self, e): System.exit(0)
def close(self, event): System.exit(0)
def onQuit(self, e): System.exit(0) def onJocl(self, e):
class __launcher(object): @staticmethod def create(name="Launcher", bundle=[], platforms=["mac", "win"], outdir="dist.platforms", ignorelibs=["*video*"]): """Creates a launcher for the given platform""" import jycessing.Runner as Runner import jycessing.launcher.StandaloneSketch as StandaloneSketch import sys # Check if we should bail out - we're not running from a standalone sketch if not isinstance(Runner.sketch, StandaloneSketch): print >> sys.stderr, "Don't use launcher.create() from processing - use the export button instead!" return # Check if we are already deployed. In that case, # don't do anything if "--internal" in sys.argv: return # Our own imports import jycessing.launcher.LaunchHelper as LaunchHelper import java.lang.System as System import java.nio.file.Paths as Paths import os, shutil, zipfile, inspect, stat, glob, errno main = System.getProperty("python.main") mainroot = System.getProperty("python.main.root") outdir = mainroot + "/" + outdir # Clean the outdir ... try: shutil.rmtree(outdir) except: pass def copyeverything(src, dst): """The Machine That Copies EVERYTHING. https://www.youtube.com/watch?v=ibEdgQJEdTA """ import shutil, errno try: shutil.copytree(src, dst) except OSError as exc: if exc.errno == errno.ENOTDIR: shutil.copy(src, dst) else: raise def copyjars(root): """Copy jars & co""" sketch = Runner.sketch _mainjar = sketch.getMainJarFile() mainjar, mainjarname = _mainjar.getAbsolutePath( ), _mainjar.getName() shutil.copyfile(mainjar, root + "/" + mainjarname) libraries = sketch.getLibraryDirectories() for lib in libraries: shutil.copytree(lib.getPath(), root + "/libraries", ignore=shutil.ignore_patterns(*ignorelibs)) def copydata(runtimedir): """Copy the main script and the given data""" # Create runtime directory try: os.mkdir(runtimedir) except: pass # Copy bundled files for data in bundle: for f in list(glob.iglob(mainroot + "/" + data)): copyeverything(f, runtimedir + "/" + f.replace(mainroot, "")) # Eventually copy the main file shutil.copyfile(main, runtimedir + "/sketch.py") # ... and recreate it os.mkdir(outdir) for platform in platforms: pdir = outdir + "/" + platform tmpfile = pdir + ".zip" os.mkdir(pdir) # Copy archive LaunchHelper.copyResourceTo("launcher." + platform + ".zip", Paths.get(tmpfile)) # Unzip z = zipfile.ZipFile(tmpfile, "r") z.extractall(pdir) z.close() # Try to remove the platform file we created try: os.remove(tmpfile) except Exception, e: print( "Could not remove %s we used for creating the launcher. Please report." % tmpfile, e) # Now the platform specific logic if "mac" in platforms: root = outdir + "/mac/Processing.app/Contents/" # Set launcher permissions ... mmhm, when created on Windows this # might lead to trouble ... Any ideas? mode = os.stat(root + "/MacOS/JavaAppLauncher").st_mode os.chmod(root + "/MacOS/JavaAppLauncher", mode | stat.S_IXUSR) # Copy the jars and app copyjars(root + "Java") copydata(root + "/Runtime") # Adjust Info.plist # TODO os.rename(outdir + "/mac/Processing.app", outdir + "/mac/" + name + ".app/") if "win" in platforms: root = outdir + "/win/" # Copy the jars and app copyjars(root) copydata(root + "/runtime") os.mkdir(root + "/jre/") JREREADME = open(root + "/jre/README.txt", "w") JREREADME.write( "In the future, you can place your JRE in here (not implemented yet)." ) JREREADME.close() # Adjust the launcher.ini # TODO # delete the console version (for now) os.remove(root + "/launcherc.exe") os.rename(root + "/launcher.exe", root + "/" + name.lower() + ".exe") os.rename(root + "/launcher.ini", root + "/" + name.lower() + ".ini") # We dont want to return System.exit(0)
def closeProgram(self): JESConfig.getInstance().writeConfig() self.pluginInstaller.cleanUp() System.exit(0)
def windowClosing(self, event): w = event.getWindow() w.setVisible(0) w.dispose() System.exit(0)
def outputExternalHttpList(self): mainDataBinder = self.sourceClient.createBinder() mainDataBinder.putLocal('IdcService', 'SS_GET_SITE_REPORT') mainDataBinder.putLocal('siteId', 'kanal1') mainDataBinder.putLocal('sitesList', '7') serverResponse = self.sourceClient.sendRequest(self.sourceUserContext, mainDataBinder) responseData = serverResponse.getResponseAsBinder() webPathList = [] for serverComp in responseData.getResultSet("SiteHierarchy").getRows(): webPathList.append(serverComp.get("namePath")) print serverComp.get("namePath") System.exit(1) websiteItemList = [] for serverComp in responseData.getResultSet("WebsiteDocs").getRows(): websiteItemList.append( serverComp.get("dDocName").encode('ascii', 'ignore')) externalHttpList = {} for serverComp in responseData.getResultSet("NodeInfo").getRows(): if 'http' in serverComp.get("primaryUrl"): externalHttpList[serverComp.get( "primaryUrl")] = serverComp.get("nodeId").encode( 'ascii', 'ignore') for key, value in externalHttpList.items(): for serverComp in responseData.getResultSet( "SiteHierarchy").getRows(): if serverComp.get("nodeId") == value: externalHttpList[ key] = 'http://www.swedbank.com/%s' % serverComp.get( "namePath") break for key, value in externalHttpList.items(): print "%s -> %s" % (value, key) for eachWebFile in websiteItemList: mainDataBinder = self.sourceClient.createBinder() mainDataBinder.putLocal('IdcService', 'DOC_INFO_BY_NAME') mainDataBinder.putLocal('dDocName', eachWebFile) serverResponse = self.sourceClient.sendRequest( self.sourceUserContext, mainDataBinder) responseData = serverResponse.getResponseAsBinder() for serverComp in responseData.getResultSet("DOC_INFO").getRows(): fileExtension = serverComp.get("dExtension").lower() fileObjectType = serverComp.get("xWebsiteObjectType").lower() if fileExtension == "xml" or fileExtension == "hcsp": if fileObjectType != "native document": fileGroup = serverComp.get("dSecurityGroup").lower() fileObjectType = "documents" fileDocType = serverComp.get("dDocType").lower() fileName = serverComp.get("dDocName").lower() if len((serverComp.get("dDocAccount").lower() ).split('/')) > 1: fileAccount = '@' + '/@'.join( (serverComp.get("dDocAccount").lower() ).split('/')) filePath = "/sb/sys/ucm/shared/contrib/weblayout/groups/%s/%s/%s/%s/%s.%s" % ( fileGroup, fileAccount, fileObjectType, fileDocType, fileName, fileExtension) else: filePath = "/sb/sys/ucm/shared/contrib/weblayout/groups/%s/%s/%s/%s.%s" % ( fileGroup, fileObjectType, fileDocType, fileName, fileExtension) if not File(filePath).exists(): print '============> DOES NOT EXIST: ', filePath else: openFile = open(filePath, 'r') iframeURLS = [] for eachLine in openFile: if 'iframe' in eachLine: #dataFileContent = open(filePath, 'r').read().encode('ascii', 'ignore') #iframeRegex = re.compile(r'src=(.*?)>\|^', re.IGNORECASE) #for eachFoundRegex in re.findall(iframeRegex, dataFileContent): iframeURLS.append(eachLine) if len(iframeURLS) > 0: print 'Found IFRAMES in file %s: ' % eachWebFile print iframeURLS
def onQuit(self, e): System.exit(0) if __name__ == '__main__':
def exit(): """quits the application""" System.exit(0)
def main(): """ The main entry point for the discoverDomain tool. :param args: the command-line arguments """ _method_name = 'main' _logger.entering(class_name=_class_name, method_name=_method_name) for index, arg in enumerate(sys.argv): _logger.finer('sys.argv[{0}] = {1}', str(index), str(arg), class_name=_class_name, method_name=_method_name) _outputdir = None try: model_context = __process_args(sys.argv) _outputdir = model_context.get_compare_model_output_dir() model1 = model_context.get_trailing_argument(0) model2 = model_context.get_trailing_argument(1) for f in [model1, model2]: if not os.path.exists(f): raise CLAException("Model %s does not exists" % f) if os.path.isdir(f): raise CLAException("Model %s is a directory" % f) model1_file = JFile(model1) model2_file = JFile(model2) if not (FileUtils.isYamlFile(model1_file) or FileUtils.isJsonFile(model1_file)): raise CLAException("Model extension must be either yaml or json") if not (FileUtils.isYamlFile(model1_file) and FileUtils.isYamlFile(model2_file) or FileUtils.isJsonFile(model1_file) and FileUtils.isJsonFile(model2_file)): ext = os.path.splitext(model1)[1] raise CLAException("Model %s is not a %s file " % (model2, ext)) obj = ModelFileDiffer(model1, model2, model_context, _outputdir) rc = obj.compare() if rc == VALIDATION_FAIL: System.exit(2) if _outputdir: fos = None writer = None file_name = None if len(compare_msgs) > 0: try: file_name = _outputdir + '/compare_model_stdout' fos = JFileOutputStream(file_name, False) writer = JPrintWriter(fos, True) writer.println(BLANK_LINE) writer.println(BLANK_LINE) index = 1 for line in compare_msgs: msg_key = line[0] msg_value = line[1] writer.println("%s. %s" % (index, format_message(msg_key,msg_value.replace(PATH_TOKEN, "-->")))) index = index + 1 writer.println(BLANK_LINE) fos.close() writer.close() except JIOException, ioe: if fos: fos.close() if writer: writer.close() _logger.severe('WLSDPLY-05708', file_name, ioe.getLocalizedMessage(), error=ioe, class_name=_class_name, method_name=_method_name) else:
def quit(): from java.lang import System print "Quitting..." System.exit(0)
webAssetRevision = eachDocRow.get('dRevisionID') safeItemList.append( '%s|%s' % (webAssetName, webAssetRevision)) except ServiceException, err: if noSkip: self.GeneralHandlerLogger.infoMessage( 'checkAssetExists', 'Unable to get information about document %s. Check document name spelling. Error: [%s]' % (webAssetName, err)) except Exception, err: self.GeneralHandlerLogger.infoMessage( 'checkAssetExists', 'Unable to get information about document %s. Error: [%s]' % (webAssetName, err)) System.exit(1) return safeItemList def checkTableExists(self, tableList, serverData, noSkip=True): if noSkip: self.GeneralHandlerLogger.infoMessage( 'checkTableExists', 'Starting checkTableExists method with params: [tableList: %s]' % tableList) safeTableList = [] checkClient = serverData[0] checkUserContext = serverData[1] checkServerInfo = serverData[2]
parser.set_defaults(**DEFAULTS) parser.add_option("-t", "--numthreads", dest="numthreads", action="store", type="int", help="maximum number of threads to run (default=2)") options, args = parser.parse_args() if (options.numthreads is not None) and (options.numthreads >= 1): numThreads = options.numthreads log('numThreads %d' % numThreads) runWindow = 5 syncWindow = 24 lastSync = datetime.today() - timedelta(hours=(syncWindow + 1)) lastRun = datetime.today() - timedelta(minutes=(runWindow + 1)) while True: try: t = lastRun + timedelta(minutes=runWindow) if t < datetime.today(): lastSync = doPrecalc(lastSync) lastRun = datetime.today() log('purge pre-calculations are complete') else: log('waiting until %s to do pre-calculations again' % (datetime.today() + timedelta(minutes=runWindow))) time.sleep(runWindow * 60) except: log('Exception caught in main',sys.exc_info(),traceback.print_exc(file=sys.stderr)) lastRun = datetime.today() System.exit(99)
def closeService(self): System.exit(0);
def exitApp(event): System.exit(0)
def doExit(self): ## have them confirm exit... System.exit(0)
def exit(self, event=None): System.exit(0)
def actionPerformed(button, e): System.exit(0)
def onQuit(self,event): System.exit(0)
def onQuit(self, e): System.exit(0) def onJOCL(self, e):
0, 0, 0, 0.5, 0, stim_seg_detailed, 0.5, 0, None) # delete all existing probes project.generatedPlotSaves.reset() # set up voltage recording at the specified points along the dendrite being stimulated project.generatedPlotSaves.addPlotSaveDetails('Golgi_reduced_v', project.simPlotInfo.getSimPlot('Golgi_reduced_v'), ArrayList([0]), ArrayList(rec_segs_reduced), False, False) project.generatedPlotSaves.addPlotSaveDetails('Golgi_detailed_v', project.simPlotInfo.getSimPlot('Golgi_detailed_v'), ArrayList([0]), ArrayList(rec_segs_detailed), False, False) # generate and compile neuron files print "Generating NEURON scripts..." simulator_seed = random.getrandbits(32) project.neuronFileManager.generateTheNeuronFiles(sim_config, None, NeuronFileManager.RUN_HOC,simulator_seed) compile_process = ProcessManager(project.neuronFileManager.getMainHocFile()) compile_success = compile_process.compileFileWithNeuron(0,0) # simulate if compile_success: print "Simulating: simulation reference " + sim_ref pm.doRunNeuron(sim_config) timefile_path = sim_path + '/time.dat' while not os.path.exists(timefile_path): time.sleep(0.1) data_string = "Data reference " + sim_ref for k,i in enumerate(rec_segs_detailed): data_string = data_string + " " + str(i) + " " + str(rec_dists_detailed[k]) print data_string System.exit(0)
def OnClose(self, event): print "Shutting down via the reloader window" System.exit(0)