def os_string(): ''' Return a string indicating the current OS formatted according to CMTK filename conventions Linux MacOSX-10.4 MacOSX-10.5 MacOSX-10.6 CYGWIN ''' from java.lang import System osname=System.getProperty("os.name") if osname.startswith('Windows'): return 'CYGWIN' elif osname.startswith('Linux'): return 'Linux' elif osname.startswith('Mac'): osversion=System.getProperty("os.version") match=re.match(r'10\.([0-9]+)(\.[0-9])*',osversion) if match==None: sys.exit('Unable to identify OS version: '+osversion) osmajor=match.group(1) iosmajor=int(osmajor) if iosmajor<4: myErr('Sorry CMTK requires MacOSX >=10.4') elif iosmajor>6: osmajor='6' return 'MacOSX-10.'+osmajor else: return None
def validateAdminPassword(domainProperties): error=0 admin_password = domainProperties.getProperty('wls.admin.password') prompt=domainProperties.getProperty('password.prompt') if admin_password is None or len(admin_password)==0: if prompt is not None and prompt.lower()=='true': admin_username=domainProperties.getProperty('wls.admin.username') if admin_username and not admin_password: dont_match=1 while dont_match: print 'Please enter WebLogic admin password: '******'Please re-enter the WebLogic admin password: '******'PASSWORDS DO NOT MATCH' domainProperties.setProperty('wls.admin.password',admin_password1) else: log.error('Please verify wls.admin.password property exists in configuration.') error=1 else: log.debug('Admin password is valid.') if error: sys.exit()
def __checkJdbcPasswords(domainProperties): # Check if global.jdbc.password flag is set to determine if the same JDBC password is to be used for each datasource. globalJdbcPasswordEnabled = domainProperties.getProperty('global.jdbc.password') jdbcDatasources=domainProperties.getProperty('jdbc.datasources') if jdbcDatasources: jdbcList=jdbcDatasources.split(',') for datasource in jdbcList: dsPassword=None dsPassword=domainProperties.getProperty('jdbc.datasource.' + str(datasource) + '.Password') if not dsPassword: if globalJdbcPasswordEnabled: globalJdbcPasswordValue = domainProperties.getProperty('global.jdbc.password.value') if not globalJdbcPasswordValue: log.info('Property global.jdbc.password is set, which indicates that all JDBC data sources have the same password.') dont_match=1 while dont_match: print 'Please enter the password for all JDBC data sources: ' password1=System.console().readPassword().tostring() print 'Please re-enter the password for all JDBC data sources: ' password2=System.console().readPassword().tostring() if password1==password2: dont_match=0 else: print 'PASSWORDS DO NOT MATCH' domainProperties.setProperty('global.jdbc.password.value', password1) globalJdbcPasswordValue=password1 domainProperties.setProperty('jdbc.datasource.' + str(datasource) + '.Password', globalJdbcPasswordValue) else: print 'Please enter password for JDBC data source [' + str(datasource) + '] :' password=System.console().readPassword().tostring() domainProperties.setProperty('jdbc.datasource.' + str(datasource) + '.Password', password)
def canMeJoin(self, player, clanid, pledgeType): clan = ClanTable.getInstance().getClan(clanid) if not clan: return False if clan.getCharPenaltyExpiryTime() > System.currentTimeMillis(): player.sendPacket(SystemMessageId.YOU_MUST_WAIT_BEFORE_ACCEPTING_A_NEW_MEMBER) return False if player.getClanId() != 0: sm = SystemMessage.getSystemMessage(SystemMessageId.S1_WORKING_WITH_ANOTHER_CLAN) sm.addString(player.getName()) player.sendPacket(sm) return False if player.getClanJoinExpiryTime() > System.currentTimeMillis(): sm = SystemMessage.getSystemMessage(SystemMessageId.C1_MUST_WAIT_BEFORE_JOINING_ANOTHER_CLAN) sm.addString(player.getName()) player.sendPacket(sm) return False if player.getLevel() > 40 or player.getClassId().level() >= 2: if pledgeType == -1: sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DOESNOT_MEET_REQUIREMENTS_TO_JOIN_ACADEMY) sm.addString(player.getName()) player.sendPacket(sm) player.sendPacket(SystemMessageId.ACADEMY_REQUIREMENTS) return False if clan.getSubPledgeMembersCount(pledgeType) >= clan.getMaxNrOfMembers(pledgeType): if pledgeType == 0: sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CLAN_IS_FULL) sm.addString(clan.getName()) player.sendPacket(sm) else: player.sendPacket(SystemMessageId.SUBCLAN_IS_FULL) return False return True
def __init__(self, pos, speed, direction): AIBase.__init__(self, "thrownshit") self.pos = pos self.speed = speed self.direction = direction self.a = System.currentTimeMillis() self.b = System.currentTimeMillis()
def CommandEntered(self, event): if event.source.text == 'exit': # let's kill the frame System.setOut(self.__outOriginal) System.setErr(self.__errOriginal) self.dispose() else: # echo the input to the text area using the printstream s = 'in : ' + event.source.text self.printStream.println(s) # try the embedded interp (the getLocals was just to see if I could interact with it) # it's not returning anything a = self.interpreter.getLocals() self.printWriter.println(a) self.interpreter.exec(event.source.txt) # try the main interp (the getLocals was just to see if I could interact with it) # it's not returning anything a = getLocals() self.printWriter.println(a) exec(event.source.txt) # set the input text blank and give it focus back. we don't get here if we try to use # the interpreter, though we do when we don't try to interact with the interpreter self.inputField.setText('') self.inputField.requestFocus()
def tick(self, framerate=0): """ Call once per program cycle, returns ms since last call. An optional framerate will add pause to limit rate. """ while self._repaint_sync.get(): try: self._thread.sleep(1) except InterruptedException: Thread.currentThread().interrupt() break self._time = System.nanoTime()//1000000 if framerate: time_pause = (1000//framerate) - (self._time-self._time_init) if time_pause > 0: try: self._thread.sleep(time_pause) except InterruptedException: Thread.currentThread().interrupt() self._time = System.nanoTime()//1000000 if self._pos: self._pos -= 1 else: self._pos = 9 self._time_diff[self._pos] = self._time-self._time_init self._time_init = self._time return self._time_diff[self._pos]
def adjustmentValueChanged(self, event): value = event.getSource().getValue() rowstride = min(width, value) for j in range(0, min(height, int(width * height / value))): System.arraycopy(pixelsCopy, j * value, pixels, j * width, rowstride) image.updateAndDraw()
def _mcvinit_classpath_hack(): r"""Attempt location of mcidasv.jar, idv.jar, and visad.jar. This function will look for the JARs within the classpath, but will also try within the following (platform-dependent) paths: Windows: "C:\Program Files\McIDAS-V-System" OS X: "/Applications/McIDAS-V-System" Linux: "" Returns: A dictionary with "mcidasv", "idv", and "visad" keys. """ classpath = System.getProperty('java.class.path') # supply platform-dependent paths to various JAR files # (in case they somehow are not present in the classpath) osname = System.getProperty('os.name') current_dir = os.path.normpath(os.getcwd()) mcv_jar = os.path.join(current_dir, 'mcidasv.jar') idv_jar = os.path.join(current_dir, 'idv.jar') visad_jar = os.path.join(current_dir, 'visad.jar') # allow the actual classpath to override any default JAR paths for entry in classpath.split(System.getProperty('path.separator')): if entry.endswith('mcidasv.jar'): mcv_jar = entry elif entry.endswith('idv.jar'): idv_jar = entry elif entry.endswith('visad.jar'): visad_jar = entry return {'mcidasv': mcv_jar, 'idv': idv_jar, 'visad': visad_jar}
def get_default_verify_paths(): """Return paths to default cafile and capath. """ cafile, capath = None, None default_cert_dir_env = os.environ.get('SSL_CERT_DIR', None) default_cert_file_env = os.environ.get('SSL_CERT_FILE', None) java_cert_file = System.getProperty('javax.net.ssl.trustStore') if java_cert_file is not None and os.path.isfile(java_cert_file): cafile = java_cert_file else: if default_cert_dir_env is not None: capath = default_cert_dir_env if os.path.isdir(default_cert_dir_env) else None if default_cert_file_env is not None: cafile = default_cert_file_env if os.path.isfile(default_cert_file_env) else None if cafile is None: # http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html java_home = System.getProperty('java.home') for _path in ('lib/security/jssecacerts', 'lib/security/cacerts'): java_cert_file = os.path.join(java_home, _path) if os.path.isfile(java_cert_file): cafile = java_cert_file capath = os.path.dirname(cafile) return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None, capath if capath and os.path.isdir(capath) else None, 'SSL_CERT_FILE', default_cert_file_env, 'SSL_CERT_DIR', default_cert_dir_env)
def exit(self): try: self.client.stopListening() except: pass os.environ['JYTHON_RUNNING'] = 'NO' System.exit(0)
def __call__(self): smtpHost = "mailhost" properties = System.getProperties() properties["mail.smtp.host"] = smtpHost session = Session.getInstance(System.getProperties()) session.debug = 1 message = MimeMessage(session) message.setFrom(InternetAddress("*****@*****.**")) message.addRecipient(Message.RecipientType.TO, InternetAddress("*****@*****.**")) message.subject = "Test email %s from thread %s" % (grinder.runNumber, grinder.threadID) # One could vary this by pointing to various files for content message.setText("SMTPTransport Email works from The Grinder!") # Wrap transport object in a Grinder Jython Test Wrapper transport = emailSendTest1.wrap(session.getTransport("smtp")) transport = emailSendTest1.wrap(transport) transport.connect(smtpHost, "username", "password") transport.send(message) transport.close()
def start(): System.setProperty("apple.laf.useScreenMenuBar", "true") System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Nengo") application = DefaultApplication() nengo = Nengo() nengo.application = application
def getJavaFX(): ver = jsys.getProperty("java.version") ver = ver.split(".") ver[-1] = float(ver[-1].replace("_", ".")) ver[0] = float(str(ver[0]) + "." + str(ver[1])) ver.pop(1) print ver if ver[0] <= 1.6: mess() elif ver[0] == 1.7: if ver[1] <= 0.11: mess() home = jsys.getProperty("java.home") try: jfxrt = os.path.join(home, "lib", "jfxrt.jar") sys.path.insert(0, jfxrt) except: part01 = "Nie można odnalesc biblioteki JavaFX(jfxrt.jar).\n" message = part01 + "Unable to find JavaFX lib (jfxrt.jar)." jop.showMessageDialog(None, message) sys.exit() else: pass
def _initializeMXPI(serverName, serverPort, protocol, MxpiMain5_1SoapBindingStubClass, VerifyAllHostnameVerifierClass): serverPortName = 'MxpiMain5_1' namespaceURI = "urn:client.v5_1.soap.mx.hp.com" serviceName = "MxpiMainService" wsdlURL = "%s://%s:%s/mxsoap/services/%s?wsdl" % (protocol, serverName, serverPort, serverPortName) # Set trust manager if protocol == 'https': verifyAllHostnameVerifier = VerifyAllHostnameVerifierClass() sslContext = SSLContextManager.getAutoAcceptSSLContext() HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()) HttpsURLConnection.setDefaultHostnameVerifier(verifyAllHostnameVerifier) ## Set trust all SSL Socket to accept all certificates System.setProperty("ssl.SocketFactory.provider", "TrustAllSSLSocketFactory") Security.setProperty("ssl.SocketFactory.provider", "TrustAllSSLSocketFactory") # Try and initialize connection simBindingStub = MxpiMain5_1SoapBindingStubClass() simServiceFactory = ServiceFactory.newInstance() simService = simServiceFactory.createService(URL(wsdlURL), QName(namespaceURI, serviceName)) theMxpiMain = simService.getPort(QName(namespaceURI, serverPortName), simBindingStub.getClass()) return theMxpiMain
def mp2scf(molecule, basisSet): from java.text import DecimalFormat from java.lang import System from org.meta.math.qm import * print("Starting computation for " + repr(molecule) + " at " + repr(basisSet) + " basis") t1 = System.currentTimeMillis() bfs = BasisFunctions(molecule, basisSet) t2 = System.currentTimeMillis() print("Number of basis functions : " + repr(bfs.getBasisFunctions().size())) print("Time till setting up basis : " + repr(t2-t1) + " ms") oneEI = OneElectronIntegrals(bfs, molecule) t2 = System.currentTimeMillis() print("Time till 1EI evaluation : " + repr(t2-t1) + " ms") twoEI = TwoElectronIntegrals(bfs) t2 = System.currentTimeMillis() print("Time till 2EI evaluation : " + repr(t2-t1) + " ms") scfm = SCFMethodFactory.getInstance().getSCFMethod(molecule, oneEI, twoEI, SCFType.MOLLER_PLESSET) scfm.scf() print("Final Energy : " + repr(scfm.getEnergy())) return scfm.getEnergy()
def ig_ref_search_2file(filename, line, col, toplevelpath, destinationfile): sf = SourceFile(File(filename)) tlp = ToplevelPath(toplevelpath) location = SourceLocation(sf, line, col) start = System.currentTimeMillis() res = SourceLocation2IG.findNearestItem(location, tlp, project) if res == None: printf('No IG item found at %s:%s,%s', filename, line, col) return item = res.getFirst() if item == None: printf('Failed to find nearest IG Item') return path = res.getSecond() rs = IGReferencesSearch(project) if isinstance(item, IGOperationObject): item = item.getObject() result = rs.search(item, path, True, True, False, False) time = System.currentTimeMillis() - start out = PrintStream(File(destinationfile)) printf('Found %s references of %s in %s ms.', result.countRefs(), item, time) out.printf('Found %s references of %s in %s ms:\n', result.countRefs(), item, time) result.dump(0, out)
def _generate(self, title, *args): System.setOut(PrintStream(NullOutputStream())) index = self.widget.indexOfTab(title) rect = self.widget.getBoundsAt(index) operator = jemmy.operators.ComponentOperator(self.widget.widget) System.setOut(out_orig) operator.clickForPopup(rect.x + rect.width/2, rect.y + rect.height/2)
def exit(self): try: self.client.stopListening() except: pass os.environ["JYTHON_RUNNING"] = "NO" System.exit(0)
def load(self, warn=True): # capture all error messages oldErr = _system.err _system.setErr(_pstream(_NoOutputStream())) try: jdh = self._loadFile() finally: _system.setErr(oldErr) data = asDatasetList(jdh.getList()) names = jdh.getNames() basenames = [] from os import path as _path for n in names: # remove bits of path so sanitising works if _path.exists(n): basenames.append(_path.basename(n)) else: basenames.append(n) if len(data) != len(basenames): raise io_exception("Number of names does not match number of datasets") metadata = None if self.load_metadata: meta = jdh.getMetadata() if meta: mnames = meta.metaNames if mnames: metadata = [ (k, meta.getMetaValue(k)) for k in mnames ] return DataHolder(list(zip(basenames, data)), metadata, warn)
def compile(files, javac=None, cpathopt="-classpath", cpath=None, options=None, sourcedir=None): cmd = [] # Search order for a Java compiler: # 1. -C/--compiler command line option # 2. python.jythonc.compiler property (see registry) # 3. guess a path to javac if javac is None: javac = sys.registry.getProperty("python.jythonc.compiler") if javac is None: javac = findDefaultJavac() cmd.append(javac) # Extra options # 1. -J/--compileropts command line option (passed in options) # 2. python.jythonc.compileropts property if options is None: options = sys.registry.getProperty("python.jythonc.compileropts") if options: options = options.split() if options is None: options = [] cmd.extend(options) # new: # Classpath: # 1. python.jythonc.classpath property # + # 2. java.class.path property # + # 3. sourcedir # + # 4. sys.path if cpath is None: sep = java.io.File.pathSeparator cpath = [] part = sys.registry.getProperty("python.jythonc.classpath") if part != None: cpath.extend(part.split(sep)) part = getClasspath() if part != None: cpath.extend(part.split(sep)) if sourcedir: cpath.append(sourcedir) cpath.extend(sys.path) cpath = sep.join(cpath) if System.getProperty("os.name")[:7] == 'Windows' and \ System.getProperty("java.version") < "1.2": cpath = '"%s"' % cpath cmd.extend([cpathopt, cpath]) cmd.extend(files) print 'Compiling with args:', cmd try: proc = runtime.exec(cmd) except IOError, e: msg = '''%s Consider using the -C/--compiler command line switch, or setting the property python.jythonc.compiler in the registry.''' % e return 1, '', msg
def test_raw_forced_delayed(self): comments = [] class Test_JavaAbortFinalizable(Object): def __init__(self, name, toAbort): self.name = name self.toAbort = toAbort def __repr__(self): return "<"+self.name+">" def finalize(self): gc.notifyPreFinalization() comments.append("del "+self.name) gc.abortDelayedFinalization(self.toAbort) # We manually restore weak references: gc.restoreWeakReferences(self.toAbort) gc.notifyPostFinalization() class Test_Finalizable(object): def __init__(self, name): self.name = name def __repr__(self): return "<"+self.name+">" def __del__(self): comments.append("del "+self.name) def callback_a(obj): comments.append("callback_a") def callback_b(obj): comments.append("callback_b") a = Test_Finalizable("a") wa = weakref.ref(a, callback_a) b = Test_JavaAbortFinalizable("b", a) wb = weakref.ref(b, callback_b) gc.addJythonGCFlags(gc.FORCE_DELAYED_FINALIZATION) gc.addJythonGCFlags(gc.FORCE_DELAYED_WEAKREF_CALLBACKS) self.assertTrue(gc.delayedFinalizationEnabled()) self.assertTrue(gc.delayedWeakrefCallbacksEnabled()) self.assertEqual(len(comments), 0) del a del b System.gc() time.sleep(2) self.assertIsNotNone(wa()) self.assertIsNone(wb()) self.assertIn('del b', comments) self.assertNotIn('callback_a', comments) self.assertIn('callback_b', comments) self.assertNotIn('del a', comments) self.assertEqual(2, len(comments)) gc.removeJythonGCFlags(gc.FORCE_DELAYED_FINALIZATION) gc.removeJythonGCFlags(gc.FORCE_DELAYED_WEAKREF_CALLBACKS)
def __init__(self): from com.raytheon.viz.gfe.core import DataManager from java.lang import System System.setProperty('user.name', 'GFETEST') self.__host = None self.__port = None self.__user = '******' self.__dataMgr = DataManager.getInstance(None)
def __init__(self): """ Sets the properties and context builders. """ context_builder = "org.jclouds.abiquo.AbiquoContextBuilder" props_builder = "org.jclouds.abiquo.AbiquoPropertiesBuilder" System.setProperty("abiquo.contextbuilder", context_builder) System.setProperty("abiquo.propertiesbuilder", props_builder) self.__context = None self.__config = Config()
def create_tmp_dir(local_connection): property = "java.io.tmpdir" temp_dir = System.getProperty(property) path_separator = local_connection.getHostOperatingSystem().getFileSeparator() work_dir = "%s%swork%s" % (temp_dir,path_separator,System.currentTimeMillis()) work_dir_as_file = File(work_dir) work_dir_as_file.mkdir() return work_dir_as_file
def _generate(self, *args): #runKeyword("closeWindow", self.widget.getTitle()) doesn't work for confirm dialogs after closing #the application. System.setProperty("abbot.robot.mode", "awt") robot = Robot() robot.setEventMode(Robot.EM_AWT) util.runOnEventDispatchThread(robot.close, self.widget.widget) robot.waitForIdle()
def isRightGB(self): '''Test if this is a right Groebner base. ''' t = System.currentTimeMillis(); b = ModSolvableGroebnerBaseAbstract().isRightGB(self.mset); t = System.currentTimeMillis() - t; print "module isRightGB executed in %s ms" % t; return b;
def testOS(self): if Env.getOS() == OS.MAC: assert System.getProperty("os.name").startswith("Mac OS X") elif Env.getOS() == OS.WINDOWS: assert System.getProperty("os.name").startswith("Windows") elif Env.getOS() == OS.LINUX: assert System.getProperty("os.name").find("Linux") >= 0 assert Env.getOSVersion() != None
def connectAdvanced(self,host,port,map): print "Connecting to the server..." System.setProperty("javax.net.ssl.trustStore", self.trustStore) System.setProperty("javax.net.ssl.trustStorePassword", self.trustStorePassword) url = JMXServiceURL("REST", host, port, "/IBMJMXConnectorREST") self.connector = JMXConnectorFactory.newJMXConnector(url, map) self.connector.connect() print "Successfully connected to the server " + '"' + host + ':%i"' % port
def rightGB(self): '''Compute a right Groebner base. ''' t = System.currentTimeMillis(); G = ModSolvableGroebnerBaseAbstract().rightGB(self.mset); t = System.currentTimeMillis() - t; print "executed module rightGB in %s ms" % t; return SolvableSubModule(self.module,"",G.list);
class EDUtilsPlatform(object): """ Static class for guessing: platform specific stuff. """ __semaphore = Semaphore() __semaphore.acquire() __strCmdSep = None __strCmdEnv = None __strEscapedLineSep = None __strLineSep = os.linesep __strSep = os.sep __strAltSep = os.altsep __strExtSep = os.extsep __strPathSep = os.pathsep __strName = os.name __strStartScript = None __PythonPlatformSize = int( round(math.log(sys.maxint + 1) / math.log(2) + 1)) __SystemPlatform = distutils.util.get_platform() if __PythonPlatformSize == 32 and __SystemPlatform.endswith("x86_64"): __PythonPlatform = __SystemPlatform[:-6] + "i386" else: __PythonPlatform = __SystemPlatform __PythonArchitecture = "lib.%s-%i.%i" % ( __PythonPlatform, sys.version_info[0], sys.version_info[1]) if sys.maxunicode == 65535: __PythonArchitecture += "-ucs2" __SystemArchitecture = "lib.%s-%i.%i" % ( __SystemPlatform, sys.version_info[0], sys.version_info[1]) if os.name == "java": # Then we are running under Jython ! from java.lang import System as javasystem if javasystem.getProperty("os.name").startswith("Windows"): __strName = "nt" else: __strName = "posix" if __strName == "nt": __strCmdSep = "&" __strCmdEnv = "set" __strEscapedSep = "/" __strEscapedLineSep = "\\r\\n" __strStartScript = "@ECHO OFF" elif __strName == "posix": __strCmdSep = ";" __strCmdEnv = "env" __strEscapedSep = "\\\\" __strEscapedLineSep = "\\n" __strStartScript = "#!%s" % sys.executable __semaphore.release() @classmethod def getArchitecture(cls): """ Returns the name of the architecture including the CPU arch and the version of python for the actual running python (i.e. can be i386 on a x86_64 computer) @return: lib-$OS-$arch-$PyVersion @rtype: python string """ return cls.__PythonArchitecture architecture = classproperty(getArchitecture) @classmethod def getSystemArchitecture(cls): """ Returns the name of the architecture including the CPU arch and the version of python for the actual operating system @return: lib-$OS-$arch-$PyVersion @rtype: python string """ return cls.__SystemArchitecture systemArchitecture = classproperty(getSystemArchitecture) @classmethod def getName(cls): """ Returns the name of the architecture @return: os.name like architecture (posix, nt, ... but never java even under jython) @rtype: python string """ return cls.__strName name = classproperty(getName) @classmethod def getCmdSep(cls): """ Returns the Command separator like - Under Unix: cmd1;cmd2 - Under Windows cmd1 & cmd2 @return: "&" or ";" depending on the architecture @rtype: python string """ return cls.__strCmdSep cmdSep = classproperty(getCmdSep) @classmethod def getCmdEnv(cls): """ @return: "env" or "set" to print the environment under the current operating system """ return cls.__strCmdEnv cmdEnv = classproperty(getCmdEnv) @classmethod def getEscapedSep(cls): """ return os.sep with "\" escaped """ return cls.__strEscapedSep escapedSep = classproperty(getEscapedSep) @classmethod def getEscapedLineSep(cls): """ return os.linesep with "\" escaped """ return cls.__strEscapedLineSep escapedLinesep = classproperty(getEscapedLineSep) @classmethod def getLineSep(cls): """ @return os.linesep """ return cls.__strLineSep linesep = classproperty(getLineSep) @classmethod def getSep(cls): """ @return: os.sep """ return cls.__strSep sep = classproperty(getSep) @classmethod def getStartScript(cls): """ @return: header for writing scripts under the current the archtecture (#!/usr/bin/python under linux) """ return cls.__strStartScript startScript = classproperty(getStartScript) @classmethod def getSize(cls): """ @return: the size of the environment, probably 32 or 64 bits """ return cls.__PythonPlatformSize size = classproperty(getSize) @classmethod def getSystemPlatform(cls): """ @return: linux-x86_64, if python 32bits is running under amd64 OS. """ return cls.__SystemPlatform systemPlatform = classproperty(getSystemPlatform) @classmethod def getPythonPlatform(cls): """ @return: linux-i386, if python 32bits is running under amd64 OS. """ return cls.__PythonPlatform pythonPlatform = classproperty(getPythonPlatform) @classmethod def getAltSep(cls): """ @return: os.altsep """ return cls.__strAltSep altsep = classproperty(getAltSep) @classmethod def getExtSep(cls): """ @return: "." as extension separator """ return cls.__strExtSep extsep = classproperty(getExtSep) @classmethod def getPathSep(cls): """ same as os.pathsep @return "/" under linux and "\" under windows. """ return cls.__strPathSep pathsep = classproperty(getPathSep) @classmethod def escape(cls, _string): """ escape \ (i.e. "\\") under windows as \\ (i.e. "\\\\") @return escaped string suitable for metaprogramming """ return _string.replace("\\", "\\\\") @classmethod def Popen(cls, *args, **kwargs): """ implementation of a platform independent subprocess.Popen method @return: subporcess.Popen instance. """ if os.name == "posix": #python under unix kwargs["preexec_fn"] = os.setsid return subprocess.Popen(*args, **kwargs) @classmethod def kill(cls, _iPid): """ implementation of a platform independent kill method @param _iPid: process ID @type _iPid: integer """ EDVerbose.log("EDUtilsPlatorm.kill called on PID: %s" % _iPid) if os.name == "posix": #python under unix os.killpg(_iPid, signal.SIGKILL) elif cls.architecture == "posix": #jython running under unix os.kill(_iPid, signal.SIGKILL) else: #windows, ... Nota: this only works from python2.7 under windows ! EDVerbose.WARNING("Kill Called to PID= %s with signal %s" % (_iPid, signal.SIGTERM)) os.kill(_iPid, signal.SIGTERM)
def execute(self) -> object: self.num_blocks_size = self.num_blocks # 64 # DEFAULT_NUM_BLOCKS self.num_blocks_feat = self.num_blocks # 64 # DEFAULT_NUM_BLOCKS self.block_size = self._block_size["block_size_1d"] # Schedule the categorical Naive Bayes and Ridge Regression kernels start_comp = System.nanoTime() start = 0 # RR - 1. self.execute_phase("rr_1", self.rr_1(self.num_blocks_feat, self.block_size), self.x, self.z, self.size, self.num_features) # NB - 1. self.execute_phase("nb_1", self.nb_1(self.num_blocks_size, self.block_size), self.x, self.nb_feat_log_prob, self.r1, self.size, self.num_features, self.num_classes) # RR - 2. self.execute_phase("rr_2", self.rr_2(self.num_blocks_size, self.block_size), self.z, self.ridge_coeff, self.r2, self.size, self.num_features, self.num_classes) # NB - 2. self.execute_phase("nb_2", self.nb_2(self.num_blocks_size, self.block_size), self.r1, self.nb_amax, self.size, self.num_classes) # NB - 3. self.execute_phase("nb_3", self.nb_3(self.num_blocks_size, self.block_size), self.r1, self.nb_amax, self.nb_l, self.size, self.num_classes) # RR - 3. self.execute_phase("rr_3", self.rr_3(self.num_blocks_size, self.block_size), self.r2, self.ridge_intercept, self.size, self.num_classes) # NB - 4. self.execute_phase("nb_4", self.nb_4(self.num_blocks_size, self.block_size), self.r1, self.nb_l, self.size, self.num_classes) # Ensemble results; # Softmax normalization; self.execute_phase("softmax_1", self.softmax(self.num_blocks_size, self.block_size), self.r1, self.size, self.num_classes) self.execute_phase("softmax_2", self.softmax(self.num_blocks_size, self.block_size), self.r2, self.size, self.num_classes) # Prediction; self.execute_phase("argmax", self.argmax(self.num_blocks_size, self.block_size), self.r1, self.r2, self.r, self.size, self.num_classes) # Add a final sync step to measure the real computation time; if self.time_phases: start = System.nanoTime() tmp = self.r[0] end = System.nanoTime() if self.time_phases: self.benchmark.add_phase({ "name": "sync", "time_sec": (end - start) / 1_000_000_000 }) self.benchmark.add_computation_time((end - start_comp) / 1_000_000_000) self.benchmark.add_to_benchmark("gpu_result", 0) if self.benchmark.debug: BenchmarkResult.log_message( f"\tgpu result: [" + ", ".join([f"{x:.4f}" for x in self.r[:10]]) + "...]") return self.r
#rk_deployOpa.py.py #rk_deployOpa.py.py import time appManager = AdminControl.queryNames( 'cell=sdcgisazapmdw19Node01Cell,node=Node01,type=ApplicationManager,process=server1,*' ) import java.lang.System as sys lineSeparator = sys.getProperty('line.separator') def installApplicationOnServer(fileName, appName, contextRoot, serverName): """Install given application on the named server using given context root""" print "installApplicationOnServer: fileName=%s appName=%s contextRoot=%s ServerName=%s" % ( fileName, appName, contextRoot, serverName) #print "installApplicationOnServer: fileName=%s appName=%s ServerName=%s" % ( fileName, appName,serverName ) AdminApp.install( fileName, '[-appname ' + appName + ' -contextroot ' + contextRoot + ' -server ' + serverName + ' -usedefaultbindings ]') #AdminApp.install(fileName,'[-appname ' + appName + ' -server ' + serverName + ' -usedefaultbindings ]') AdminConfig.save() fileName = "./web-determinations.war" appName = "web-determinations" serverName = "server1" contextRoot = "web-determinations" installApplicationOnServer(fileName, appName, contextRoot, serverName) #start application
plot = {} plotd = {} br = 1 for i in range(1, 30): L = QQ(-1) + (i, 10) #L = QQ(9,10) + (i,100); fr = QQ(5) * ((1, 5)) * A**7 - ((21, 20) * L - (29, 20)) * A**6 - ( (21, 10) * L) * A**5 + ((1, 5)) * A**2 - ((1, 20) * L - (9, 20)) * A - ((1, 10) * L) print "L = " + str(DD(L)) #print "fr = " + str(fr); #print; t = System.currentTimeMillis() R = r3.realRoots(fr) t = System.currentTimeMillis() - t # print "R = " + str([ str(DD(r.elem.getRational())) for r in R ]); print "R = " + str([r.elem.decimalMagnitude() for r in R]) plot[float(DD(L))] = R #print "real roots time =", t, "milliseconds"; if len(R) != br: br = len(R) print "#(real roots) = %s" % br b = L - (11, 100) for j in range(1, 12): L = b + (j, 100) fri = QQ(5) * ((1, 5)) * A**7 - ( (21, 20) * L - (29, 20)) * A**6 - ((21, 10) * L) * A**5 + ( (1, 5)) * A**2 - ((1, 20) * L -
if (formerDoNoiseAndBackgroundRemoval == doNoiseAndBackgroundRemoval and sigma1 == formerSigma1 and sigma2 == formerSigma2 and formerDoRigidTransform == doRigidTransform and translationX == formerTranslationX and translationY == formerTranslationY and translationZ == formerTranslationZ and rotationX == formerRotationX and rotationY == formerRotationY and rotationZ == formerRotationZ and formerT == imp.getFrame() and formerTolerance == tolerance and formerThreshold == threshold and formerDoSpotDetection == doSpotDetection): # sleep some msec Thread.sleep(100) continue # measure start time for benchmarking timeStamp = System.currentTimeMillis() if (formerT != imp.getFrame()): formerT = imp.getFrame() # push image to GPU pushed = clij2.pushCurrentZStack(imp) # scale it initially; depends on zoom factor and voxel size scaleTransform = AffineTransform3D() scaleTransform.scale(1.0 / scaleX, 1.0 / scaleY, 1.0 / scaleZ) clij2.affineTransform3D(pushed, input, scaleTransform) pushed.close() stillValid = False # Noise/background removal if (formerDoNoiseAndBackgroundRemoval != doNoiseAndBackgroundRemoval or formerSigma1 != sigma1 or formerSigma2 != sigma2):
def get_time(self): """ Get current time. """ return System.nanoTime() / 1000000.0
def test_unquoted(self): # for the build bot, try to specify a real java home javaHome = System.getProperty('java.home', 'C:\\Program Files\\Java\\someJava') self.assertOutput(javaHome=javaHome)
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) except CompareException, ce: cla_helper.clean_up_temp_files() __logger.severe('WLSDPLY-05704', ce.getLocalizedMessage()) System.exit(2) except PyWLSTException, pe: cla_helper.clean_up_temp_files() __logger.severe('WLSDPLY-05704', pe.getLocalizedMessage()) System.exit(2) except: exc_type, exc_obj, exc_tb = sys.exc_info() eeString = traceback.format_exception(exc_type, exc_obj, exc_tb) cla_helper.clean_up_temp_files() __logger.severe('WLSDPLY-05704', eeString) System.exit(2) def format_message(key, *args): """ Get message using the bundle. :param key: bundle key
from com.mysql.jdbc import Driver from net.grinder.script.Grinder import grinder from net.grinder.script import Test from java.util import Random from java.lang import System DB_SERVER_IP = "<>:3306" DATABASE = "" # Parameters DB_connect = "jdbc:mysql://" + DB_SERVER_IP + "/" + DATABASE DB_user = "******" DB_password = "" test1 = Test(1, "Database select") random = Random(long(System.nanoTime())) # Load the JDBC driver. DriverManager.registerDriver(Driver()) def getConnection(): return DriverManager.getConnection(DB_connect, DB_user, DB_password) def ensureClosed(object): try: object.close() except: pass class TestRunner: def __init__(self): test1.record(TestRunner.__call__)
except: #ok, just ignore it if we couldn't get it if DEBUG: import traceback traceback.print_exc() #@Reimport #------------------------------------------------------------------------------------------------------------------- if not encoding: #Jython try: from java.lang import System except ImportError: pass else: #that's the way that the encoding is specified in WorkbenchEncoding.getWorkbenchDefaultEncoding encoding = System.getProperty("file.encoding", "") if DEBUG: sys.stdout.write('encoding from "file.encoding": %s\n' % (encoding, )) #------------------------------------------------------------------------------------------------------------------- if not encoding: #Python: get the default system locale (if possible) try: import locale except ImportError: if DEBUG: import traceback traceback.print_exc() #@Reimport else: loc = locale.getdefaultlocale()
from org.slf4j import LoggerFactory LOG = LoggerFactory.getLogger("jython.Startup") from java.lang import System import sys, platform LOG.warn("") if hasattr(sys.version_info, "major"): LOG.warn("Jython version: {}.{}.{}.{}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro, sys.version_info.releaselevel)) else: LOG.warn("Jython version: {}".format(sys.version)) LOG.warn("Operating system: {}".format(System.getProperty("os.name"))) LOG.warn("OS Version: {}".format(System.getProperty("os.version"))) LOG.warn("Architecture: {}".format(platform.uname()[5])) LOG.warn("Java version: {}".format(sys.platform)) LOG.warn("sys.path: {}".format(sys.path)) LOG.warn("")
def openDir(): osName = System.getProperty('os.name').lower() if osName.find('mac os x') > -1: os.system('chmod a+rw ' + lpath) os.system('chmod a+rw ' + lpath + '*')
# FOR A PARTICULAR PURPOSE. THIS CODE AND INFORMATION ARE NOT SUPPORTED BY XEBIALABS. # import sys from com.perforce.p4java.server import ServerFactory from com.perforce.p4java.option.server import GetChangelistsOptions from com.perforce.p4java.core import IChangelist from com.perforce.p4java.core.file import FileSpecBuilder from com.perforce.p4java import PropertyDefs from java.lang import System if perforceServer is None: print "No server provided" sys.exit(1) props = System.getProperties() props.put(PropertyDefs.PROG_NAME_KEY, "P4-XL_Release") props.put(PropertyDefs.PROG_VERSION_KEY, "2.0.0") iServer = ServerFactory().getOptionsServer(perforceServer['port'], props) iServer.setUserName(perforceServer['username']) iServer.connect() if perforceServer['password']: iServer.login(perforceServer['password']) opts = GetChangelistsOptions() opts.setMaxMostRecent(1) opts.setType(IChangelist.Type.SUBMITTED) filespec = None
def run1(): JyNI.JyRefMonitor_setMemDebugFlags(1) JyWeakReferenceGC.monitorNativeCollection = True # PyType <- Make native ref-cycle test with heap type to test partly-stub-mode. # PySet, but no native link to other PyObject # PyFrozenSet, " # PyCode, not GC-relevant in CPython import DemoExtension #Note: # For now we attempt to verify JyNI's GC-functionality independently from # Jython concepts like Jython weak references or Jython GC-module. # So we use java.lang.ref.WeakReference and java.lang.System.gc to monitor # and control Java-gc. #JyNI.JyRefMonitor_setMemDebugFlags(1) #JyWeakReferenceGC.monitorNativeCollection = True #l = (123,) l = ([0, "test"],) l[0][0] = l #l = (123, {'a': 0, 'b': "test"}) #l[1]['a'] = l #We create weak reference to l to monitor collection by Java-GC: wkl = WeakReference(l) print "weak(l): "+str(wkl.get()) # We pass down l to some native method. We don't care for the method itself, # but conversion to native side causes creation of native PyObjects that # correspond to l and its elements. We will then track the life-cycle of these. print "make l native..." DemoExtension.argCountToString(l) #print "argCountToString.__doc__-address: "+str(JyNI.lookupNativeHandle(DemoExtension.argCountToString.__doc__)) #print "We access a method-doc as this used to cause problems with GC:" #print " "+DemoExtension.argCountToString.__doc__ #print "Native static objects so far:" #print JyNI.nativeStaticPyObjectHeads.keySet() print "Delete l... (but GC not yet ran)" del l #l = None print "weak(l) after del: "+str(wkl.get()) print "" # monitor.list-methods display the following format: # [native pointer]{'' | '_GC_J' | '_J'} ([type]) #[native ref-count]: [repr] *[creation time] # _GC_J means that JyNI tracks the object # _J means that a JyNI-GC-head exists, but the object is not actually treated by GC # This can serve monitoring purposes or soft-keep-alive (c.f. java.lang.ref.SoftReference) # for caching. print "Leaks before GC:" monitor.listLeaks() print "" # By inserting this line you can confirm that native # leaks would persist if JyNI-GC is not working: #JyWeakReferenceGC.nativecollectionEnabled = False print "calling Java-GC..." System.gc() time.sleep(2) print "weak(l) after GC: "+str(wkl.get()) print "" monitor.listWouldDeleteNative() print "" print "leaks after GC:" monitor.listLeaks() print "" print " "+DemoExtension.argCountToString.__doc__ monitor.listLeaks() #print "----" #print monitor.listAll() print "" print "====" print "exit" print "===="
from java.util import Properties from java.util import HashMap from java.io import FileInputStream from java.io import ByteArrayOutputStream from java.io import ObjectOutputStream from java.lang import String from java.lang import Boolean from java.lang import Runtime from java.lang import Integer from com.collation.platform.ip import ScopedProps ######################################################## # Set the Path information ######################################################## coll_home = System.getProperty("com.collation.home") System.setProperty("jython.home", coll_home + "/external/jython-2.1") System.setProperty("python.home", coll_home + "/external/jython-2.1") jython_home = System.getProperty("jython.home") sys.path.append(jython_home + "/Lib") sys.path.append(coll_home + "/lib/sensor-tools") sys.prefix = jython_home + "/Lib" ######################################################## # More Standard Jython/Python Library Imports ######################################################## import traceback import string import re import jarray
def build_libs(cl_args): presets = { "win32-2013": ("Visual Studio 12", ""), "win32-2015": ("Visual Studio 14", ""), "win32-2017": ("Visual Studio 15", ""), "win64-2013": ("Visual Studio 12 Win64", ""), "win64-2015": ("Visual Studio 14 Win64", ""), "win64-2017": ("Visual Studio 15 Win64", ""), "win32-mingw": ("MinGW Makefiles", ""), "linux32": ("Unix Makefiles", "-DSUBSYSTEM_NAME=x86"), "linux32-universal": ("Unix Makefiles", "-DSUBSYSTEM_NAME=x86"), "linux64": ("Unix Makefiles", "-DSUBSYSTEM_NAME=x64"), "linux64-universal": ("Unix Makefiles", "-DSUBSYSTEM_NAME=x64"), "mac10.7": ("Xcode", "-DSUBSYSTEM_NAME=10.7"), "mac10.8": ("Xcode", "-DSUBSYSTEM_NAME=10.8"), "mac10.9": ("Xcode", "-DSUBSYSTEM_NAME=10.9"), "mac10.10": ("Xcode", "-DSUBSYSTEM_NAME=10.10"), "mac10.11": ("Xcode", "-DSUBSYSTEM_NAME=10.11"), "mac10.12": ("Xcode", "-DSUBSYSTEM_NAME=10.12"), "mac10.13": ("Xcode", "-DSUBSYSTEM_NAME=10.13"), "mac-universal": ("Unix Makefiles", "-DSUBSYSTEM_NAME=10.7"), } parser = OptionParser(description='Indigo libraries build script') parser.add_option('--generator', help='this option is passed as -G option for cmake') parser.add_option('--params', default="", help='additional build parameters') parser.add_option('--config', default="Release", help='project configuration') parser.add_option('--nobuild', default=False, action="store_true", help='configure without building', dest="nobuild") parser.add_option('--clean', default=False, action="store_true", help='delete all the build data', dest="clean") parser.add_option('--preset', type="choice", dest="preset", choices=list(presets.keys()), help='build preset %s' % (str(list(presets.keys())))) parser.add_option('--with-static', action='store_true', help='Build Indigo static libraries', default=False, dest='withStatic') parser.add_option('--verbose', action='store_true', help='Show verbose build information', default=False, dest='buildVerbose') parser.add_option('--cairo-gl', dest="cairogl", default=False, action="store_true", help='Build Cairo with OpenGL support') parser.add_option('--cairo-vg', dest="cairovg", default=False, action="store_true", help='Build Cairo with CairoVG support') parser.add_option('--cairo-egl', dest="cairoegl", default=False, action="store_true", help='Build Cairo with EGL support') parser.add_option('--cairo-glesv2', dest="cairoglesv2", default=False, action="store_true", help='Build Cairo with GLESv2 support') parser.add_option('--find-cairo', dest="findcairo", default=False, action="store_true", help='Find and use system Cairo') parser.add_option('--find-pixman', dest="findpixman", default=False, action="store_true", help='Find and use system Pixman') parser.add_option('--no-multithreaded-build', dest='mtbuild', default=True, action='store_false', help='Use only 1 core to build') if os.name == 'posix': parser.add_option('--check-abi', dest='checkabi', default=False, action="store_true", help='Check ABI type of Indigo libraries on Linux') (args, left_args) = parser.parse_args(cl_args) if len(left_args) > 0: print("Unexpected arguments: %s" % (str(left_args))) exit() if args.preset: args.generator, args.params = presets[args.preset] else: if os.name == 'java': from java.lang import System system = System.getProperty("os.name") else: system = platform.system() if system in ('Darwin', 'Mac OS X'): mac_version = platform.mac_ver( )[0] if os.name != 'java' else System.getProperty('os.version') preset = 'mac{}'.format('.'.join(mac_version.split('.')[:2])) elif system == 'Linux': preset = 'linux{}'.format(platform.architecture()[0][:2]) elif system == 'Windows': preset = '' auto_vs = True else: raise NotImplementedError('Unsupported OS: {}'.format(system)) if preset: print("Auto-selecting preset: {}".format(preset)) args.generator, args.params = presets[preset] else: print( "Preset is no selected, continuing with empty generator and params..." ) args.generator, args.params = '', '' cur_dir = os.path.abspath(os.path.dirname(__file__)) root = os.path.join(cur_dir, "..") project_dir = os.path.join(cur_dir, "indigo-all") if args.cairogl: args.params += ' -DWITH_CAIRO_GL=TRUE' if args.cairovg: args.params += ' -DWITH_CAIRO_VG=TRUE' if args.cairoegl: args.params += ' -DWITH_CAIRO_EGL=TRUE' if args.cairoglesv2: args.params += ' -DWITH_CAIRO_GLESV2=TRUE' if args.findcairo: args.params += ' -DUSE_SYSTEM_CAIRO=TRUE' if args.findcairo: args.params += ' -DUSE_SYSTEM_PIXMAN=TRUE' if args.withStatic: args.params += ' -DWITH_STATIC=TRUE' if args.preset and args.preset.find('universal') != -1: args.params += ' -DUNIVERSAL_BUILD=TRUE' if os.name == 'posix' and args.checkabi: args.params += ' -DCHECK_ABI=TRUE' build_dir = (args.generator + " " + args.config + args.params.replace('-D', '')) build_dir = "indigo_" + build_dir.replace(" ", "_").replace( "=", "_").replace("-", "_") full_build_dir = os.path.join(root, "build", build_dir) if os.path.exists(full_build_dir) and args.clean: print("Removing previous project files") shutil.rmtree(full_build_dir) if not os.path.exists(full_build_dir): os.makedirs(full_build_dir) os.chdir(full_build_dir) environment_prefix = '' if args.preset and (args.preset.find('linux') != -1 and args.preset.find('universal') != -1): if args.preset.find('32') != -1: os.environ['LD_FLAGS'] = '{} {}'.format( os.environ.get('LD_FLAGS', ''), '-m32') environment_prefix = 'CC=gcc CXX=g++' command = "%s cmake %s %s %s" % (environment_prefix, '-G \"%s\"' % args.generator if args.generator else '', args.params, project_dir) print(command) check_call(command, shell=True) if args.nobuild: exit(0) for f in os.listdir(full_build_dir): path, ext = os.path.splitext(f) if ext == ".zip": os.remove(os.path.join(full_build_dir, f)) if args.generator.find("Unix Makefiles") != -1: make_args = '' if args.buildVerbose: make_args += ' VERBOSE=1' if args.mtbuild: make_args += ' -j{} '.format(get_cpu_count()) check_call("make package %s" % (make_args), shell=True) check_call("make install", shell=True) elif args.generator.find("Xcode") != -1: check_call("cmake --build . --target package --config %s" % (args.config), shell=True) check_call("cmake --build . --target install --config %s" % (args.config), shell=True) elif args.generator.find("Visual Studio") != -1 or auto_vs: vsenv = os.environ if args.mtbuild: vsenv = dict(os.environ, CL='/MP') check_call("cmake --build . --target PACKAGE --config %s" % (args.config), env=vsenv, shell=True) check_call("cmake --build . --target INSTALL --config %s" % (args.config), shell=True) elif args.generator.find("MinGW Makefiles") != -1: check_call("mingw32-make package", shell=True) check_call("mingw32-make install", shell=True) else: print("Do not know how to run package and install target") check_call("ctest -V --timeout 60 -C %s ." % (args.config), shell=True) os.chdir(root) if not os.path.exists("dist"): os.mkdir("dist") dist_dir = os.path.join(root, "dist") zip_path_vec = [] for f in os.listdir(full_build_dir): path, ext = os.path.splitext(f) if ext == ".zip": zip_path = os.path.join(dist_dir, f) shutil.copy(os.path.join(full_build_dir, f), zip_path) zip_path_vec.append(zip_path) return (zip_path_vec)
def tts_converter(content): LOG.debug(u"start: [{}]".format(content).decode('utf-8')) # Get the file object for the appropriate prefix sound and if the content # always changes, then don't save the file (recycle it) openhab_conf = System.getenv("OPENHAB_CONF") alert_prefix = File.separator.join( [openhab_conf, "html", "TTS", "Alert_Prefix.mp3"]) recycled = False if "Weather Alert:" in content: alert_prefix = File.separator.join( [openhab_conf, "html", "TTS", "Alert_Weather.mp3"]) recycled = True elif any(alert_type in content for alert_type in FLITE_TTS_CONFIGURATION["recycle"]): recycled = True file_name = "recycled.wav" if not recycled: # Since the file is being saved, truncate the filename to 150 allowed characters file_name = re.sub("[^a-zA-Z0-9_.-]", "", content) if len(file_name) > 149: file_name = file_name[0:149] file_name = "{}.wav".format(file_name) # Substitute text to help TTS pronounce some words content_scrubbed = content for key, value in FLITE_TTS_CONFIGURATION["substitutions"].items(): content_scrubbed = content_scrubbed.replace(key, value) # Set paths and files, creating them if they do not exist voice = File(FLITE_TTS_CONFIGURATION["path_to_voice"]).getName() directory_path_name = File.separator.join( [openhab_conf, "html", "TTS", voice]) directory_path = File(directory_path_name) if not directory_path.exists(): directory_path.mkdir() file_path_name = File.separator.join([directory_path_name, file_name]) file_path = File(file_path_name.replace(".wav", ".mp3")) # If it does not yet exist, generate the TTS if recycled or not file_path.exists(): Exec.executeCommandLine( "{}@@-voice@@{}@@-t@@{}@@-o@@{}".format( FLITE_TTS_CONFIGURATION["path_to_flite"], FLITE_TTS_CONFIGURATION["path_to_voice"], content_scrubbed, file_path_name), 60000) Exec.executeCommandLine( "{}@@-y@@-i@@{}@@-af@@volume=10, highpass=f=500, lowpass=f=3000@@{}" .format(FLITE_TTS_CONFIGURATION["path_to_ffmpeg"], file_path_name, file_path_name.replace(".wav", ".mp3")), 60000) Exec.executeCommandLine( "{} -y -i \"concat:{}|{}\" -c copy {}".format( FLITE_TTS_CONFIGURATION["path_to_ffmpeg"], alert_prefix, file_path_name.replace(".wav", ".mp3"), file_path_name.replace(".wav", ".combined.mp3")), 60000) # Create the URL used in the PlayURI result = "http://{}:{}/static/TTS/{}/{}".format( HOST_PORT_CONFIGURATION.get("openhab").get("host"), HOST_PORT_CONFIGURATION.get("openhab").get("port"), voice, file_name.replace(".wav", ".combined.mp3")) LOG.debug(u"complete: [{}]".format(content).decode('utf-8')) return result
def launchFiji(args, workingDir = None): args.insert(0, System.getProperty('fiji.executable')) try: launchProgram(args, workingDir) except: return -1
def onQuit(self, e): System.exit(0)
def onAdvEvent(self, event, npc, player): if event == "Soul of Water Ashutar has despawned": npc.reduceCurrentHp(9999999, npc, None) self.addSpawn(31560, 105452, -36775, -1050, 34000, False, 0, True) AutoChat( npc, "The fetter strength is weaken Your consciousness has been defeated!" ) return elif event == "spawn_npc": self.addSpawn(31560, 105452, -36775, -1050, 34000, False, 0, True) return st = player.getQuestState(qn) if not st: return cond = st.getInt("cond") id = st.getInt("id") Green_Totem = st.getQuestItemsCount(Totem2) Heart = st.getQuestItemsCount(Ice_Heart) htmltext = event if event == "31372-04.htm": if st.getPlayer().getLevel() >= 75 and st.getPlayer( ).getAllianceWithVarkaKetra() >= 2: if Green_Totem: st.set("cond", "1") st.set("id", "1") st.setState(State.STARTED) st.playSound("ItemSound.quest_accept") htmltext = "31372-04.htm" else: htmltext = "31372-02.htm" st.exitQuest(1) else: htmltext = "31372-03.htm" st.exitQuest(1) elif event == "31372-08.htm": if Heart: htmltext = "31372-08.htm" st.takeItems(Ice_Heart, -1) st.addExpAndSp(10000, 0) ObjectId = st.getPlayer().getObjectId() st.getPlayer().broadcastPacket(SocialAction(ObjectId, 3)) st.unset("id") st.unset("cond") st.playSound("ItemSound.quest_finish") st.exitQuest(1) else: htmltext = "31372-09.htm" elif event == "31560-02.htm": if Green_Totem == 0: htmltext = "31560-04.htm" else: if self.gstate.getState() == StateEnum.INTERVAL: if System.currentTimeMillis() < self.gstate.getRespawnDate( ): return "<html><body><center><br>No time to call</body></html>" spawnedNpc = st.addSpawn(Ashutar, 104825, -36926, -1136) st.takeItems(Totem2, 1) st.set("id", "2") npc.deleteMe() st.set("cond", "2") self.startQuestTimer("Soul of Water Ashutar has despawned", 1200000, spawnedNpc, None) AutoChat( spawnedNpc, "The water charm then is the storm and the tsunami strength! Opposes with it only has the blind alley!" ) return htmltext
def resetBuffer(self): self.CurrentBuffer = StringBuffer() self.CurrentBuffer.append("<file_created time=\"") self.CurrentBuffer.append( (Date(System.currentTimeMillis())).toString()) self.CurrentBuffer.append("\">\n")
import ij from ij import IJ, Macro from fiji.tool import AbstractTool from ini.trakem2 import Project, ControlWindow from ini.trakem2.display import Patch, Display from ini.trakem2.utils import Utils from mpicbg.trakem2.align import Align, AlignTask import sys sys.path.append(IJ.getDirectory('plugins')) import fijiCommon as fc import java from java.lang import System System.setProperty('javax.xml.parsers.SAXParserFactory', 'com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl') def xyToN(x, y, nX): return y * nX + (nX - x - 1) namePlugin = 'assembly_EM' MagCFolder = fc.startPlugin(namePlugin) MagCParameters = fc.readMagCParameters(MagCFolder) ControlWindow.setGUIEnabled(False) MagC_EM_Folder = os.path.join(MagCFolder, 'MagC_EM','') # read metadata EMMetadataPath = fc.findFilesFromTags(MagCFolder,['EM_Metadata'])[0] EMMetadata = fc.readParameters(EMMetadataPath) numTilesX = EMMetadata['numTilesX']
from com.collation.platform.security.auth import AuthManager from com.collation.platform.security.auth import EMCViprSRMAuth from com.collation.discover.agent import AgentException import sys import java import time from java.lang import System coll_home = System.getProperty("com.collation.home") System.setProperty( "jython.home", coll_home + "/osgi/plugins/com.ibm.cdb.core.jython253_2.5.3/lib") System.setProperty( "python.home", coll_home + "/osgi/plugins/com.ibm.cdb.core.jython253_2.5.3/lib") jython_home = System.getProperty("jython.home") sys.path.append(jython_home + "/Lib") sys.path.append(coll_home + "/lib/sensor-tools") sys.prefix = jython_home + "/Lib" import traceback import sensorhelper import urllib2 # for HTTP REST API ######################################################## # Some default GLOBAL Values (Typically these should be in ALL CAPS) # Jython does not have booleans
# -*- coding: UTF-8 -*- # From github.com/villares/villares/ubuntu_jogl_fix.py from java.lang import System System.setProperty("jogl.disable.openglcore", "false")
def getuser(): return System.getProperty("user.name")
def gethome(): return System.getProperty("user.home")
print "Try to parse %s" % filename # Set up a simple configuration that logs on the console. BasicConfigurator.configure() format = sys.argv[2] if format == "0.91": parser = RSS_0_91_Parser() else: parser = RSS_1_0_Parser() builder = ChannelBuilder() parser.setBuilder(builder) # time has come to actually start working start_time = System.currentTimeMillis() channel = parser.parse(File(filename).toURL()) end_time = System.currentTimeMillis() print "Parsing took %d milliseconds." % (end_time - start_time) # display a bit print print "Channel: %s (%s)" % (channel.getTitle(), channel.getDescription()) print " %s" % channel.getSite() print for item in channel.getItems(): print " - %s" % item.getTitle() print " [Id: %s]" % item.getId() print " link to %s" % item.getLink() if item.getDescription():
'username': configuration.username, 'password': configuration.password, 'proxyHost': configuration.proxyHost, 'proxyPort': configuration.proxyPort, 'domain': configuration.domain, 'authenticationMethod': configuration.authenticationMethod } # do an http request to the server response = HttpRequest(params).get('/_apis/projectcollections', contentType='application/json') # check response status code, if is different than 200 exit with error code if response.status != 200: sys.exit(1) elif configuration.preferredLibType == 'SDK': System.setProperty("com.microsoft.tfs.jni.native.base-directory", os.getcwd() + "/conf/native") collectionUrl = configuration.url + "/" if configuration.authenticationMethod == 'Ntlm': credentials = NTCredentials(configuration.username, configuration.domain, configuration.password) else: credentials = UsernamePasswordCredentials(configuration.username, configuration.password) tpc = TFSTeamProjectCollection(URIUtils.newURI(collectionUrl), credentials) workItemClient = tpc.getWorkItemClient()
project.simulationParameters.setReference(sim_ref) # create gap junction graph object gj_graph = utils.random_graph_heterogeneous_synapses(cell_positions) # delete all existing synaptic connections and associated information project.generatedNetworkConnections.reset() project.morphNetworkConnectionsInfo.deleteAllNetConns() # generate connections according to graph utils.nC_generate_gj_network_from_graph(project, sim_config, gj_graph, 'Golgi_network_reduced', 'GJGolgi_Reduced', ['GCL', 'ML1', 'ML2', 'ML3'], 'Golgi_gap_2010') # export generated network structure to graphml for debugging utils.nC_network_to_graphml( project, '/home/ucbtepi/thesis/data/GoC_net_structures/graph_' + sim_ref + '.graphml') if simulate: # generate, compile and run NEURON files remote_sim_refs = utils.nC_generate_NEURON_and_submit(pm, project, sim_config, sim_ref, remote_sim_refs, run_time=14) if remote_sim_refs: utils.wait_and_pull_remote(remote_sim_refs, sleep_time=0.5) print('timestamp ' + timestamp) System.exit(0)
def windowClosed(self, evt): import java.lang.System as System System.exit(0)