def startJVM(): global JasperCompileManager, JasperFillManager, JasperExportManager, \ JRPdfExporter, JRRtfExporter, JRHtmlExporter, JRXlsExporter, \ JRExporterParameter, JRPdfExporterParameter, JRrtfExporterParameter, JRXlsExporterParameter, \ JRLoader, JRParameter,JRXmlDataSource, JRXPathQueryExecuterFactory, JRXmlUtils _jvmArgs = ["-ea"] # enable assertions _jvmArgs.append("-Djava.ext.dirs=%s" % pathToJRLibs) jpype.startJVM(JVMPath, *_jvmArgs) # JasperCompileManager= jpype.JClass("net.sf.jasperreports.engine.JasperCompileManager") JasperFillManager= jpype.JClass("net.sf.jasperreports.engine.JasperFillManager") JasperExportManager= jpype.JClass("net.sf.jasperreports.engine.JasperExportManager") JRPdfExporter= jpype.JClass("net.sf.jasperreports.engine.export.JRPdfExporter") JRRtfExporter= jpype.JClass("net.sf.jasperreports.engine.export.JRRtfExporter") JRHtmlExporter= jpype.JClass("net.sf.jasperreports.engine.export.JRHtmlExporter") JRXlsExporter= jpype.JClass("net.sf.jasperreports.engine.export.JRXlsExporter") # JRParameter= jpype.JClass("net.sf.jasperreports.engine.JRParameter") JRExporterParameter= jpype.JClass("net.sf.jasperreports.engine.JRExporterParameter") JRPdfExporterParameter= jpype.JClass("net.sf.jasperreports.engine.export.JRPdfExporterParameter") JRXlsExporterParameter= jpype.JClass("net.sf.jasperreports.engine.export.JRXlsExporterParameter") JRLoader= jpype.JClass("net.sf.jasperreports.engine.util.JRLoader") JRXmlDataSource=jpype.JClass("net.sf.jasperreports.engine.data.JRXmlDataSource") JRXPathQueryExecuterFactory=jpype.JClass("net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory") JRXmlUtils=jpype.JClass("net.sf.jasperreports.engine.util.JRXmlUtils")
def jvm(max_mem=None): """Return the jpype module, after guaranteeing the JVM is running and the classpath has been loaded properly.""" jarpaths = (os.path.abspath( os.path.join(os.path.dirname(__file__), "../lib")), os.path.abspath( os.path.join(os.path.dirname(__file__), "../dist"))) log4j_properties_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "../log4j.properties")) if not jpype.isJVMStarted(): max_mem = get_jvm_max_mem(max_mem) LOG.debug("Default JVM path is %s" % jpype.getDefaultJVMPath()) jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s:%s" % jarpaths, # "-Dlog4j.debug", # turn on log4j internal debugging "-Dlog4j.configuration=file://%s" % log4j_properties_path, "-Xmx%sM" % max_mem) # override the log level set in log4j configuration file this can't be # done on the JVM command line (i.e. -Dlog4j.rootLogger= is not # supported by log4j) _set_java_log_level(FLAGS.debug.upper()) if FLAGS.capture_java_debug: _setup_java_capture(sys.stdout, sys.stderr) return jpype
def check(self, textkey, data, config): try: import jpype from jpype import java, javax if not jpype.isJVMStarted(): jpype.startJVM(config['jvm_path']) jhash = java.util.HashMap() jarray = jpype.JArray(java.lang.String)([config['username'], config['password']]) jhash.put(javax.management.remote.JMXConnector.CREDENTIALS, jarray) url = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi" % (config['host'], int(config['port'])) jmxurl = javax.management.remote.JMXServiceURL(url) jmxsoc = javax.management.remote.JMXConnectorFactory.connect(jmxurl, jhash) connection = jmxsoc.getMBeanServerConnection() parts = data.split("/", 3) obj = parts[0] attribute = parts[1] if len(parts) == 3: key = parts[2] else: key = None res = connection.getAttribute(javax.management.ObjectName(obj), attribute) if key: res = res.contents.get(key) return res.floatValue() except: return 0
def __init__(self, class_schema_definition_dicts={}, class_abrv_lookup={}, \ use_weka_jvm=True, training_arff_features_list=[]): self.class_schema_definition_dicts = class_schema_definition_dicts self.training_arff_features_list = training_arff_features_list self.arffmaker = arffify.Maker(search=[], \ skip_class=True, local_xmls=True, dorun=False, \ class_abrv_lookup=class_abrv_lookup) if use_weka_jvm: # TODO/NOTE: I think a WekaClassifier() class needs to be # instantiated for each WEKA classification instance # which uses a different .model and/or training .arff # We initialize a Java virtual machine for Weka classifications #try: if not jpype.isJVMStarted(): #TODO / DEBUG: disable the next line for speed-ups once stable? _jvmArgs = ["-ea"] # enable assertions _jvmArgs.append("-Djava.class.path=" + \ os.environ["CLASSPATH"]) ###20091905 dstarr comments out: #_jvmArgs.append("-Xmx1000m") _jvmArgs.append("-Xmx12000m") # 4000 & 5000m works, 3500m doesnt for some WEKA .models jpype.startJVM(jpype.getDefaultJVMPath(), *_jvmArgs) class_schema_name_list = self.class_schema_definition_dicts.keys() class_schema_name_list.remove('mlens3 MicroLens') class_schema_name_list.remove('Dovi SN') class_schema_name_list.remove('General') self.wc = {} for class_schema_name in class_schema_name_list: class_schema_dict = self.class_schema_definition_dicts[class_schema_name] weka_training_model_fpath = class_schema_dict['weka_training_model_fpath'] weka_training_arff_fpath = class_schema_dict['weka_training_arff_fpath'] self.wc[class_schema_name] = weka_classifier.WekaClassifier( \ weka_training_model_fpath, weka_training_arff_fpath)
def initjvm(): global _jvm_initialized if (not _jvm_initialized): LOG.debug("Starting JVM...") startJVM(getDefaultJVMPath(), "-ea") java.lang.System.out.println("JVM Running") _jvm_initialized = True
def classGen( ) : global Modifier root = os.path.abspath( os.path.dirname( __file__ ) ) cp = os.path.abspath(root+"/../../build-support/jasmin.jar;"+root+"/../../_bin;"+root+"/../../_classgen") jpype.startJVM( jpype.getDefaultJVMPath( ), "-ea", "-Djava.class.path=%s"%cp) Modifier = jpype.JClass( "java.lang.reflect.Modifier" ) try : # base = jpype.JClass("javax.swing.JFrame") base = jpype.JClass( "java.lang.Object" ) intf = [ jpype.JClass( "java.lang.Comparable" ), #jpype.JClass("javax.swing.CellEditor"), ] try : result = generateClass( "com.darkwolf.jpype.classgen.TestClass", base, intf, "../../_classgen" ); dumpClassInformation( result ); except : import traceback traceback.print_exc( ) finally : jpype.shutdownJVM( )
def _inner(*args, **kwargs): if not jpype.isJVMStarted(): jpype.startJVM(jvm_path) ret_val = func(*args, **kwargs) return ret_val
def __init__(self,libjvm='/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.65-2.b17.el7_1.x86_64/jre/lib/amd64/server/libjvm.so'): try: logger.debug(libjvm) jpype.startJVM(libjvm) except RuntimeError, e: logger.error(e) raise JVM_Import_Error()
def startCli() : # These are the lines to start up the the java <--> python bridge # We add the lib directory to the jar path, it expects there to be a jar # of the OpenSHA + gem build. # We also add the parent folder, so that the contents of the 'data' folder # Can be accessed with getResource from within java jarpath = os.path.join(os.path.abspath('..'), 'lib') classpath = os.path.abspath('..') jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.ext.dirs=%s:%s' % (jarpath, classpath)) # These lines are the same as the imports in Java CalculatorConfigData = jpype.JClass( 'org.opensha.gem.GEM1.calc.gemLogicTreeProcessor.CalculatorConfigData') LogicTreeProcessor = jpype.JClass( 'org.opensha.gem.GEM1.calc.gemLogicTreeProcessor.LogicTreeProcessor') ErfLogicTreeData = jpype.JClass( 'org.opensha.gem.GEM1.calc.gemLogicTreeProcessor.ErfLogicTreeData') GmpeLogicTreeData = jpype.JClass( 'org.opensha.gem.GEM1.calc.gemLogicTreeProcessor.GmpeLogicTreeData') InputModelData = jpype.JClass( 'org.opensha.gem.GEM1.calc.gemLogicTreeProcessor.InputModelData') # We can instantiate python classes as python-normal # calculator = LogicTreeProcessor() calcConfigData = CalculatorConfigData("CalculatorConfig.inp")
def jvm(): """ Return the jpype module, after guaranteeing the JVM is running and the classpath has been loaded properly. """ jarpaths = (os.path.abspath( os.path.join(os.path.dirname(__file__), "../dist")), '/usr/share/java') if not jpype.isJVMStarted(): max_mem = get_jvm_max_mem() jpype.startJVM(jpype.getDefaultJVMPath(), "-Xmx%sM" % max_mem, "-Djava.ext.dirs=%s:%s" % jarpaths, # setting Schema path here is ugly, but it's better than # doing it before all XML parsing calls "-Dopenquake.nrml.schema=%s" % nrml.nrml_schema_file(), # force the default Xerces parser configuration, otherwise # some random system-installed JAR might override it "-Dorg.apache.xerces.xni.parser.XMLParserConfiguration=" \ "org.apache.xerces.parsers.XIncludeAwareParserConfiguration") _init_logs() return jpype
def _jdbc_connect_jpype(jclassname, *args): import jpype # Ensure JVN is running if not jpype.isJVMStarted(): jpype.startJVM(jpype.getDefaultJVMPath()) # Connect Jpype to JVM Thread if not jpype.isThreadAttachedToJVM(): jpype.attachThreadToJVM() # Initialize Type Conversion Mapping if _converters is None: types = jpype.java.sql.Types types_map = {} for i in types.__javaclass__.getClassFields(): types_map[i.getName()] = i.getStaticAttribute() _init_converters(types_map) global _java_array_byte if _java_array_byte is None: def _java_array_byte(data): return jpype.JArray(jpype.JByte, 1)(data) # register driver for DriverManager jpype.JClass(jclassname) return jpype.java.sql.DriverManager.getConnection(*args)
def file2tasks(self, f1): fr = open(f1, 'r') tasks = [] for line in fr: line = line.rstrip("\n") arr2 = line.split("\t") # path, params, tbin, tbout, time, line tasks.append( (arr2[0], arr2[2], arr2[5].split(",") if arr2[5] else [], arr2[6].split(",") if arr2[6] else [], float(arr2[7]), line)) fr.close() out2id=dict([(ot, t[0]) for t in tasks for ot in t[3]]) id2time=dict([(t[0], t[4]) for t in tasks]) id2time["_end_"] = 0.0 edges=[(out2id[it], t[0], id2time[out2id[it]]) for t in tasks for it in t[2]] edges += [(t[0], "_end_", id2time[t[0]]) for t in tasks] vs = [id for id in id2time.keys()] id2i = dict([(id, i) for i, id in enumerate(vs)]) edges2A4 = [(id2i[e[0]], id2i[e[1]], e[2]) for e in edges] graphfile = f1 + ".graph" graphfw = open(graphfile, 'w') graphfw.write("%s\n" % len(id2i)) graphfw.write("%s\n" % len(edges2A4)) [graphfw.write("%s %s %s\n" %(e[0], e[1], e[2])) for e in edges2A4] graphfw.close() jarpath = "/home/wangdawei/github/algs4/target/algs4-1.0.0.0.jar" jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath) AcycleLPSort = jpype.JClass('edu.princeton.cs.algs4.AcycleLPSort') acycleLPSort = AcycleLPSort() res = acycleLPSort.sort(graphfile) i2v = dict([(e.i, e.d) for e in res]) jpype.shutdownJVM() return [(id, status, ins, outs, runtime, i2v[id2i[id]], line) for id, status, ins, outs, runtime, line in tasks]
def __init__(self, playerID): jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % os.path.abspath(".")) Move = jpype.JClass("kalah.Move") self.jmove = Move(playerID) Player.__init__(self, playerID)
def __init__(self, jar_filename=None, download_if_missing=False, version=None, extra_jvm_args=None, start_jpype=True, jvm_path=None): """extra_jvm_args can be set to a list of strings which will be passed to your JVM. If start_jpype is True, we will start a JVM via JPype if one hasn't been started already. The user is responsible for stopping the JVM (jpype.shutdownJVM()) when they are done converting. Once the JVM has been shutdown, you'll need to create a new JPypeBackend in order to convert after that. jvm_path is the path to libjvm.so (if None, will use JPype's default JRE path).""" StanfordDependencies.__init__(self, jar_filename, download_if_missing, version) if start_jpype and not jpype.isJVMStarted(): jpype.startJVM(jvm_path or jpype.getDefaultJVMPath(), '-ea', '-Djava.class.path=' + self.jar_filename, *(extra_jvm_args or [])) self.corenlp = jpype.JPackage('edu').stanford.nlp try: self.acceptFilter = self.corenlp.util.Filters.acceptFilter() except TypeError: # this appears to be caused by a mismatch between CoreNLP and JRE # versions since this method changed to return a Predicate. version = jpype.java.lang.System.getProperty("java.version") self._report_version_error(version) trees = self.corenlp.trees self.treeReader = trees.Trees.readTree self.converter = trees.EnglishGrammaticalStructure self.universal_converter = trees.UniversalEnglishGrammaticalStructure # we now need to test whether we can actually create a universal # converter -- we'll call it with invalid number of arguments # since we don't want create a tree just for this try: self.universal_converter() except TypeError: # this is JPype's way of saying that it doesn't exist so we # fall back to the original converter self.universal_converter = self.converter except RuntimeError as re: # this means it exists but wanted a different number of arguments # (in other words, we have a universal converter) assert "No matching overloads found" in str(re) try: self.stemmer = \ self.corenlp.process.Morphology.stemStaticSynchronized except AttributeError: # stemStaticSynchronized was renamed in CoreNLP 3.6.0 to stemStatic self.stemmer = \ self.corenlp.process.Morphology.stemStatic puncFilterInstance = trees.PennTreebankLanguagePack(). \ punctuationWordRejectFilter() try: self.puncFilter = puncFilterInstance.test except AttributeError: self.puncFilter = puncFilterInstance.accept self.lemma_cache = {}
def start(heapSizeMiB=1024, enableAssertions=False, stackSizeMiB=None, garbageSizeMiB=None, allowRemoteManagement=False): # build JVM launch args args = [ jpype.getDefaultJVMPath(), '-Xmx%dM' % heapSizeMiB, '-Djava.class.path=%s' % makeClasspath() ] if enableAssertions: args.append("-ea") if stackSizeMiB is not None: args.append('-Xss%sM' % stackSizeMiB) if garbageSizeMiB is not None: args.append('-XX:MaxNewSize=%dM' % garbageSizeMiB) if _nativesDir is not None: args.append('-Djava.library.path=%s' % _nativesDir) if allowRemoteManagement: args.append('-Dcom.sun.management.jmxremote.ssl=false') args.append('-Dcom.sun.management.jmxremote.authenticate=false') args.append('-Dcom.sun.management.jmxremote.port=9010') args.append('-Dcom.sun.management.jmxremote.rmi.port=9011') args.append('-Djava.rmi.server.hostname=localhost') args.append('-Dcom.sun.management.jmxremote.local.only=false') # start the JVM jpype.startJVM(*args) # set up class factories global c c = Packages() c.java = jpype.JPackage('java') c.javax = jpype.JPackage('javax')
def jvm(max_mem=4000): """Return the jpype module, after guaranteeing the JVM is running and the classpath has been loaded properly.""" jarpaths = (os.path.abspath( os.path.join(os.path.dirname(__file__), "../lib")), os.path.abspath( os.path.join(os.path.dirname(__file__), "../dist"))) # TODO(JMC): Make sure these directories exist # LOG.debug("Jarpath is %s", jarpaths) if not jpype.isJVMStarted(): LOG.debug("Default JVM path is %s" % jpype.getDefaultJVMPath()) jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s:%s" % jarpaths, #"-Dnet.spy.log.LoggerImpl=net.spy.memcached.compat.log.Log4JLogger", # "-Dlog4j.debug", "-Dlog4j.configuration=log4j.properties", "-Dlog4j.rootLogger=%s, A1" % (FLAGS.debug.upper()), # "-Dlog4j.rootLogger=DEBUG, A1", "-Xmx%sM" % max_mem) if FLAGS.capture_java_debug: mystream = jpype.JProxy("org.gem.IPythonPipe", inst=sys.stdout) errstream = jpype.JProxy("org.gem.IPythonPipe", inst=sys.stderr) outputstream = jpype.JClass("org.gem.PythonOutputStream")() err_stream = jpype.JClass("org.gem.PythonOutputStream")() outputstream.setPythonStdout(mystream) err_stream.setPythonStdout(errstream) ps = jpype.JClass("java.io.PrintStream") jpype.java.lang.System.setOut(ps(outputstream)) jpype.java.lang.System.setErr(ps(err_stream)) return jpype
def init_jvm(jvmpath=None): """Initializes the Java virtual machine (JVM). :param jvmpath: The path of the JVM. If left empty, inferred by :py:func:`jpype.getDefaultJVMPath`. """ if jpype.isJVMStarted(): logging.warning('JVM is already running. Do not init twice!') return folder_suffix = ['{0}', '{0}{1}bin',\ '{0}{1}jhannanum-0.8.4.jar',\ '{0}{1}kkma-2.0.jar',\ '{0}{1}komoran-2.4-e.jar',\ '{0}{1}shineware-common-2.0.jar', '{0}{1}shineware-ds-1.0.jar',\ '{0}{1}snakeyaml-1.12.jar', '{0}{1}scala-library-2.11.4.jar', '{0}{1}twitter-korean-text-2.4.3.jar', '{0}{1}twitter-text-1.10.1.jar',\ '{0}{1}*'] javadir = '%s%sjava' % (utils.installpath, os.sep) args = [javadir, os.sep] classpath = os.pathsep.join(f.format(*args) for f in folder_suffix) jvmpath = jvmpath or jpype.getDefaultJVMPath() if jvmpath: jpype.startJVM(jvmpath, '-Djava.class.path=%s' % classpath,\ '-Dfile.encoding=UTF8',\ '-ea', '-Xmx768m') else: raise ValueError("Please specify the JVM path.")
def _jdbc_connect_jpype(jclassname, jars, libs, *driver_args): import jpype if not jpype.isJVMStarted(): args = [] class_path = [] if jars: class_path.extend(jars) class_path.extend(_get_classpath()) if class_path: args.append('-Djava.class.path=%s' % os.path.pathsep.join(class_path)) if libs: # path to shared libraries libs_path = os.path.pathsep.join(libs) args.append('-Djava.library.path=%s' % libs_path) # jvm_path = ('/usr/lib/jvm/java-6-openjdk' # '/jre/lib/i386/client/libjvm.so') jvm_path = jpype.getDefaultJVMPath() jpype.startJVM(jvm_path, *args) if not jpype.isThreadAttachedToJVM(): jpype.attachThreadToJVM() if _jdbc_name_to_const is None: types = jpype.java.sql.Types types_map = {} for i in types.__javaclass__.getClassFields(): types_map[i.getName()] = i.getStaticAttribute() _init_types(types_map) global _java_array_byte if _java_array_byte is None: def _java_array_byte(data): return jpype.JArray(jpype.JByte, 1)(data) # register driver for DriverManager jpype.JClass(jclassname) return jpype.java.sql.DriverManager.getConnection(*driver_args)
def init_jpype(): build_dir = os.path.join( os.path.abspath(os.path.split(__file__)[0]), 'build' ) jpath = jpype.getDefaultJVMPath() jpype.startJVM(jpath, "-ea", "-Djava.ext.dirs=%s" % build_dir)
def __init__(self, connect, driver, user, password,isolation=''): config_parser = SafeConfigParser() config_parser.read(PATH_JDBC_CFG) # since it is impossible to call jpype.isThreadAttachedToJVM() before jpype.startJVM() # we won't check if JVM is started. classpath = config_parser.get("JVM", "classpath") javaHome = config_parser.get("JVM", "java_home") if (javaHome[0] != '/'): javaHome = "%s/%s" % (etl_util.get_app_root_path(), javaHome) args='-Djava.class.path=%s' % classpath try: os.environ['JAVA_HOME'] = javaHome jvm_path = jpype.getDefaultJVMPath() except TypeError: logging.error("failed to get default JVM path") raise if (jpype.isJVMStarted() == False): jpype.startJVM(jvm_path, args) logging.debug("Connecting with %s to %s with user %s" % (driver, connect, user)) self.conn = jaydebeapi.connect(driver, connect, user, password) #set isolation level if isolation!='': if 'mysql' in driver: sql='SET SESSION TRANSACTION ISOLATION LEVEL %s' % isolation elif 'teradata' in driver: sql='SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL %s' % isolation self._execute(sql)
def startJVM(self): global mbeanServer,dominio,puerto print os.path.abspath('.') classpath = os.path.join(os.path.abspath('.')) print jpype.getDefaultJVMPath() jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.awt.headless=true',"-ea", "-Dvisualvm.display.name="+dominio+":"+str(puerto), "-Dcom.sun.management.jmxremote", "-Dcom.sun.management.jmxremote.port="+str(puerto), "-Dcom.sun.management.jmxremote.authenticate=false", "-Dcom.sun.management.jmxremote.ssl=false", "-Djava.class.path=simple-xml-2.6.9.jar:%s" % classpath) mbeanServer = java.lang.management.ManagementFactory.getPlatformMBeanServer();
def __startJVM(self): """ Initializes Java Virtual Machine and loads symmetrizer """ # Path to the jar file jarpath = os.path.join(None) try: jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % (jarpath)) self._globJVMOn = True self._globJVMJar = JPackage('net.webmo.symmetry').Main messages.log(__name__, "JVM initialised!", verbose=1) # Hello world from Java jpype.java.lang.System.out.println("Java: hello world!") #TODO: In future this should be done via streams fs = jpype.JClass("java.io.File") ps = jpype.JClass("java.io.PrintStream") # Directing the output jpype.java.lang.System.setOut(ps(fs(self._globJVMOutPath))) jpype.java.lang.System.setErr(ps(fs(self._globJVMErrPath))) except: self._globJVMOn = False self._globJVMJar = None messages.warning(__name__, "Cannot start JVM!", verbose=0)
def initJava(JAVA_HOME=None, SX_JAR=None): global gIsJavaInitialized if gIsJavaInitialized: return if not JAVA_HOME: JAVA_HOME = SX_environ.get_JAVA_HOME() if not SX_JAR: SX_JAR = SX_environ.get_SX_JAR() os.environ['JAVA_HOME'] = JAVA_HOME options = [ '-Djava.class.path=%s' % SX_JAR ] jvmPath = jpype.getDefaultJVMPath() if not jvmPath: jvmPath = os.path.join(JAVA_HOME, "bin", "client", "jvm.dll") if not os.path.isfile(jvmPath): print >>sys.stderr, "JVM dll doesn't exist at %s" % jvmPath return False try: print "Before Start" jpype.startJVM(jvmPath, *options) print "After Start" except: traceback.print_exc() return False gIsJavaInitialized = True return True
def __init__(self, gui=False, thd=False): ''' Create a link with netlogo. Underneath, the netlogo jvm is started through jpype. :param gui: boolean, if true run netlogo with gui, otherwise run in headless mode. Defaults to false. :param thd: boolean, if thrue start netlogo in 3d mode. Defaults to false ''' if not jpype.isJVMStarted(): # netlogo jars jars = [NETLOGO_HOME + r'/lib/scala-library.jar', NETLOGO_HOME + r'/lib/asm-all-3.3.1.jar', NETLOGO_HOME + r'/lib/picocontainer-2.13.6.jar', NETLOGO_HOME + r'/lib/log4j-1.2.16.jar', NETLOGO_HOME + r'/lib/jmf-2.1.1e.jar', NETLOGO_HOME + r'/lib/pegdown-1.1.0.jar', NETLOGO_HOME + r'/lib/parboiled-core-1.0.2.jar', NETLOGO_HOME + r'/lib/parboiled-java-1.0.2.jar', NETLOGO_HOME + r'/lib/mrjadapter-1.2.jar', NETLOGO_HOME + r'/lib/jhotdraw-6.0b1.jar', NETLOGO_HOME + r'/lib/quaqua-7.3.4.jar', NETLOGO_HOME + r'/lib/swing-layout-7.3.4.jar', NETLOGO_HOME + r'/lib/jogl-1.1.1.jar', NETLOGO_HOME + r'/lib/gluegen-rt-1.1.1.jar', NETLOGO_HOME + r'/NetLogo.jar', PYNETLOGO_HOME + r'/external_files/netlogoLink.jar'] # format jars in right format for starting java virtual machine # TODO the use of the jre here is only relevant under windows # apparently # might be solvable by setting netlogo home user.dir joined_jars = jar_separator.join(jars) jarpath = '-Djava.class.path={}'.format(joined_jars) jvm_handle = jpype.getDefaultJVMPath() jpype.startJVM(jvm_handle, jarpath, "-Xms128M","-Xmx1024m") jpype.java.lang.System.setProperty('user.dir', NETLOGO_HOME) if sys.platform=='darwin': jpype.java.lang.System.setProperty("java.awt.headless", "true"); debug("jvm started") link = jpype.JClass('netlogoLink.NetLogoLink') debug('NetLogoLink class found') if sys.platform == 'darwin' and gui: info('on mac only headless mode is supported') gui=False self.link = link(gui, thd) debug('NetLogoLink class instantiated')
def fault_poly_from_mls(fault_source_geom, dip, upp_seis_depth, low_seis_depth): """Given a fault source geometry (as a MultiLineString), dip, upper seismogenic depth, lower seismogenic depth, and grid spacing (in km), create a 3D polygon to represent the fault. :param fault_source_geom: :class:`django.contrib.gis.geos.collections.MultiLineString` :param float dip: Angle of dip, from 0.0 to 90.0 degrees (inclusive) :param float upp_seis_depth: Upper seismogenic depth :param float low_seis_depth: Lower seismogenic depth :returns: 3D polygon representing the complete fault geometry :rtype: :class:`django.contrib.gis.geos.collections.Polygon` """ # I take no responsibility for writing this #: Value is in kilometers GRID_SPACING = 1.0 if not jpype.isJVMStarted(): # start jvm once jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % settings.GEOCLUDGE_JAR_PATH) FT = jpype.JClass('org.opensha.sha.faultSurface.FaultTrace') LOC = jpype.JClass('org.opensha.commons.geo.Location') LOC_LIST = jpype.JClass('org.opensha.commons.geo.LocationList') SGS = jpype.JClass('org.opensha.sha.faultSurface.StirlingGriddedSurface') coords = fault_source_geom.coords fault_trace = FT('') for line_str in coords: for lon, lat in line_str: # warning: the ordering of lat/lon is switched here # be careful loc = LOC(lat, lon) fault_trace.add(loc) surface = SGS(fault_trace, float(dip), float(upp_seis_depth), float(low_seis_depth), GRID_SPACING) # now we make a polygon with the perimeter coords: poly_coords = [] for per_loc in surface.getSurfacePerimeterLocsList(): lon = per_loc.getLongitude() lat = per_loc.getLatitude() depth = per_loc.getDepth() poly_coords.append((lon, lat, depth)) return Polygon(poly_coords)
def __init__(self): #~ jpype.startJVM('C:/Program Files (x86)/Java/jdk1.6.0_21/jre/bin/client/jvm.dll', '-Xmx800m') #~ jpype.startJVM(jpype.getDefaultJVMPath()) jpype.startJVM('/usr/lib/jvm/java-6-openjdk/jre/lib/amd64/server/libjvm.so', '-Xmx2000m') nlpPackage = jpype.JPackage('edu').stanford.nlp self.lexicalizedParser = nlpPackage.parser.lexparser.LexicalizedParser('englishPCFG.ser.gz') self.grammaticalStructureFactory = nlpPackage.trees.PennTreebankLanguagePack().grammaticalStructureFactory()
def _open(self): logger.info("Starting JVM") if isJVMStarted(): logger.warn("JVM is already started. Only one connection can be opened," "previously created connection will be used.") return startJVM(getDefaultJVMPath(), *self._jvm_args())
def setup_module(module): # Module-level setup. if not jpype.isJVMStarted(): jvm_args = [ '-Xmx%dM' % (MAX_JVM_HEAP_SIZE_BYTES // 1000 ** 2), ] jpype.startJVM(jpype.getDefaultJVMPath(), *jvm_args) module.JavaDoubleArray = jpype.JArray(jpype.JDouble, 1)
def startJvm(): import os os.environ.setdefault("STANFORD_PARSER_HOME", "3rdParty/stanford-parser/stanford-parser-2010-08-20") global stanford_parser_home stanford_parser_home = os.environ["STANFORD_PARSER_HOME"] jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s/stanford-parser.jar" % (stanford_parser_home),)
import pandas as pd import matplotlib.pyplot as plt from pathlib import Path Path.ls = lambda x: list(x.iterdir()) # In[3]: import jpype, math, random import os, sys from jpype import * # In[4]: try: jarLocation = "/home/fsf/software/inforDynamics-dist-1.5/infodynamics.jar" jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=" + jarLocation) except: print("JVM has already started !") # In[5]: sys.path.append('../../srcs') # In[6]: from jidt.data import example1, example2 # In[7]: x, y = example2(length=3000, noise_level=[0.1, 0.1])
import os import sys import subprocess packages = ['JPype1', 'selenium', 'tqdm', 'shapely'] for p in packages: subprocess.check_call([sys.executable, "-m", "pip", "install", p]) import argparse, posixpath, json import numpy as np import pandas as pd import time import jpype from jpype import imports from jpype.types import * jpype.addClassPath('./lib/OpenSHA-1.5.2.jar') jpype.startJVM("-Xmx8G", convertStrings=False) from CreateStation import * from CreateScenario import * from ComputeIntensityMeasure import * from SelectGroundMotion import * if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--hazard_config') args = parser.parse_args() with open(args.hazard_config) as f: hazard_info = json.load(f) # Directory
def testRestart(self): with self.assertRaises(OSError): jpype.startJVM()
outformats - a dictionary of supported output formats """ import os import sys if sys.platform[:4] == "java": # Jython import uk.ac.cam.ch.wwmm.opsin as opsin else: # CPython import jpype if not jpype.isJVMStarted(): _jvm = os.environ['JPYPE_JVM'] if _jvm[0] == '"': # Handle trailing quotes _jvm = _jvm[1:-1] _cp = os.environ['CLASSPATH'] jpype.startJVM(_jvm, "-Djava.class.path=" + _cp) opsin = jpype.JPackage("uk").ac.cam.ch.wwmm.opsin try: _nametostruct = opsin.NameToStructure.getInstance() _restoinchi = opsin.NameToInchi.convertResultToInChI except TypeError: raise ImportError("The OPSIN Jar file cannot be found.") informats = {'iupac': 'IUPAC name'} """A dictionary of supported input formats""" outformats = {'cml': "Chemical Markup Language", 'inchi': "InChI", 'smi': "SMILES"} """A dictionary of supported output formats""" def readstring(format, string):
import jpype import numpy as np from numpy import random jpype.startJVM(jpype.getDefaultJVMPath()) random.seed(44) values = np.random.randn(7) java_array = jpype.JArray(jpype.JDouble, 1)(values.tolist()) for item in java_array: jpype.java.lang.System.out.println(item) jpype.shutdownJVM()
# -*- coding: utf-8 -*- ## Zemberek: Document Correction Example # Documentation: https://github.com/ahmetaa/zemberek-nlp/tree/master/normalization # Java Code Example: https://github.com/ahmetaa/zemberek-nlp/blob/master/examples/src/main/java/zemberek/examples/normalization/CorrectDocument.java import jpype as jp # Relative path to Zemberek .jar ZEMBEREK_PATH = '../../bin/zemberek-full.jar' # Start the JVM jp.startJVM(jp.getDefaultJVMPath(), '-ea', '-Djava.class.path=%s' % (ZEMBEREK_PATH)) # Import required Java classes TurkishSpellChecker = jp.JClass('zemberek.normalization.TurkishSpellChecker') TurkishTokenizer = jp.JClass('zemberek.tokenization.TurkishTokenizer') TurkishLexer = jp.JClass('zemberek.tokenization.antlr.TurkishLexer') TurkishMorphology = jp.JClass('zemberek.morphology.TurkishMorphology') # A dummy data to work on dummy = ( ' Türk Vatanı ve Milletinin ebedi varlığxını ve Yüce Türk Devlatinin bölünmez bütünlüğünü belirleyen bu Anayasa,\n' + 'Türkiye Cumhuriyetinin kurucusu, ölümsüz önder ve eşsiz kahraman Atatürk’ün belirlediği milliyetçilik anlayışı ve onun\n' + 'inkılap ve ilkeleri doğrultusunda;\n' + 'Dünya milletleri ailesinin eşit haklara sahip şerefli bir üyesi olarak, Türkiye Cumhuriyetinin ebedi varlığı, refahı,\n' + 'maddi ve manelvi mutluluğu ile çağdaş medeniyet düzeyine ulaşma azmi yönünde;\n' +
import cudf import dask_cudf import dask import jpype import dask.distributed import netifaces as ni import random jpype.addClassPath( os.path.join(os.getenv("CONDA_PREFIX"), 'lib/blazingsql-algebra.jar')) jpype.addClassPath( os.path.join(os.getenv("CONDA_PREFIX"), 'lib/blazingsql-algebra-core.jar')) jvm_path = os.environ["CONDA_PREFIX"] + "/jre/lib/amd64/server/libjvm.so" jpype.startJVM('-ea', convertStrings=False, jvmpath=jvm_path) ArrayClass = jpype.JClass('java.util.ArrayList') ColumnTypeClass = jpype.JClass( 'com.blazingdb.calcite.catalog.domain.CatalogColumnDataType') dataType = ColumnTypeClass.fromString("GDF_INT8") ColumnClass = jpype.JClass( 'com.blazingdb.calcite.catalog.domain.CatalogColumnImpl') TableClass = jpype.JClass( 'com.blazingdb.calcite.catalog.domain.CatalogTableImpl') DatabaseClass = jpype.JClass( 'com.blazingdb.calcite.catalog.domain.CatalogDatabaseImpl') BlazingSchemaClass = jpype.JClass('com.blazingdb.calcite.schema.BlazingSchema') RelationalAlgebraGeneratorClass = jpype.JClass( 'com.blazingdb.calcite.application.RelationalAlgebraGenerator')
def add_dependency_to_vec(words_vec,sentences_data,idx_2_w): ''' 参数说明 words_vec:词向量数据,有如下属性:( words_vec.vocab :表示包含的所以词的词典,\ 如果 有个词 w 在words_vec.vocab中 ,可用 words_vec[w] 获得其词向量(100维)) sentences_data:文本数据包含8w条左右的数据,如下所示: [ [1,3,6,7,9,0,0], [5,6,7,9,1,3,0], .... .... .... ] 每句话由一个list表示,其中每一个数字表示词的编号 idx_2_w:编号转词的词典,如词w编号5,可以根据idx_2_w[5]得到词w ''' windowSize = 3 jpype.startJVM(jpype.getDefaultJVMPath(),"-Djava.class.path=/home/gpu2/zhaozd/hanlp1/hanlp-1.2.9.jar:/home/gpu2/zhaozd/hanlp1", "-Xms1g", "-Xmx1g") # gai!!! HanLP = jpype.JClass('com.hankcs.hanlp.HanLP') #windowSize = 4 #依存关系最多提取10个孩子 dep = [] depLabel=[] f0 = open('../vae/depLabel.txt','r') #生成依存标签-编号字典 gai!!! i0 = 0 for line in f0.readlines(): dep.append(line.strip('\n')) depLabel.append(i0) i0+=1 dictDep = {} dictDep=dict(zip(dep,depLabel)) print ('依存关系类别词典建立完毕') mapping=words_vec print ('词向量匹配中...') print ('提取依存序列') docIndex = [] #总 allWord=[] for count in range(len(sentences_data)) : if count % 1000 ==0: print (count) sentIndex = [] #句存储list 包含每个词及他们的孩子编号序列 sentWord = [] l = ' '.join([idx_2_w[int(x)] for x in sentences_data[count]]) if l.strip('\n') != '' : linewrite0 = HanLP.parseDependency(l) lineData = linewrite0.toString().split('\n') lineData.pop() for ll in lineData: #针对每个词提取依存孩子序列 if ll.strip() == '': continue wordIndex = [] #词存储lixt 每个孩子依次加入 ''' 该词词向量 ''' if ll.split('\t')[7] == '标点符号' : for count in range(100) : wordIndex.append(float(0)) #标点词向量设置为0 list ? # wordIndex.append(listVal) #标点词向量设置为0 list ? # wordSeq.append(listVal) #标点词向量设置为0 list ? elif ll.split('\t')[1] not in mapping.vocab: for count in range(100) : wordIndex.append(float(0)) #生僻或怪符号词向量设置为0 list ? else: for x in mapping[ll.split('\t')[1]]: wordIndex.append(x) #该词词向量 # wordIndex.append(mapping[ll.split('\t')[1]]) #该词词向量 ''' 依存结构:该词孩子index+依存类型+孩子词向量 ''' flag = 0 i = 0 for lll in lineData: wordSeq = [] if lll.split('\t')[6] == ll.split('\t')[0] and i< windowSize : flag = 1 if lll.split('\t')[7] not in dictDep.keys() : dictDep[lll.split('\t')[7]] = len(dictDep) wordIndex.append(int(lll.split('\t')[0])) #孩子编号 wordIndex.append(dictDep.get(lll.split('\t')[7])) #孩子与当前词的依存关系类别 # wordSeq.append(int(lll.split('\t')[0])) #孩子编号 # wordSeq.append(dictDep.get(lll.split('\t')[7])) #孩子与当前词的依存关系类别 if lll.split('\t')[7] == '标点符号' : for count in range(100) : wordIndex.append(float(0)) #标点词向量设置为0 list ? # wordIndex.append(listVal) #标点词向量设置为0 list ? # wordSeq.append(listVal) #标点词向量设置为0 list ? elif lll.split('\t')[1] not in mapping.vocab: for count in range(100) : wordIndex.append(float(0)) #生僻或怪符号词向量设置为0 list ? else: for x in mapping[lll.split('\t')[1]] : wordIndex.append(x) #该词词向量 # wordIndex.append(mapping[lll.split('\t')[1]]) #孩子词向量 # wordSeq.append(mapping[lll.split('\t')[1]]) #孩子词向量 # wordIndex.append(wordSeq) i+=1 for count in range(102*(windowSize-i)): wordIndex.append(float(0)) # if flag == 0 : #如果该词无孩子 则孩子序列则为0 # wordIndex.append(0) sentIndex.append(wordIndex) #注意!!依存句法结构提取出来第一词编号为1,而此处第一词编号 为 0 但index同 且提取出的孩子序号同原来编号 sentWord.append(ll.split('\t')[1]) docIndex.append(sentIndex) allWord.append(sentWord) return docIndex,allWord
self.index = i self.obj = obj DestructionTracker.init_calls += 1 tally[i] = 1 super().__init__() def __del__(self): tally[self.index] += 1 DestructionTracker.del_calls += 1 def callback(self, message): pass if __name__ == '__main__': jpype.startJVM(classpath=['test/classes', 'project/jpype_java/dist/*'], convertStrings=True) print() kB = (1024 / 8) MB = (1024**2 / 8) fixture = JClass("jpype.common.Fixture")() for i in range(trials): x = np.arange(int(10 * kB), dtype=np.int64) interface = jpype.JProxy( "java.io.Serializable", dict={'callback': DestructionTracker(i, x).callback}) interface_container = fixture.callObject(interface) if (i % 1000) == 0:
user = user.replace("\n", "") if impostazione == 'password': password = valore password = password.replace("\n", "") ##############################################FINE FILE INI IMPOSAZIONI################################################################### #CONNESSIONE A SYBASE IQ cnxn = pyodbc.connect("DSN=melc6h1_dmcomm") cursiq = cnxn.cursor() ########FINE SYBASE IQ #CONNESSIONE A DB2 jar = 'db2jcc4.jar' # location of the jdbc driver jar args = '-Djava.class.path=%s' % jar jvm = jpype.getDefaultJVMPath() jpype.startJVM(jvm, args) jdbc_string = "jdbc:db2://" + server + ":" + porta + "/" + dbname try: conn = jaydebeapi.connect("com.ibm.db2.jcc.DB2Driver", jdbc_string, [user, password]) #connessione al db2 except: app = gui("MIGRAZIONE CLIENTI POTENZIALI SYBASE IQ -> DB2", "600x300") app.setBg("yellow") app.setFont(18) app.addLabel( "title", "\nCLIENTI POTENZIALI SYBASE IQ -> DB2\n") #NOMELABEL, CONTENUTO app.setLabelBg("title", "blue") #NOMELABEL, COLORE SFONDO app.setLabelFg("title", "red") #NOME LABEL, COLORE CARATTERE app.addLabel("errore", "!!!ERRORE CONNESSIONE A DB!!!") #NOMELABEL, CONTENUTO
# !/usr/local/bin/python3.7 # -*- coding: utf-8 -*- # @Time : 2019/10/15 17:37 # @Author: [email protected] from jtyoui.neuralNetwork.paddle import ernie_st, ernie_match from jpype import startJVM, JClass, getDefaultJVMPath from config import Log, Models_DIR import os import jtyoui HanNLP_path = os.path.dirname(__file__) + os.sep + 'hanlp-1.7.4.jar' st = ernie_st(Models_DIR) sep = ':' if os.name != 'nt' else ';' # 开始初始化Java虚拟机 startJVM(getDefaultJVMPath(), F"-Djava.class.path={HanNLP_path}{sep}{os.path.dirname(__file__)}") HanNLP = JClass('com.hankcs.hanlp.HanLP') @jtyoui.log(Log) def extract_summary(word, num=3): """摘要提取 :param word:一段文字 :param num: 提取的数量 """ result = HanNLP.extractSummary(word, num).toString() return result[1:-1] @jtyoui.log(Log) def extract_keyword(word, num=3):
tokenizer = TweetTokenizer() from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer import bokeh.plotting as bp from bokeh.models import HoverTool, BoxSelectTool from bokeh.plotting import figure, show, output_notebook sg_flag = 0 tfidfflag = 1 # zemberek import jpype jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=zemberek_jar/zemberek-tum-2.0.jar", "-ea") # Türkiye Türkçesine göre çözümlemek için gerekli sınıfı hazırla Tr = jpype.JClass("net.zemberek.tr.yapi.TurkiyeTurkcesi") # tr nesnesini oluştur tr = Tr() # Zemberek sınıfını yükle Zemberek = jpype.JClass("net.zemberek.erisim.Zemberek") # zemberek nesnesini oluştur zemberek = Zemberek(tr) def ingest(): data = pd.read_csv("data/tweets_turktelekom_result.csv", header=0, delimiter="•", quoting=3,
# shutdownJVM() def startJVM(): # jvmPath = jpype.getDefaultJVMPath() jvmPath = u'D:\\Program Files\\Java\\jre1.8.0_152\\bin\server\\jvm.dll' jpype.startJVM(jvmPath) jpype.java.lang.System.out.println("hello world!") jpype.shutdownJVM() # startJVM() path = u'D:\\Program Files\\Java\\jre1.8.0_152\\bin\server\\jvm.dll' # jvm.dll启动成功 jpype.startJVM(path, "-Djava.class.path=D:\\jupyter\\hanlp-portable-1.6.8.jar") HanLP = JClass('com.hankcs.hanlp.HanLP') # 中文分词 print(HanLP.segment('你好,欢迎在Python中调用HanLP的API')) testCases = [ "商品和服务", "结婚的和尚未结婚的确实在干扰分词啊", "买水果然后来世博园最后去世博会", "中国的首都是北京", "欢迎新老师生前来就餐", "工信处女干事每月经过下属科室都要亲口交代24口交换机等技术性器件的安装工作", "随着页游兴起到现在的页游繁盛,依赖于存档进行逻辑判断的设计减少了,但这块也不能完全忽略掉。" ] for sentence in testCases: print(HanLP.segment(sentence)) # 命名实体识别与词性标注 NLPTokenizer = JClass('com.hankcs.hanlp.tokenizer.NLPTokenizer') print(NLPTokenizer.segment('中国科学院计算技术研究所的宗成庆教授正在教授自然语言处理课程'))
from database.database import database from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from snowballstemmer import stemmer import json import psycopg2 as psycopg2 from jpype import JClass, JString, getDefaultJVMPath, shutdownJVM, startJVM, java ZEMBEREK_PATH = r'C:\Users\casper\PycharmProjects\title_generate\zemberek-full.jar' startJVM(getDefaultJVMPath(), '-ea', f'-Djava.class.path={ZEMBEREK_PATH}', convertStrings=False) db = database() stopWords = set(stopwords.words('turkish')) lemmatizer = WordNetLemmatizer() stemmer = stemmer('turkish') class preprocessing: def __init__(self): self.preprocess() def preprocess(self): sql = """ UPDATE texts_tab SET pre_title = %s, pre_content = %s WHERE id = %s""" conn = None
def startJVM(): # jvmPath = jpype.getDefaultJVMPath() jvmPath = u'D:\\Program Files\\Java\\jre1.8.0_152\\bin\server\\jvm.dll' jpype.startJVM(jvmPath) jpype.java.lang.System.out.println("hello world!") jpype.shutdownJVM()
input("Enter human reply delay 投入人工打回复延期(秒钟): ")) #FIND WINDOW HANDLE try: regex = r".*(?= - 接待中心)" cW = QianNiuWindow() cW.find_window_regex(regex) cW.initialize() print(cW.userID, cW.msg_dlg, cW.input_dlg, cW.send_but) except: log_err("WINDOW HANDLE FIND") #START OCR & BOT projectDIR = os.getcwd() #set JAVA path defaultJVMpath = (r"C:\Program Files\Java\jdk-12.0.2\bin\server\jvm.dll") jarPath = "-Djava.class.path=" + os.path.join(projectDIR, r"sikuliX\sikulixapi.jar") SeekImagePath = os.path.join(projectDIR, r"sikuliX\newmsg.PNG") print("Starting JVM...") jpype.startJVM(defaultJVMpath, '-ea', jarPath, convertStrings=False) jpype.java.lang.System.out.println("Started JVM!") bot = Chatbot() bot.start() #MAIN PROGRAMME LOOP print("Starting program....") main(cW, bot, SeekImagePath, mode, delay_time)
#!/usr/bin/env python2.6 import jpype from jpype import java from jpype import javax HOST = '192.168.90.50' PORT = 9999 USER = '******' PASS = '******' URL = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi" % (HOST, PORT) #this it the path of your libjvm /usr/lib/jvm/sun-jdk-1.6/jre/lib/amd64/server/libjvm.so on linux jpype.startJVM( "/System/Library/Frameworks/JavaVM.framework/Libraries/libjvm_compat.dylib" ) java.lang.System.out.println("JVM load OK") jhash = java.util.HashMap() jarray = jpype.JArray(java.lang.String)([USER, PASS]) jhash.put(javax.management.remote.JMXConnector.CREDENTIALS, jarray) jmxurl = javax.management.remote.JMXServiceURL(URL) jmxsoc = javax.management.remote.JMXConnectorFactory.connect(jmxurl, jhash) connection = jmxsoc.getMBeanServerConnection() object = "java.lang:type=Threading" attribute = "ThreadCount" attr = connection.getAttribute(javax.management.ObjectName(object), attribute) print attribute, attr #Memory is a special case the answer is a Treemap in a CompositeDataSupport object = "java.lang:type=Memory"
import jpype jvmPath = jpype.getDefaultJVMPath() #the path of jvm.dll classpath = "/Users/moguoyi/pyStudy/httpApi/file" #the path of PasswordCipher.class jvmArg = "-Djava.class.path=" + classpath if not jpype.isJVMStarted(): #test whether the JVM is started jpype.startJVM(jvmPath,jvmArg) #start JVM javaClass = jpype.JClass("Yit.class") #create the Java class ncryptedString = javaClass.moAdd(1,3) print(ncryptedString) jpype.shutdownJVM() #shut down JVM
sys.path.append( '/Users/jennyhung/MathfreakData/School/OMSCS_ML/Assign2/abagail_py/ABAGAIL/ABAGAIL.jar' ) #print(sys.path) from array import * import jpype as jp import get_all_data import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from itertools import product #jp.startJVM(jp.getDefaultJVMPath(), "-ea") jp.startJVM( jp.getDefaultJVMPath(), '-ea', '-Djava.class.path=/Users/jennyhung/MathfreakData/School/OMSCS_ML/Assign2/abagail_py/ABAGAIL/ABAGAIL.jar' ) jp.java.lang.System.out.println("hello world") jp.java.func.nn.backprop.BackPropagationNetworkFactory jp.java.func.nn.backprop.RPROPUpdateRule jp.java.func.nn.backprop.BatchBackPropagationTrainer jp.java.shared.SumOfSquaresError jp.java.shared.DataSet jp.java.shared.Instance jp.java.opt.SimulatedAnnealing jp.java.opt.example.NeuralNetworkOptimizationProblem jp.java.opt.prob.GenericProbabilisticOptimizationProblem jp.java.opt.RandomizedHillClimbing jp.java.opt.prob.MIMIC jp.java.opt.example.CountOnesEvaluationFunction jp.java.func.nn.activation.RELU
def test_01(self): # 第二步:打开被测网站 driver = self.driver driver.get(self.base_url) # 第三步:执行测试动作 # 定义测试数据 email = "*****@*****.**" password = "******" name = "王朝12001" # 登录主账号 login_thinksns(driver, email, password, name) # 先定位到左侧应用列表,再点击 相册 driver.find_element_by_class_name( "user_app_list").find_element_by_link_text("相册").click() # 得到当前照片数量 我的全部照片(2) number = self.get_pictures_number(driver, "我的全部照片(", ")") # 点击 上传 driver.find_element_by_link_text("上传").click() sleep(1) # 定义jvm和sikuli jar包所在的路径 jvm_path = r"C:\Program Files\Java\jdk1.8.0_151\jre\bin\server\jvm.dll" jar_path = "-Djava.class.path=" + self.path + r"\libs\sikulixapi.jar" # 启动JVM jpype.startJVM(jvm_path, jar_path) # 找到能够进行屏幕操作的Screen类(相当于将Java版本的Screen类转换成Python的) Screen = jpype.JClass("org.sikuli.script.Screen") # 实例化该Screen类 screen = Screen() # 定义添加照片按钮图片所在的路径 add_path = self.path + r"\images\sikuli_imgs\add.png" # 根据实例化对象,点击该图片 screen.click(add_path) # 定义文件名输入框图片所在的路径 input_path = self.path + r"\images\sikuli_imgs\input.png" # 根据实例化对象,点击该图片 screen.click(input_path) # 定义两张需要上传的照片的路径 "c:\灯塔.jpg" "c:\八仙花.jpg" img1 = self.path + "\\images\\blog_imgs\\" + str(randint(0, 7)) + ".jpg" img2 = self.path + "\\images\\blog_imgs\\" + str(randint(0, 7)) + ".jpg" img_path = '"' + img1 + '" "' + img2 + '"' # 根据实例化对象,在输入框内输入上述路径 screen.type(input_path, img_path) # 定义打开按钮的图片所在的路径 open_path = self.path + r"\images\sikuli_imgs\open.png" # 根据实例化对象,点击该图片 screen.click(open_path) sleep(1) # 关闭JVM jpype.shutdownJVM() # 点击开始上传 driver.find_element_by_id("btnUpload").click() sleep(2) # 判断是否出现成功的提示,判断在其中即可: 照片上传成功! actual_tip = driver.find_element_by_name("save_upload_photos").text self.assertIn("照片上传成功!", actual_tip) # 点击完成上传 driver.find_element_by_class_name("btn_b").click() # 得到当前照片数量 共4张 actual_number = self.get_pictures_number(driver, "共", "张") # 判断照片数量的变化是否正确 self.assertEqual(number + 2, actual_number)
def __init__(self, filename, meta=True, java_memory='512m', read_mode='auto', series=0): global loci if read_mode not in ['auto', 'jpype', 'stringbuffer', 'javacasting']: raise ValueError('Invalid read_mode value.') # Make sure that file exists before starting java if not os.path.isfile(filename): raise IOError('The file "{}" does not exist.'.format(filename)) # Start java VM and initialize logger (globally) if not jpype.isJVMStarted(): loci_path = _find_jar() jpype.startJVM(jpype.getDefaultJVMPath(), '-ea', '-Djava.class.path=' + loci_path, '-Xmx' + java_memory) log4j = jpype.JPackage('org.apache.log4j') log4j.BasicConfigurator.configure() log4j_logger = log4j.Logger.getRootLogger() log4j_logger.setLevel(log4j.Level.ERROR) if not jpype.isThreadAttachedToJVM(): jpype.attachThreadToJVM() loci = jpype.JPackage('loci') # Initialize reader and metadata self.filename = str(filename) self.rdr = loci.formats.ChannelSeparator(loci.formats.ChannelFiller()) if meta: self._metadata = loci.formats.MetadataTools.createOMEXMLMetadata() self.rdr.setMetadataStore(self._metadata) self.rdr.setId(self.filename) if meta: self.metadata = MetadataRetrieve(self._metadata) # Checkout reader dtype and define read mode isLittleEndian = self.rdr.isLittleEndian() LE_prefix = ['>', '<'][isLittleEndian] FormatTools = loci.formats.FormatTools self._dtype_dict = { FormatTools.INT8: 'i1', FormatTools.UINT8: 'u1', FormatTools.INT16: LE_prefix + 'i2', FormatTools.UINT16: LE_prefix + 'u2', FormatTools.INT32: LE_prefix + 'i4', FormatTools.UINT32: LE_prefix + 'u4', FormatTools.FLOAT: LE_prefix + 'f4', FormatTools.DOUBLE: LE_prefix + 'f8' } self._dtype_dict_java = {} for loci_format in self._dtype_dict.keys(): self._dtype_dict_java[loci_format] = \ (FormatTools.getBytesPerPixel(loci_format), FormatTools.isFloatingPoint(loci_format), isLittleEndian) # Set the correct series and initialize the sizes self.size_series = self.rdr.getSeriesCount() if series >= self.size_series or series < 0: self.rdr.close() raise IndexError('Series index out of bounds.') self._series = series self._change_series() # Set read mode. When auto, tryout fast and check the image size. if read_mode == 'auto': Jarr = self.rdr.openBytes(0) if isinstance(Jarr[:], np.ndarray): read_mode = 'jpype' else: warn('Due to an issue with JPype 0.6.0, reading is slower. ' 'Please consider upgrading JPype to 0.6.1 or later.') try: im = self._jbytearr_stringbuffer(Jarr) im.reshape(self._sizeRGB, self._sizeX, self._sizeY) except (AttributeError, ValueError): read_mode = 'javacasting' else: read_mode = 'stringbuffer' self.read_mode = read_mode # Define the names of the standard per frame metadata. self.frame_metadata = {} if meta: if hasattr(self.metadata, 'PlaneDeltaT'): self.frame_metadata['t_s'] = 'PlaneDeltaT' if hasattr(self.metadata, 'PlanePositionX'): self.frame_metadata['x_um'] = 'PlanePositionX' if hasattr(self.metadata, 'PlanePositionY'): self.frame_metadata['y_um'] = 'PlanePositionY' if hasattr(self.metadata, 'PlanePositionZ'): self.frame_metadata['z_um'] = 'PlanePositionZ'
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. #if __name__ == "__main__": # print "Hello World" from WorkingWithFiles import ConvertingWorksheetToSVG import jpype import os.path asposeapispath = os.path.join(os.path.abspath("../../../"), "lib/") dataDir = os.path.join(os.path.abspath("./"), "data/") print "You need to put your Aspose.Cells for Java APIs .jars in this folder:\n" + asposeapispath #print dataDir jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % asposeapispath) hw = ConvertingWorksheetToSVG(dataDir) hw.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @time: 2021/1/31 10:36 @author: LQ @email: [email protected] @File: jvm_tool.py @Software: PyCharm """ import jpype import os base_dir = os.path.dirname(os.path.abspath(__file__)) jarpath = os.path.join(base_dir, "java-utils.jar") # 第二个参数是jar包的路径 jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % (jarpath)) # 启动jvm JDClass = jpype.JClass("com.demo.utils.PakoGzipUtils") jpython_obj = JDClass() # 创建类的实例,可以调用类里边的方法 if __name__ == '__main__': jpype.shutdownJVM() # 最后关闭jvm
ERRORCONNECTIONTITLE = U"Fehler beim Verbindungsaufbau" ConTypes = Enum("Eibnet", "sFT12") ConTypesText = Enum("Eibnet/IP", "RS232 FT1.2") COM = Enum("COM 1", "COM 2", "COM 3", "COM 4", "COM 5", "COM 6", "COM 7", "COM 8") #----------------------------------------------------------------------------------------------------------------------- #--------------------------------------------- Java Kram -------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- #Get path to directory with calimero-2.0a4.jar jarpath = os.path.join(os.path.abspath("."), "lib") #Start JVM jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % jarpath) KNXNetworkLinkIP = jpype.JClass("tuwien.auto.calimero.link.KNXNetworkLinkIP") TPSettings = jpype.JClass("tuwien.auto.calimero.link.medium.TPSettings") KNXnetIPTunnel = jpype.JClass("tuwien.auto.calimero.knxnetip.KNXnetIPTunnel") CEMILData = jpype.JClass("tuwien.auto.calimero.cemi.CEMILData") IndividualAddress = jpype.JClass("tuwien.auto.calimero.IndividualAddress") KNXAddress = jpype.JClass("tuwien.auto.calimero.KNXAddress") ManagementClientImpl = jpype.JClass("tuwien.auto.calimero.mgmt.ManagementClientImpl") #java internals KNXnetIPConnection = jpype.JClass("tuwien.auto.calimero.knxnetip.KNXnetIPConnection") InetSocketAddress = jpype.JClass("java.net.InetSocketAddress") #interfaces
def runStringToByteArray(data): print 'Running String conversion to byte array. size = ', len( data) / 1024.0, 'kb' start = time.time() arr_cls = jpype.JArray(jpype.JByte) java_arr = arr_cls(data) end = time.time() print ' test run in', (end - start), 'seconds.' root = os.path.abspath(os.path.dirname(__file__)) jpype.startJVM( jpype.getDefaultJVMPath(), "-ea", "-Xmx5M", "-verbose:gc", "-Djava.class.path=./classes%s%s%sclasses" % (os.pathsep, root, os.sep)) DELETED = False class MyStr(str): def __del__(self): global DELETED print 'string got deleted' DELETED = True def testStringMemory(): print 'with keeping the data' data = MyStr('5' * 1024)
import os import jpype jpype.startJVM(jpype.getDefaultJVMPath(),"-ea","-Djava.class.path=c:/Java") A = jpype.JClass("C") c = A() c.a() jpype.shutdownJVM()
str_NATS_CLIENT_HOME = "" if not (env_NATS_CLIENT_HOME is None): str_NATS_CLIENT_HOME = env_NATS_CLIENT_HOME + "/" classpath = str_NATS_CLIENT_HOME + "dist/nats-client.jar" classpath = classpath + ":" + str_NATS_CLIENT_HOME + "dist/nats-shared.jar" classpath = classpath + ":" + str_NATS_CLIENT_HOME + "dist/json.jar" classpath = classpath + ":" + str_NATS_CLIENT_HOME + "dist/rmiio-2.1.2.jar" classpath = classpath + ":" + str_NATS_CLIENT_HOME + "dist/commons-logging-1.2.jar" #b directory in which Center and Sector data are located data_dir = './data' #starts JVM jp.startJVM(jp.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % classpath) NATSClientFactory = jp.JClass('NATSClientFactory') natsClient = NATSClientFactory.getNATSClient() #Obtain the airport for the above aircraft environmentInterface = natsClient.getEnvironmentInterface() airportInterface = environmentInterface.getAirportInterface() natsClient.login("admin") # ============================================================================= # TaxiPlan Design Example starts here # # Step 1. Load TRX file and select an aircraft.
def init_jvm(jvmpath): if jpype.isJVMStarted(): return jpype.startJVM(classpath=[jvmpath])
# coding: utf-8 # In[3]: from jpype import JClass, JString, getDefaultJVMPath, shutdownJVM, startJVM # In[5]: startJVM( getDefaultJVMPath(), '-ea', '-Djava.class.path=zemberek-full.jar', convertStrings=False ) # In[6]: Paths: JClass = JClass('java.nio.file.Paths') # In[39]: trainPath = Paths.get("./enamex_train.txt") testPath = Paths.get("./enamex_test.txt")
def katechToWgs84(x, y): if(type(x) != type(0.0) or type(y) != type(0.0)): print "Parameters must be type of float" return -1 """ classpath = os.path.join(os.path.abspath('../'), 'bin') jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=%s" % classpath) """ # jarpath = os.path.join(os.path.abspath('.'), 'GeoTrans.jar') # jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % jarpath) # JVM Start if not jpype.isJVMStarted(): jarpath = ".:GeoTrans.jar" jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % (jarpath)) # Package Import GeoPkg = jpype.JPackage("GeoTrans") # Class Import GeoPoint = GeoPkg.GeoPoint GeoTrans = GeoPkg.GeoTrans # Point convert oKA = GeoPoint(x, y) oGeo = GeoTrans.convert(GeoTrans.KATEC, GeoTrans.GEO, oKA) return {"x":oGeo.getX(), "y":oGeo.getY()}