# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import xmlrpclib,sys
+import xmlrpc.client,sys
data="""
<methodCall>
</methodCall>
"""
def echo(args):
- print args
+ print(args)
return 96785439
f=open("input")
data=f.read()
f.close()
-params, method = xmlrpclib.loads(data)
+params, method = xmlrpc.client.loads(data)
try:
call=eval(method)
response = (response,)
except:
# report exception back to server
- response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2]))
+ response = xmlrpc.client.dumps( xmlrpc.client.Fault(1, "%s:%s" % sys.exc_info()[:2]))
else:
- response = xmlrpclib.dumps( response, methodresponse=1)
+ response = xmlrpc.client.dumps( response, methodresponse=1)
-print response
+print(response)
f=open("output",'w')
f.write(response)
f.close()
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2006-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
"""Doxygen XML to SWIG docstring converter.
-Usage:
-
- doxy2swig.py [options] input.xml output.i
-
Converts Doxygen generated XML files into a file containing docstrings
that can be used by SWIG-1.3.x. Note that you need to get SWIG
version > 1.3.23 or use Robin Dunn's docstring patch to be able to use
output will be written (the file will be clobbered).
"""
+
+__usage__ = "doxy2swig.py [options] input.xml output.i"
######################################################################
#
# This code is implemented using Mark Pilgrim's code as a guideline:
import sys
import types
import os.path
-import optparse
+import argparse
def my_open_read(source):
if hasattr(source, "read"):
return source
else:
- return open(source)
+ return open(source, encoding='utf8')
def my_open_write(dest):
if hasattr(dest, "write"):
return dest
else:
- return open(dest, 'w')
+ return open(dest, 'w', encoding='utf8')
class Doxy2SWIG:
def add_text(self, value):
"""Adds text corresponding to `value` into `self.pieces`."""
- if type(value) in (types.ListType, types.TupleType):
+ if type(value) in (list, tuple):
self.pieces.extend(value)
else:
self.pieces.append(value)
kind = node.attributes['kind'].value
if kind in ('class', 'struct'):
prot = node.attributes['prot'].value
- if prot <> 'public':
+ if prot != 'public':
return
names = ('compoundname', 'briefdescription',
'detaileddescription', 'includes')
first = self.get_specific_nodes(node, names)
for n in names:
- if first.has_key(n):
+ if n in first:
self.parse(first[n])
self.add_text(['";','\n'])
for n in node.childNodes:
- if n not in first.values():
+ if n not in list(first.values()):
self.parse(n)
elif kind in ('file', 'namespace'):
nodes = node.getElementsByTagName('sectiondef')
def do_parameterlist(self, node):
text='unknown'
- for key, val in node.attributes.items():
+ for key, val in list(node.attributes.items()):
if key == 'kind':
if val == 'param': text = 'Parameters'
elif val == 'exception': text = 'Exceptions'
if name[:8] == 'operator': # Don't handle operators yet.
return
- if not first.has_key('definition') or \
+ if 'definition' not in first or \
kind in ['variable', 'typedef']:
return
self.add_text(' %s::%s "\n%s'%(cname, name, defn))
for n in node.childNodes:
- if n not in first.values():
+ if n not in list(first.values()):
self.parse(n)
self.add_text(['";', '\n'])
if not os.path.exists(fname):
fname = os.path.join(self.my_dir, fname)
if not self.quiet:
- print "parsing file: %s"%fname
+ print("parsing file: %s"%fname)
p = Doxy2SWIG(fname, self.include_function_definition, self.quiet)
p.generate()
self.pieces.extend(self.clean_pieces(p.pieces))
p.write(output)
def main():
- usage = __doc__
- parser = optparse.OptionParser(usage)
- parser.add_option("-n", '--no-function-definition',
- action='store_true',
- default=False,
- dest='func_def',
- help='do not include doxygen function definitions')
- parser.add_option("-q", '--quiet',
- action='store_true',
- default=False,
- dest='quiet',
- help='be quiet and minimise output')
+ parser = argparse.ArgumentParser(description=__doc__, usage = __usage__)
+ parser.add_argument("-n", '--no-function-definition',
+ action='store_true',
+ default=False,
+ dest='func_def',
+ help='do not include doxygen function definitions')
+ parser.add_argument("-q", '--quiet',
+ action='store_true',
+ default=False,
+ dest='quiet',
+ help='be quiet and minimise output')
+ parser.add_argument('input')
+ parser.add_argument('ouput')
- options, args = parser.parse_args()
- if len(args) != 2:
- parser.error("error: no input and output specified")
+ args = parser.parse_args()
- convert(args[0], args[1], not options.func_def, options.quiet)
+ convert(args.input, args.output, not options.func_def, options.quiet)
if __name__ == '__main__':
description:
-- Import test_schema.xml
-- Select block node "bbb" => modify its parameters as:
- · Delete "node4" from first line
- · Create new line by "+" pressing
- · Add "nnode0"
+ · Delete "node4" from first line
+ · Create new line by "+" pressing
+ · Add "nnode0"
-- Press Apply button
Result: SIGSEGV
comments: OCC: DONE
description:
-- Import test_schema_last.xml
-- Select node "node1" => modify its parameters as:
- · Change name
- · Assign new valyes to X and Y
+ · Change name
+ · Assign new valyes to X and Y
-- Press Apply button
-- Select in 2D Viewer block node"Sb1", for which previous node belongs
Result: SIGSEGV
TODOlist, questions
-------------------
-Les noms de noeuds devraient avoir une portée relative au bloc qui les contient,
-et pouvoir être identifiés au sein d'une hiérarchie de bloc par un nom
-construit de la même façon que pour les ports:
+Les noms de noeuds devraient avoir une portée relative au bloc qui les contient,
+et pouvoir être identifiés au sein d'une hiérarchie de bloc par un nom
+construit de la même façon que pour les ports:
"bloc1.bloc2.noeud3"
-Dans quels cas faut-il créer des ports de données sur des noeuds composés ?
+Dans quels cas faut-il créer des ports de données sur des noeuds composés ?
(Switch, boucle...).
-La création est elle faite automatiquement au niveau de l'engine ?
+La création est elle faite automatiquement au niveau de l'engine ?
-Fonction de vérification de la compétude d'un graphe à l'édition:
-- tous les ports de donnée entrants doivent être initialisés ou connectés.
-- inventaire des ports de donnée entrants non initialisés et non connectés.
-- faut-il vérifier quelque chose pour les gates ?
+Fonction de vérification de la compétude d'un graphe à l'édition:
+- tous les ports de donnée entrants doivent être initialisés ou connectés.
+- inventaire des ports de donnée entrants non initialisés et non connectés.
+- faut-il vérifier quelque chose pour les gates ?
-Regles d'ecriture C++ à definir :
+Regles d'ecriture C++ à definir :
- pas de clause using namespace dans les .hxx
- prefixer les attributs de classe par _
- indentation style gnu
- utilisation des namespace dans les cxx
- - nom complets dans les declarations (identité avec .hxx pour doxygen)
+ - nom complets dans les declarations (identité avec .hxx pour doxygen)
IMPROVEMENTS :
- test foreach4.xml problemes sporadiques (CC) sur conversions de doubles
- ecriture graphe XML :
- - ajout attribut _isComponentMethod initialisé a true pour noeuds SALOME
+ - ajout attribut _isComponentMethod initialisé a true pour noeuds SALOME
est-ce utile ?
- <node>/<component> dans bschema, cschema, dschema...
- calcium*.xml
The Python protocol
++++++++++++++++++++++
-The Python protocol is based on serialisation done by the cPickle module (C implementation of the pickle module).
+The Python protocol is based on serialisation done by the pickle module.
All that is necessary is to define an object reference type with the Python protocol so that Python objects
can be exchanged between Python inline nodes and with SALOME components implemented in Python.
SALOME components implemented in Python that are required to support this exchange type must be designed
way as the example in the run method described below::
def run(self,s):
- o=cPickle.loads(s)
+ o=pickle.loads(s)
ret={'a':6, 'b':[1,2,3]}
- return cPickle.dumps(ret,-1)
+ return pickle.dumps(ret,-1)
The json protocol
++++++++++++++++++++++
The json protocol is based on `JSON <http://www.json.org/>`_ (JavaScript Object Notation)
-serialisation / deserialisation instead of cPickle. JSON supports fewer data types and requires that
+serialisation / deserialisation instead of pickle. JSON supports fewer data types and requires that
the simplejson Python module should be installed, but it has the advantage that it is more interoperable.
In particular, there are C++ libraries that serialise/deserialise the JSON.
const char *instanceName,
const char *interfaceName);
virtual ~HELLO();
- HELLO_ORB::status hello ( SALOMEDS::Study_ptr study, const char* name );
- HELLO_ORB::status goodbye( SALOMEDS::Study_ptr study, const char* name );
+ HELLO_ORB::status hello ( const char* name );
+ HELLO_ORB::status goodbye( const char* name );
void copyOrMove( const HELLO_ORB::object_list& what,
SALOMEDS::SObject_ptr where,
CORBA::Long row, CORBA::Boolean isCopy );
The definitions of the constructor and the HELLOEngine_factory instantiation function (both normalized!),
hello, goodbye and copyOrMove are given in the source file (HELLO.cxx)::
- HELLO_ORB::status HELLO::hello( SALOMEDS::Study_ptr study, const char* name )
+ HELLO_ORB::status HELLO::hello( const char* name )
{
...
}
- HELLO_ORB::status HELLO::goodbye( SALOMEDS::Study_ptr study, const char* name )
+ HELLO_ORB::status HELLO::goodbye( const char* name )
{
...
}
>>> print hello
<HELLO_ORB._objref_HELLO_Gen instance at 0x8274e94>
- >>> status=hello.hello(salome.myStudy, "Nicolas")
+ >>> status=hello.hello("Nicolas")
>>> print status
OP_OK
If a preliminary check is successfully done, schema run is created and then the user can start its execution in the chosen mode. Schema run
-is exported to an XML file and passed to YACS CORBA engine and executed there. YACS CORBA engine is also given a study ID.
+is exported to an XML file and passed to YACS CORBA engine and executed there.
For visual representation of execution state the following means are provided by YACS module.
C = compo.compo()
z = C.addvec(x, y)
-print 'x = ', x
-print 'y = ', y
-print 'z = ', z
-print C.prdscl(x,y)
+print('x = ', x)
+print('y = ', y)
+print('z = ', z)
+print(C.prdscl(x,y))
S = systeme.Systeme()
-print "create U1 ..."
+print("create U1 ...")
S.touch('U1')
-print "dir : ", S.dir()
+print("dir : ", S.dir())
-print "copy U1 to U2 ..."
+print("copy U1 to U2 ...")
S.cp('U1', 'U2')
-print "dir : ", S.dir()
+print("dir : ", S.dir())
-print "delete U1 ..."
+print("delete U1 ...")
S.rm('U1')
-print "dir : ", S.dir()
+print("dir : ", S.dir())
-print "delete U2 ..."
+print("delete U2 ...")
S.rm('U2')
-print "dir : ", S.dir()
+print("dir : ", S.dir())
v2 = [ 3, 4, 5 ]
v3 = o.addvec(v1, v2)
-print v3
+print(v3)
-print o.prdscl(v1, v3)
+print(o.prdscl(v1, v3))
StudyIn node
...................
-A StudyIn node has output data ports only. It is used to define data in the calculation scheme originating from a SALOME study. The associated study is given by its SALOME StudyID.
+A StudyIn node has output data ports only. It is used to define data in the calculation scheme originating from a SALOME study.
A port corresponds to data stored in the associated study. The data has a name (the port name), a type (the port type), and a reference that gives the entry into the study. This reference is either a SALOME Entry (for example 0:1:1:2) or a path in the SALOME study tree (for example, /Geometry/box_1).
StudyOut node
...................
-A StudyOut node only has input data ports. It is used to store results in a SALOME study. The associated study is given by its SALOME StudyID.
+A StudyOut node only has input data ports. It is used to store results in a SALOME study.
A port corresponds to a result to be stored in an associated study. The result has a name (the port name), a type (the port type), and a reference that gives the entry into the study. This reference is either a SALOME Entry (for example 0:1:1:2) or a path in the SALOME study tree (for example, /Geometry/box_1).
value of 1 and a default case, then the absolute name of node “n” in the case 1 will be “c.b.p1_n” and the absolute name of the node in
the default case will be “c.b.default_n”.
-Active study
---------------
-A schema can be executed without using the SALOME study manager. But when a schema must be executed in the context
-of a SALOME study, it is possible to specify the studyId to use.
-
-The way to do that is to set the schema property **DefaultStudyID** to the study id.
-
-In the GUI, this is set automatically to the current active studyId.
-For execution in console mode, see :ref:`xml_active_study`
-
.. _errorreport:
Error report
StudyIn node
++++++++++++++
A StudyIn node is defined using the runtime createInDataNode method. It uses two arguments, the first of which must be “study”
-and the second the node name. The associated study is specified by adding the “StudyID” property to the node using
-its setProperty method. Node data are defined by adding output data ports using the edAddOutputPOrt method, transferring
+and the second the node name. Node data are defined by adding output data ports using the edAddOutputPOrt method, transferring
the name of the data and its type as arguments. The data is initialised with the reference in the study, using the setData method
for the port thus created, transferring a character string to it containing either the SALOME Entry or the path in the study
tree structure.
The following is an example of the StudyIn node that defines 2 GEOM_Object type data (a and b). The study is assumed to be
-loaded into memory by SALOME as StudyID 1. Data a is referenced by one SALOME Entry. Data b is referenced by a path in the
+loaded into memory by SALOME. Data a is referenced by one SALOME Entry. Data b is referenced by a path in the
study tree structure::
n=r.createInDataNode("study","study1")
p.edAddChild(n)
- n.setProperty("StudyID","1")
pout=n.edAddOutputPort('a',tgeom)
pout.setData("0:1:1:1")
pout=n.edAddOutputPort('b',tgeom)
StudyOut node
++++++++++++++
A StudyOut node is defined using the runtime createOutDataNode method. It uses two arguments, the first of
-which must be “study” and the second the node name. The associated study is specified by adding
-the “StudyID” property to the node using its setProperty method. The name of the file in which the study will be
+which must be “study” and the second the node name. The name of the file in which the study will be
saved is specified using the node SetRef method with the file name as an argument.
The node results are defined by adding input data ports to it using the edAddInputPort method, transferring the data name
and type as arguments. The setData method for the port is used to associate the entry into the study to the result, transferring
a character string to it that contains either the SALOME Entry or the path in the study tree structure.
The following contains an example of the StudyOut node that defines two GEOM_Object type results (a and b).
-The studyId of the study used is 1. Result a is referenced by a SALOME Entry. The result b is referenced by a path.
+Result a is referenced by a SALOME Entry. The result b is referenced by a path.
The complete study is saved in the study1.hdf file at the end of the calculation::
n=r.createOutDataNode("study","study2")
n.setRef("study1.hdf")
p.edAddChild(n)
- n.setProperty("StudyID","1")
pout=n.edAddInputPort('a',tgeom)
pout.setData("0:1:2:1")
pout=n.edAddInputPort('b',tgeom)
.. _xml_active_study:
-Active study
---------------
-To execute a schema in the context of a SALOME study, you have to set the **DefaultStudyID** property of the schema.
-
-Example to execute the schema in the study with studyId 5:
-
-.. code-block:: xml
-
- <proc name="myschema">
- <property name="DefaultStudyID" value="5"/>
- ...
- </proc>
-
-
Datastream connections
----------------------------
Datastream connections are only possible for SALOME service nodes, as we have seen in :ref:`principes`. Firstly, datastream ports
StudyIn node
'''''''''''''''
This type of node is defined as a DataIn node with the datanode tag. All that is necessary is to add the kind attribute
-with the “study” value. The associated study is given by a property (property tag) named StudyID (the value of which is an integer).
+with the “study” value.
The parameter sub-tag will be used to define the node data. This tag has two compulsory attributes, name and type, that give the
data name and type respectively. The ref attribute gives the input into the study in the form of a SALOME Entry, or a
path in the study tree structure.
The following is an example of a StudyIn node that defines 2 data (b and c) with types GEOM_Object and Boolean. It is assumed
-that SALOME has loaded the study (with StudyID 1) into memory. Data b is referenced by a SALOME Entry.
+that SALOME has loaded the study into memory. Data b is referenced by a SALOME Entry.
The data c is referenced by a path in the study tree structure.
.. code-block:: xml
<datanode name="s" kind="study" >
- <property name="StudyID" value="1" />
<parameter name="b" type="GEOM/GEOM_Object" ref="0:1:2:2"/>
<parameter name="c" type="bool" ref="/Geometry/Box_1"/>
</datanode>
''''''''''''''''''
This type of node is defined as a DataOut node with the outnode tag and the name attribute.
All that is necessary is to add the kind attribute with the value “study”.
-The optional ref attribute gives the name of the file in which the study will be saved at the end of the calculation.
-The associated study is given by a property (property tag) with name StudyID (the value of which is an integer).
+The optional ref attribute gives the name of the file in which the study will be saved at the end of the calculation.
The parameter sub-tag will be used to define the node results. This tag has two compulsory attributes, name and type, that
give the data name and type respectively. The ref attribute gives the entry into the study in the form of a SALOME Entry, or
a path in the study tree structure.
-The following gives an example of the StudyOut node that defines 2 results (a and b) of the GEOM_Object type. The study used has
-the studyId 1. The complete study is saved in the study1.hdf file at the end of the calculation:
+The following gives an example of the StudyOut node that defines 2 results (a and b) of the GEOM_Object type.
+The complete study is saved in the study1.hdf file at the end of the calculation:
.. code-block:: xml
<outnode name="o" kind="study" ref="stud1.hdf">
- <property name="StudyID" value="1"/>
<parameter name="a" type="GEOM/GEOM_Object" ref="/Geometry/YacsFuse"/>
<parameter name="b" type="GEOM/GEOM_Object" ref="0:1:1:6"/>
</outnode>
compodefs=r"""
class A:
- def createObject( self, study, name ):
+ def createObject( self, name ):
"Create object. "
- builder = study.NewBuilder()
- father = study.FindComponent( "pycompos" )
+ builder = salome.myStudy.NewBuilder()
+ father = salome.myStudy.FindComponent( "pycompos" )
if father is None:
father = builder.NewComponent( "pycompos" )
attr = builder.FindOrCreateAttribute( father, "AttributeName" )
Here is an excerpt from cppgui1 example that shows how to redefine the DumpPython method in a C++ component::
compomethods=r"""
- Engines::TMPFile* DumpPython(CORBA::Object_ptr theStudy, CORBA::Boolean isPublished,
+ Engines::TMPFile* DumpPython(CORBA::Boolean isPublished,
CORBA::Boolean& isValidScript)
{
- SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
- if(CORBA::is_nil(aStudy))
- return new Engines::TMPFile(0);
- SALOMEDS::SObject_var aSO = aStudy->FindComponent("cppcompos");
+ SALOMEDS::SObject_var aSO = KERNEL::getStudy()->FindComponent("cppcompos");
if(CORBA::is_nil(aSO))
return new Engines::TMPFile(0);
std::string Script = "import cppcompos_ORB\n";
Script += "import salome\n";
Script += "compo = salome.lcc.FindOrLoadComponent('FactoryServer','cppcompos')\n";
- Script += "def RebuildData(theStudy):\n";
- Script += " compo.SetCurrentStudy(theStudy)\n";
const char* aScript=Script.c_str();
char* aBuffer = new char[strlen(aScript)+1];
strcpy(aBuffer, aScript);
SALOME_DriverPy.SALOME_DriverPy_i.__init__(self,"pycompos")
return
- def createObject( self, study, name ):
+ def createObject( self, name ):
"Create object. "
- builder = study.NewBuilder()
- father = study.FindComponent( "pycompos" )
+ builder = salome.myStudy.NewBuilder()
+ father = salome.myStudy.FindComponent( "pycompos" )
if father is None:
father = builder.NewComponent( "pycompos" )
attr = builder.FindOrCreateAttribute( father, "AttributeName" )
interface Idl_A : SALOMEDS::Driver
{
- void createObject(in SALOMEDS::Study theStudy, in string name) raises (SALOME::SALOME_Exception);
+ void createObject(in string name) raises (SALOME::SALOME_Exception);
};
In this simple case, it is also possible to include directly the content of the file with the *interfacedefs* parameter.
import sys, os, string, py_compile
files = '''$*'''
-print 'Byte-compiling python modules...'
+print('Byte-compiling python modules...')
for file in string.split(files):
$trans
if not os.path.exists(path) or not (len(path) >= 3 and path[-3:] == '.py'):
continue
- print file,
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(path)
print" || exit $?
import sys, os, string, py_compile
files = '''$*'''
-print 'Byte-compiling python modules (optimised versions) ...'
+print('Byte-compiling python modules (optimised versions) ...')
for file in string.split(files):
$trans
if not os.path.exists(path) or not (len(path) >= 3 and path[-3:] == '.py'):
continue
- print file,
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(path)
print" 2>/dev/null || :
#define ROSENBROCK
-/* constante dépendant du choix de l'évaluateur */
+/* constante dépendant du choix de l'évaluateur */
-// nombre de paramètre
+// nombre de paramètre
#ifdef GRIEWANK
#define NBGENE 30
#else
INCLUDE_DIRECTORIES(
${PTHREAD_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIRS}
${PROJECT_BINARY_DIR}/idl
${PROJECT_BINARY_DIR}
#ifdef OMNIORB
#include <omniORB4/CORBA.h>
-//--- from omniORBpy.h (not present on Debian Sarge packages)
-struct omniORBPYAPI
-{
- PyObject* (*cxxObjRefToPyObjRef)(const CORBA::Object_ptr cxx_obj,
- CORBA::Boolean hold_lock);
- // Convert a C++ object reference to a Python object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- CORBA::Object_ptr (*pyObjRefToCxxObjRef)(PyObject* py_obj,
- CORBA::Boolean hold_lock);
- // Convert a Python object reference to a C++ object reference.
- // Raises BAD_PARAM if the Python object is not an object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- PyObject* (*handleCxxSystemException)(const CORBA::SystemException& ex);
- // Sets the Python exception state to reflect the given C++ system
- // exception. Always returns NULL. The caller must hold the Python
- // interpreter lock.
-};
-
-omniORBPYAPI* api;
+#include <omniORBpy.h>
+omniORBpyAPI* api=0;
#define OMNIPY_CATCH_AND_HANDLE_SYSTEM_EXCEPTIONS \
catch (const CORBA::SystemException& ex) { \
$result = PyList_New($1.size());
for (i=0, iL=$1.begin(); iL!=$1.end(); i++, iL++)
- PyList_SetItem($result,i,PyString_FromString((*iL).c_str()));
+ PyList_SetItem($result,i,PyUnicode_FromString((*iL).c_str()));
}
%typemap(in) std::list<std::string>
for (i = 0; i < size; i++)
{
PyObject *o = PyList_GetItem($input,i);
- if (PyString_Check(o))
- $1.push_back(std::string(PyString_AsString(PyList_GetItem($input,i))));
+ if (PyUnicode_Check(o))
+ $1.push_back(std::string(PyUnicode_AsUTF8(PyList_GetItem($input,i))));
else
{
PyErr_SetString(PyExc_TypeError,"list must contain strings");
void *ptr;
if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0) == 0)
$1 = 1;
- else if (PyInt_Check($input))
+ else if (PyLong_Check($input))
$1 = 1;
else if(PyFloat_Check($input))
$1 = 1;
- else if (PyString_Check($input))
+ else if (PyUnicode_Check($input))
+ $1 = 1;
+ else if (PyBytes_Check($input))
$1 = 1;
else
$1 = 0;
// It is an Any : it is converted by SWIG_ConvertPtr $input -> $1
is_new_object=0;
}
- else if (PyInt_Check($input))
+ else if (PyLong_Check($input))
{
// It is an Int
- $1=YACS::ENGINE::AtomAny::New((int)PyInt_AsLong($input));
+ $1=YACS::ENGINE::AtomAny::New((int)PyLong_AsLong($input));
is_new_object=1;
}
else if(PyFloat_Check($input))
$1=YACS::ENGINE::AtomAny::New(PyFloat_AsDouble($input));
is_new_object=1;
}
- else if(PyString_Check($input))
+ else if(PyUnicode_Check($input))
{
- // It is a Float
- $1=YACS::ENGINE::AtomAny::New(PyString_AsString($input));
+ // It is a Unicode
+ $1=YACS::ENGINE::AtomAny::New(PyUnicode_AsUTF8($input));
+ is_new_object=1;
+ }
+ else if(PyBytes_Check($input))
+ {
+ // It is a Bytes
+ $1=YACS::ENGINE::AtomAny::New(PyBytes_AsString($input));
is_new_object=1;
}
else
else if (PyInt_Check($1))
{
// It is an Int
- $result=YACS::ENGINE::AtomAny::New((int)PyInt_AsLong($1));
+ $result=YACS::ENGINE::AtomAny::New((int)PyLong_AsLong($1));
}
else if(PyFloat_Check($1))
{
// It is a Float
$result=YACS::ENGINE::AtomAny::New(PyFloat_AsDouble($1));
}
- else if(PyString_Check($1))
+ else if(PyUnicode_Check($1))
{
- // It is a String
- $result=YACS::ENGINE::AtomAny::New(PyString_AsString($1));
+ // It is a Unicode
+ $result=YACS::ENGINE::AtomAny::New(PyUnicode_AsUTF8($1));
+ }
+ else if(PyBytes_Check($1))
+ {
+ // It is a Bytes
+ $result=YACS::ENGINE::AtomAny::New(PyBytes_AsString($1));
}
else
{
To overload standard SWIG wrapping we define a full specialization of std::map
with %extend for 4 basic methods : getitem, setitem, delitem and keys.
Then we complete the interface by deriving the shadow wrapper from
- the python mixin class (UserDict.DictMixin).
+ the python mixin class (UserDict.DictMixin / collections.MutableMapping with Python 3).
Do not forget to declare the new shadow class to SWIG with tname_swigregister(tname).
Objects returned by __getitem__ are declared new (%newobject) so that when destroyed they
call decrRef (see feature("unref") for RefCounter).
*/
+/*
+%inline %{
+template <typename U> class StopIterator {};
+template <typename U> class Iterator {
+ public:
+ Iterator(std::map<std::string,U*>::iterator _cur, std::map<std::string,U*>::iterator _end) : cur(_cur), end(_end) {}
+ Iterator* __iter__()
+ {
+ return this;
+ }
+ template <typename U> std::map<std::string,U*>::iterator cur;
+ template <typename U> std::map<std::string,U*>::iterator end;
+ };
+%}
+
+%include "exception.i"
+%exception Iterator::next {
+ try
+ {
+ $action // calls %extend function next() below
+ }
+ catch (StopIterator)
+ {
+ PyErr_SetString(PyExc_StopIteration, "End of iterator");
+ return NULL;
+ }
+}
+
+%extend Iterator
+{
+ std::map<std::string,U*>& next()
+ {
+ if ($self->cur != $self->end)
+ {
+ // dereference the iterator and return reference to the object,
+ // after that it increments the iterator
+ return *$self->cur++;
+ }
+ throw StopIterator();
+ }
+}
+*/
template<>
class std::map<std::string,T*>
{
PyObject* keyList = PyList_New(pysize);
std::map<std::string, T* >::const_iterator i = self->begin();
for (int j = 0; j < pysize; ++i, ++j) {
- PyList_SET_ITEM(keyList, j, PyString_FromString(i->first.c_str()));
+ PyList_SET_ITEM(keyList, j, PyUnicode_FromString(i->first.c_str()));
}
return keyList;
}
+/* Iterator __iter__()
+ {
+ // return a constructed Iterator object
+ return Iterator($self->begin(), $self->end());
+ }
+*/
+ int __len__()
+ {
+ int pysize = self->size();
+ return pysize;
+ }
}
};
%template() std::pair<std::string, T* >;
%template(tname) std::map<std::string, T* >;
%pythoncode{
-from UserDict import DictMixin
-class tname(tname,DictMixin):pass
+from collections import MutableMapping
+class tname(tname,MutableMapping):pass
tname##_swigregister(tname)
}
%enddef
if (!omnipy)
{
PyErr_SetString(PyExc_ImportError,(char*)"Cannot import _omnipy");
- return;
+ return NULL;
}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
- api = (omniORBPYAPI*)PyCObject_AsVoidPtr(pyapi);
+ api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
#endif
%}
%include <Port.hxx>
%extend YACS::ENGINE::Port
{
- int __cmp__(Port* other)
+ /* __cmp__ does not exist in Python 3 */
+ int __lt__(Port* other)
{
if(self==other)
return 0;
else
return 1;
}
+ int __gt__(Port* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+ int __ne__(Port* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+ int __eq__(Port* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+ int __le__(Port* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+ int __ge__(Port* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+
long ptr()
{
return (long)self;
%include <Node.hxx>
%extend YACS::ENGINE::Node
{
- int __cmp__(Node* other)
+ /* __cmp__ does not exist in Python 3 */
+ int __lt__(Node* other)
{
if(self==other)
return 0;
else
return 1;
}
+ int __gt__(Node* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+ int __ne__(Node* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+ int __eq__(Node* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+ int __le__(Node* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+ int __ge__(Node* other)
+ {
+ if(self==other)
+ return 0;
+ else
+ return 1;
+ }
+
long ptr()
{
return (long)self;
// param 0
PyObject *ret0Py(PyList_New(ret0.size()));
for(std::size_t i=0;i<ret0.size();i++)
- PyList_SetItem(ret0Py,i,PyInt_FromLong(ret0[i]));
+ PyList_SetItem(ret0Py,i,PyLong_FromLong(ret0[i]));
PyTuple_SetItem(ret,0,ret0Py);
// param 1
PyObject *ret1Py(PyList_New(ret1.size()));
// param 2
PyObject *ret2Py(PyList_New(ret2.size()));
for(std::size_t i=0;i<ret2.size();i++)
- PyList_SetItem(ret2Py,i,PyString_FromString(ret2[i].c_str()));
+ PyList_SetItem(ret2Py,i,PyBytes_FromString(ret2[i].c_str()));
PyTuple_SetItem(ret,2,ret2Py);
return ret;
}
if (!omnipy)
{
PyErr_SetString(PyExc_ImportError,(char*)"Cannot import _omnipy");
- return;
+ return NULL;
}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
- api = (omniORBPYAPI*)PyCObject_AsVoidPtr(pyapi);
+ api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
#endif
%}
# additional include directories
INCLUDE_DIRECTORIES(
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIR}
${PROJECT_SOURCE_DIR}/src/bases
${PROJECT_SOURCE_DIR}/src/engine
throw YACS::Exception("YACSEvalInputPort::getDefaultValueDefined : internal error !");
if(PyFloat_Check(data))
return new YACSEvalAnyDouble(PyFloat_AsDouble(data));
- if(PyInt_Check(data))
- return new YACSEvalAnyInt((int)PyInt_AsLong(data));
+ if(PyLong_Check(data))
+ return new YACSEvalAnyInt((int)PyLong_AsLong(data));
throw YACS::Exception("YACSEvalInputPort::getDefaultValueDefined : unmanaged types different from int and double for py !");
}
YACS::ENGINE::AnyInputPort *i1(dynamic_cast<YACS::ENGINE::AnyInputPort *>(_ptr));
}
else if(par1)
{
- PyObject *obj(PyInt_FromLong(par1->toInt()));
+ PyObject *obj(PyLong_FromLong(par1->toInt()));
i0->put(obj);
Py_XDECREF(obj);
}
-// Copyright (C) 2012-2016 CEA/DEN, EDF R&D
+ // Copyright (C) 2012-2016 CEA/DEN, EDF R&D
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
PyObject *ob(PyList_New(sz));
for(std::size_t i=0;i<sz;i++)
{
- PyList_SetItem(ob,i,PyInt_FromLong((*_arr)[i]));
+ PyList_SetItem(ob,i,PyLong_FromLong((*_arr)[i]));
}
p->put(ob);
p->exSaveInit();
_salomeInstance=PyObject_Call(startMeth,myArgs,myKWArgs);//new
YACS::ENGINE::AutoPyRef getPortMeth(PyObject_GetAttrString(_salomeInstance,const_cast<char *>("get_port")));//new
YACS::ENGINE::AutoPyRef portPy(PyObject_CallObject(getPortMeth,0));//new
- _port=PyInt_AsLong(portPy);
+ _port=PyLong_AsLong(portPy);
//
int dummy;
_corbaConfigFileName=GetConfigAndPort(dummy);
PyObject *kernelRootDir(0);// os.environ["KERNEL_ROOT_DIR"]
{
YACS::ENGINE::AutoPyRef environPy(PyObject_GetAttrString(osPy,const_cast<char *>("environ")));//new
- YACS::ENGINE::AutoPyRef kernelRootDirStr(PyString_FromString(const_cast<char *>(KERNEL_ROOT_DIR)));//new
+ YACS::ENGINE::AutoPyRef kernelRootDirStr(PyBytes_FromString(const_cast<char *>(KERNEL_ROOT_DIR)));//new
kernelRootDir=PyObject_GetItem(environPy,kernelRootDirStr);//new
}
{
YACS::ENGINE::AutoPyRef joinPy(PyObject_GetAttrString(pathPy,const_cast<char *>("join")));//new
YACS::ENGINE::AutoPyRef myArgs(PyTuple_New(4));
Py_XINCREF(kernelRootDir); PyTuple_SetItem(myArgs,0,kernelRootDir);
- PyTuple_SetItem(myArgs,1,PyString_FromString(const_cast<char *>("bin")));
- PyTuple_SetItem(myArgs,2,PyString_FromString(const_cast<char *>("salome")));
- PyTuple_SetItem(myArgs,3,PyString_FromString(const_cast<char *>("appliskel")));
+ PyTuple_SetItem(myArgs,1,PyBytes_FromString(const_cast<char *>("bin")));
+ PyTuple_SetItem(myArgs,2,PyBytes_FromString(const_cast<char *>("salome")));
+ PyTuple_SetItem(myArgs,3,PyBytes_FromString(const_cast<char *>("appliskel")));
YACS::ENGINE::AutoPyRef res(PyObject_CallObject(joinPy,myArgs));
- ret=PyString_AsString(res);
+ ret=PyBytes_AsString(res);
}
Py_XDECREF(kernelRootDir);
return ret;
YACS::ENGINE::AutoPyRef osPy(PyImport_ImportModule(const_cast<char *>("os")));//new
YACS::ENGINE::AutoPyRef environPy(PyObject_GetAttrString(osPy,const_cast<char *>("environ")));//new
//
- YACS::ENGINE::AutoPyRef corbaConfigStr(PyString_FromString(const_cast<char *>(CORBA_CONFIG_ENV_VAR_NAME)));//new
+ YACS::ENGINE::AutoPyRef corbaConfigStr(PyBytes_FromString(const_cast<char *>(CORBA_CONFIG_ENV_VAR_NAME)));//new
YACS::ENGINE::AutoPyRef corbaConfigFileNamePy(PyObject_GetItem(environPy,corbaConfigStr));//new
- std::string ret(PyString_AsString(corbaConfigFileNamePy));
+ std::string ret(PyBytes_AsString(corbaConfigFileNamePy));
//
- YACS::ENGINE::AutoPyRef nsPortStr(PyString_FromString(const_cast<char *>(NSPORT_VAR_NAME)));//new
+ YACS::ENGINE::AutoPyRef nsPortStr(PyBytes_FromString(const_cast<char *>(NSPORT_VAR_NAME)));//new
YACS::ENGINE::AutoPyRef nsPortValuePy(PyObject_GetItem(environPy,nsPortStr));//new
- std::string portStr(PyString_AsString(nsPortValuePy));
+ std::string portStr(PyBytes_AsString(nsPortValuePy));
std::istringstream iss(portStr);
iss >> port;
return ret;
const char fetchPyCmd[]="import salome,CORBA\nsalome.salome_init()\nsl=salome.naming_service.Resolve(\"/SalomeLauncher\")\nif not CORBA.is_nil(sl):\n return salome.orb.object_to_string(sl)\nelse:\n raise Exception(\"Impossible to locate salome launcher !\")";
YACS::ENGINE::AutoPyRef func(YACS::ENGINE::evalPy(methName,fetchPyCmd));
YACS::ENGINE::AutoPyRef val(YACS::ENGINE::evalFuncPyWithNoParams(func));
- std::string ior(PyString_AsString(val));
+ std::string ior(PyBytes_AsString(val));
CORBA::Object_var obj(string_to_object(ior));
if(CORBA::is_nil(obj))
throw YACS::Exception("goFetchingSalomeLauncherInNS : fetched ior is NIL !");
for(std::size_t i=0;i<sz;i++)
{
PyObject *elt(PyList_GetItem(obj,i));
- eltCpp[i]=PyInt_AsLong(elt);
+ eltCpp[i]=PyLong_AsLong(elt);
}
YACS::AutoCppPtr<YACSEvalSeqAnyInt> elt(new YACSEvalSeqAnyInt(eltCpp));
return elt.dettach();
//
YACS::ENGINE::AutoPyRef func(YACS::ENGINE::evalPy(EFXGenFileName,EFXGenContent));
YACS::ENGINE::AutoPyRef val(YACS::ENGINE::evalFuncPyWithNoParams(func));
- _locSchemaFile=PyString_AsString(val);
+ _locSchemaFile=PyBytes_AsString(val);
func=YACS::ENGINE::evalPy(EFXGenFileName,EFXGenContent2);
val=YACS::ENGINE::evalFuncPyWithNoParams(func);
- _jobName=PyString_AsString(val);
+ _jobName=PyBytes_AsString(val);
//
static const char LISTPYOBJ_STR[]="list[pyobj]";
if(getBoss()->getOutputsOfInterest().empty())
${PROJECT_SOURCE_DIR}/src/yacsloader_swig
${PROJECT_SOURCE_DIR}/src/evalyfx
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIRS}
)
PyObject *o=PyList_GetItem(pyLi,i);
if(PyInt_Check(o))
{
- int val=(int)PyInt_AS_LONG(o);
+ int val=(int)PyLong_AS_LONG(o);
arr[i]=val;
}
else
for(int i=0;i<size;i++)
{
PyObject *o=PyTuple_GetItem(pyLi,i);
- if(PyInt_Check(o))
+ if(PyLong_Check(o))
{
- int val=(int)PyInt_AS_LONG(o);
+ int val=(int)PyLong_AS_LONG(o);
arr[i]=val;
}
else
std::size_t sz(arr.size());
PyObject *ret(PyList_New(sz));
for(std::size_t i=0;i<sz;i++)
- PyList_SetItem(ret,i,PyInt_FromLong(arr[i]));
+ PyList_SetItem(ret,i,PyLong_FromLong(arr[i]));
return ret;
}
std::size_t sz2(zeArr->size());
PyObject *ret2(PyList_New(sz2));
for(std::size_t i2=0;i2<sz2;i2++)
- PyList_SetItem(ret2,i2,PyInt_FromLong((*zeArr)[i2]));
+ PyList_SetItem(ret2,i2,PyLong_FromLong((*zeArr)[i2]));
PyList_SetItem(ret,i,ret2);
}
else
}
else if(PyInt_Check(parameter))
{
- YACSEvalAnyInt tmp((int)PyInt_AsLong(parameter));
+ YACSEvalAnyInt tmp((int)PyLong_AsLong(parameter));
self->setDefaultValue(&tmp);
}
else
PyObject *ret0Py(ret0?Py_True:Py_False);
Py_XINCREF(ret0Py);
PyTuple_SetItem(ret,0,ret0Py);
- PyTuple_SetItem(ret,1,PyInt_FromLong(ret1));
+ PyTuple_SetItem(ret,1,PyLong_FromLong(ret1));
return ret;
}
}
cp.setWCKey("P11U50:CARBONES") ; cp.setNbProcs(5) ; cp.setMaxDuration("00:05")
assert(not rss.isInteractive())
a,b=efx.run(session)
-print("************",a,b)
-print efx.getResults()
+print(("************",a,b))
+print(efx.getResults())
INCLUDE_DIRECTORIES(
${PYTHON_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${LIBXML2_INCLUDE_DIR}
${GRAPHVIZ_INCLUDE_DIRS}
${QT_INCLUDES}
void FormContainerDecorator::connectForTyp()
{
connect(_typ->cb_resource,SIGNAL(mousePressed()),this,SLOT(onResMousePressed()));
- connect(_typ->cb_resource,SIGNAL(activated(int)),this,SLOT(onResActivated));
- connect(tb_container,SIGNAL(toggled(bool)),this,SLOT(onContToggled()));
+ connect(_typ->cb_resource,SIGNAL(activated(int)),this,SLOT(onResActivated(int)));
+ connect(tb_container,SIGNAL(toggled(bool)),this,SLOT(onContToggled(bool)));
}
</widget>
</item>
<item>
- <widget class="QComboBox" name="cb_resource">
+ <widget class="ComboBox" name="cb_resource">
<property name="toolTip">
<string>name of the resource hosting container when manually set</string>
</property>
</item>
</layout>
</widget>
+ <customwidgets>
+ <customwidget>
+ <class>ComboBox</class>
+ <extends>QComboBox</extends>
+ <header>FormComponent.hxx</header>
+ </customwidget>
+ </customwidgets>
<resources/>
<connections/>
</ui>
break;
}
}
- int studyId = _wrapper->activeStudyId();
- if (context->getStudyId() == studyId)
+ _wrapper->deleteSchema(view);
+ DEBTRACE("delete context");
+ if (GuiExecutor* exec = context->getGuiExecutor())
{
- _wrapper->deleteSchema(view);
- DEBTRACE("delete context");
- if (GuiExecutor* exec = context->getGuiExecutor())
- {
- exec->closeContext();
- }
- delete context;
- _mapViewContext.erase(view);
- switchContext(newView, onExit);
+ exec->closeContext();
}
+ delete context;
+ _mapViewContext.erase(view);
+ switchContext(newView, onExit);
return true;
}
GraphicsView* gView = new GraphicsView(viewWindow);
gView->setScene(scene);
gView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
- int studyId = _wrapper->AssociateViewToWindow(gView, viewWindow);
- context->setStudyId(studyId);
- std::ostringstream value;
- value << studyId;
- proc->setProperty("DefaultStudyID",value.str());
+ _wrapper->AssociateViewToWindow(gView, viewWindow);
context->setScene(scene);
context->setView(gView);
context->setWindow(viewWindow);
void GenericGui::onCleanOnExit()
{
DEBTRACE("GenericGui::onCleanOnExit");
- int studyId = _wrapper->activeStudyId();
map<QWidget*, YACS::HMI::QtGuiContext*> mapViewContextCopy = _mapViewContext;
map<QWidget*, YACS::HMI::QtGuiContext*>::iterator it = mapViewContextCopy.begin();
for (; it != mapViewContextCopy.end(); ++it)
SALOME_NamingService namingService(orb);
SALOME_LifeCycleCORBA lcc(&namingService);
ostringstream containerName;
- containerName << "localhost/YACSContainer" << QtGuiContext::getQtCurrent()->getStudyId();
+ containerName << "localhost/YACSContainer";
Engines::EngineComponent_var comp = lcc.FindOrLoad_Component(containerName.str().c_str(), "YACS" );
_engineRef =YACS_ORB::YACS_Gen::_narrow(comp);
YASSERT(!CORBA::is_nil(_engineRef));
#include <iostream>
#include <fstream>
-#include "ListJobs_GUI.hxx"
#include "RuntimeSALOME.hxx"
+#include "ListJobs_GUI.hxx"
#include "GenericGui.hxx"
#include "QtGuiContext.hxx"
#include "YACSGuiLoader.hxx"
_selectedSubject = 0;
_isEdition = true;
_isLoadingPresentation = false;
- _studyId = 0;
_fileName = QString();
_mapOfSchemaItem.clear();
_mapOfSceneItem.clear();
inline QString getFileName() {return _fileName; };
inline YACS::HMI::GuiExecutor* getGuiExecutor() {return _guiExecutor; };
inline bool isEdition() {return _isEdition; };
- inline int getStudyId() {return _studyId; };
inline bool isLoadingPresentation() {return _isLoadingPresentation; };
YACS::HMI::Subject* getSubjectToPaste(bool &isCut);
inline void setFileName(const QString& fileName) {_fileName = fileName; };
inline void setGuiExecutor(YACS::HMI::GuiExecutor* guiEx) {_guiExecutor = guiEx; };
inline void setEdition(bool isEdition) {_isEdition = isEdition; };
- inline void setStudyId(int studyId) {_studyId = studyId; };
inline void setLoadingPresentation(bool isLoadpres) {_isLoadingPresentation = isLoadpres; };
void setSubjectToCut(YACS::HMI::Subject* sub);
YACS::HMI::Subject* _selectedSubject;
bool _isEdition;
bool _isLoadingPresentation;
- int _studyId;
SuitWrapper* _wrapper;
};
void SceneComposedNodeItem::shrinkExpandRecursive(bool toExpand, bool fromHere, ShrinkMode theShrinkMode)
{
- DEBTRACE("SceneComposedNodeItem::shrinkExpandRecursive " << isExpanding << " " << fromHere << " " << isExpanded() << " " << _label.toStdString());
+ DEBTRACE("SceneComposedNodeItem::shrinkExpandRecursive " << toExpand << " " << fromHere << " " << isExpanded() << " " << _label.toStdString());
bool toChangeShrinkState = false;
switch (theShrinkMode) {
x sauvegarde schema en edition
x import catalogues depuis schemas
x insertion dans SALOME 5
-x boutons-actions zoom, panning, cadre zone à voir, reset vue, fit all
+x boutons-actions zoom, panning, cadre zone à voir, reset vue, fit all
x proc remplit automatiquement toute la vue principale (bouton fit all)
x bouton save ou save as au lieu de export
x Model/view table (ports)
x affichage etat en edition
-x dessins des liens de contrôle
+x dessins des liens de contrôle
x gestion etude SALOME : object browser
x design arbre (edition/execution)
x contournement bug confirmOverwrite QFileDialog Qt 4.3.3 (corrige en 4.3.5)
- drag & drop de ports pour l'ordre dans le tableau, dans la scene
- creation de liens par menu
-x distinguer les liens simples (sans contrôle)
+x distinguer les liens simples (sans contrôle)
- deplacement de noeud a la souris: pouvoir passer par dessus un bloc
(pressed + touche...) transparence, finir le deplacement que s'il y a
la place, ou pousser le bloc ?
- choix d'un port dans le panneau noeud -> arbre, vue
- selection multiples (arbre, tableau vue) pour action groupee
(deplacement scene, destruction...)
-- connexion automatique de ports avec des noeuds bord à bord
+- connexion automatique de ports avec des noeuds bord à bord
(regle de correspondance de noms ? respect de l'ordre ?)
- dessiner les liens avec des ponts quand des liens se croisent !
- 2eme vue avec schema complet et cadre de la vue principale
x message incomprehensible lors de l'ajout d'un deuxieme noeud dans un forloop
x libelle comboBox ajout de ports dans panneau edition: folklorique (newSchema_1)
x fermeture schema non sauvegarde : dialogues de sauvegarde
-x lien nouvellement créé droit et très fin, pas toujours visible
+x lien nouvellement créé droit et très fin, pas toujours visible
x panneau edition function Node: controler nom de fonction saisie (validation)
x panneau edition function Node: remonter le nom de fonction
x remontee d'erreur en edition: le contenu de la log proc ne change pas, quand c'est en erreur
dernier selectionne, idem pour la selection dans l'arbre
(avec correction SchemaItem 1.8)
lie au clearAndSelect dans SchemaItem::select (correction SchemaItem 1.8)
-- selection rubrique containers ou types: précédente selection reste dans canvas et edition
-- destruction component instance : mal repercuté (arbres, map proc...)
-- caractères accentues dans script python d'un noeud python, fichier xml mal chargé
+- selection rubrique containers ou types: précédente selection reste dans canvas et edition
+- destruction component instance : mal repercuté (arbres, map proc...)
+- caractères accentues dans script python d'un noeud python, fichier xml mal chargé
- fermeture vue SALOME, object Browser pas mis a jour mais schema detruit...
- noeud elementaire
-----------------
- - developpé, edition : entete + ports avec nom (valeurs = tooltip ou panneau)
+ - developpé, edition : entete + ports avec nom (valeurs = tooltip ou panneau)
- reduit, edition : entete + ports sans nom
- collapsed, edition : entete seul (que les control link ?)
memes vues en execution (faut il des valeurs sur les ports ?)
-- noeud composé
+- noeud composé
-------------
- - developpé, edition : tout les internes de premier niveau visibles,
+ - developpé, edition : tout les internes de premier niveau visibles,
au moins sous forme reduite
- - macro noeud, edition : un seul macro noeud, presentation du noeud élémentaire developpé
- certains ports internes cachés
- (enrichir description IHM avec notion port privé ? )
- - reduit, edition : un seul macro noeud, presentation du noeud élémentaire réduit
- - collapsed, édition : entete seul
+ - macro noeud, edition : un seul macro noeud, presentation du noeud élémentaire developpé
+ certains ports internes cachés
+ (enrichir description IHM avec notion port privé ? )
+ - reduit, edition : un seul macro noeud, presentation du noeud élémentaire réduit
+ - collapsed, édition : entete seul
memes vues en execution
on peut ajouter 2 methodes dans le DataFlowPort :
recup valeur : string fetch()
chargement valeur : void load(string)
-à dériver dans les ports any, python, corba
+à dériver dans les ports any, python, corba
# additional include directories
INCLUDE_DIRECTORIES(
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${LIBXML2_INCLUDE_DIR}
${PYTHON_INCLUDE_DIR}
${PROJECT_SOURCE_DIR}/src/bases
# imports python
import unittest
-import exceptions
-from exceptions import RuntimeError
import os
import shutil
self.tmpDir += "PmmlUnitTest";
self.tmpDir += os.sep ;
if ( not os.path.exists(self.tmpDir) ):
- os.mkdir(self.tmpDir);
+ os.makedirs(self.tmpDir);
pass
pass
model = "sANNName";
exportPyScript = self.tmpDir + "swigTestExportPythonNeuralNet.py";
refPyFilename = self.resourcesDir + "unittest_ref_ann_model.py";
- refLines = file(refPyFilename).readlines();
+ with open(refPyFilename,"r") as f:
+ refLines = f.readlines();
#
p = PMMLlib( pmmlFile );
p.SetCurrentModel( model, kANN );
p.ExportPython( exportPyScript, "myTestFunc",
"File used by unit test\n PMMLBasicsTest1::testExportNeuralNetworkPython" );
- myLines = file(exportPyScript).readlines();
+ with open(exportPyScript,"r") as f:
+ myLines = f.readlines();
self.assertEqual( len(myLines), len(refLines) );
for (i,line) in enumerate(myLines):
self.assertEqual( line, refLines[i] );
model = "Modeler[LinearRegression]Tds[steamplant]Predictor[x6:x8:x6x8:x6x6x8]Target[x1]";
exportPyScript = self.tmpDir + "swigTestExportPythonRegression.py";
refPyFilename = self.resourcesDir + "unittest_ref_lr_model.py";
- refLines = file(refPyFilename).readlines();
+ with open(refPyFilename,"r") as f:
+ refLines = f.readlines();
#
p = PMMLlib( pmmlFile );
p.SetCurrentModel( model, kLR );
p.ExportPython( exportPyScript, "myTestFunc",
"File used by unit test\n PMMLBasicsTest1::testExportLinearRegressionPython" );
- myLines = file(exportPyScript).readlines();
+ with open(exportPyScript,"r") as f:
+ myLines = f.readlines();
self.assertEqual( len(myLines), len(refLines) );
for (i,line) in enumerate(myLines):
self.assertEqual( line, refLines[i] );
os.chdir("..")
# GO !
dn=os.path.dirname(__file__)
-p=subprocess.Popen(["python","PMMLBasicsTest.py"],cwd=dn,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
+p=subprocess.Popen(["python3","PMMLBasicsTest.py"],cwd=dn,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
a,b=p.communicate()
ret=p.returncode
# Clean up the wonderful first part stuf
INCLUDE_DIRECTORIES(
${PYTHON_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${SALOME_INCL_PATH}
${PROJECT_SOURCE_DIR}/src/bases
${PROJECT_SOURCE_DIR}/src/engine
{
CPPUNIT_FAIL(e.what());
}
+ catch(std::exception& e)
+ {
+ CPPUNIT_FAIL(e.what());
+ }
catch(...)
{
CPPUNIT_FAIL("Unknown exception");
std::cerr << "===============================================" << std::endl;
CPPUNIT_ASSERT(what.find(error_message) != std::string::npos);
}
+ catch(std::exception& e)
+ {
+ CPPUNIT_FAIL(e.what());
+ }
}
static
std::cerr << "===============================================" << std::endl;
CPPUNIT_ASSERT(what.find(error_message) != std::string::npos);
}
+ catch(std::exception& e)
+ {
+ CPPUNIT_FAIL(e.what());
+ }
}
void Py2yacsTest::t1()
void Py2yacsTest::t3()
{
const char * code_py = "def f1(a, b, c):\n"
- " print a\n"
- " print b\n"
- " print c\n";
+ " print(a)\n"
+ " print(b)\n"
+ " print(c)\n";
const char* input_ports[] = {"a", "b", "c"};
const char** output_ports;
verifyCorrectPycode(code_py, "f1", 3, input_ports, 0, output_ports);
void Py2yacsTest::t4()
{
const char * code_py = "def f1():\n"
- " print 'toto'\n"
+ " print('toto')\n"
" return\n";
const char* input_ports[] = {"a", "b", "c"};
const char** output_ports;
const char * code_py = "def f(a):\n"
" return a\n"
"if __name__ == '__main__':"
- " print 'toto'\n";
+ " print('toto')\n";
verifyWrongPycode(code_py, "f", "not accepted statement");
}
{
const char * code_py = "bla bla bla\n"
" return f1(x)\n";
- verifyWrongPycode(code_py, "f2", "SyntaxError");
+ verifyWrongPycode(code_py, "f2", "invalid syntax");
}
void Py2yacsTest::badFunctionName()
// Test the behaviour when there is an error in the python parser
void Py2yacsTest::parserErrors()
{
- verifyWrongParser("bad_parsers", "p1", "argument");
- verifyWrongParser("bad_parsers", "p2", "Attribute 'name' not found");
+ verifyWrongParser("bad_parsers", "p1", "0 positional arguments");
+ verifyWrongParser("bad_parsers", "p2", "'str' object has no attribute 'name'");
verifyWrongParser("bad_parsers", "p3", "should be a python list");
- verifyWrongParser("bad_parsers", "p4", "Traceback");
+ verifyWrongParser("bad_parsers", "p4", "unsupported operand type");
verifyWrongParser("bad_parsers", "f", "Cannot find the parsing function");
verifyWrongParser("err_py2yacs_invalid", "get_properties", "invalid syntax");
verifyWrongParser("no_file", "f", "Failed to load");
- verifyWrongParser("bad_parsers", "p5", " ");
- verifyWrongParser("bad_parsers", "p6", " ");
- verifyWrongParser("bad_parsers", "p7", " ");
+ verifyWrongParser("bad_parsers", "p5", "is not a string");
+ verifyWrongParser("bad_parsers", "p6", "is not a string");
+ verifyWrongParser("bad_parsers", "p7", "is not a string");
verifyWrongParser("bad_parsers", "p8", "Attribute 'name' should be a string.");
- verifyWrongParser("bad_parsers", "p9", " ");
- verifyWrongParser("bad_parsers", "p10", " ");
+ verifyWrongParser("bad_parsers", "p9", "Not a python list");
+ verifyWrongParser("bad_parsers", "p10", "is not a string");
}
void Py2yacsTest::globalVerification()
std::cerr << "-----------------------------------------" << std::endl;
}
-}
\ No newline at end of file
+}
static
std::string copyList(PyObject *pyList, std::list<std::string>& cppList)
{
- std::string error;
+ std::string error="";
if(!PyList_Check(pyList))
{
error = "Not a python list.\n";
}
else
{
- int n = PyList_Size(pyList);
- for(int i=0; i<n; i++)
+ Py_ssize_t n = PyList_Size(pyList);
+ for(Py_ssize_t i=0; i<n; i++)
{
PyObject *elem = PyList_GetItem(pyList,i);
- if(!PyString_Check(elem))
+ if(!PyUnicode_Check(elem))
{
std::stringstream message;
message << "List element number " << i << " is not a string.\n";
}
else
{
- const char * portName = PyString_AsString(elem);
- cppList.push_back(portName);
+ cppList.push_back(std::string(PyUnicode_AsUTF8(elem)));
}
}
}
PyObject *pystr, *module_name, *pyth_module, *pyth_func;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
pystr = PyObject_Str(pvalue);
- result = PyString_AsString(pystr);
+ result = std::string(PyUnicode_AsUTF8(pystr));
result += "\n";
Py_DECREF(pystr);
/* See if we can get a full traceback */
if(ptraceback)
{
- module_name = PyString_FromString("traceback");
+ module_name = PyUnicode_FromString("traceback");
pyth_module = PyImport_Import(module_name);
Py_DECREF(module_name);
if (pyth_module)
for(int i=0; i<n; i++)
{
pystr = PyList_GetItem(pyList,i);
- result += PyString_AsString(pystr);
+ result += std::string(PyUnicode_AsUTF8(pystr));
}
Py_DECREF(pyList);
}
// Py_Initialize();
YACS::ENGINE::AutoGIL agil;
- pValue = PyString_FromString(_python_parser_module.c_str());
+ pValue = PyUnicode_FromString(_python_parser_module.c_str());
pModule = PyImport_Import(pValue);
Py_DECREF(pValue);
if (pFunc && PyCallable_Check(pFunc))
{
pArgs = PyTuple_New(1);
- pValue = PyString_FromString(python_code.c_str());
+ pValue = PyUnicode_FromString(python_code.c_str());
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
{
errorMessage += "Parsing function should return a tuple of two string lists.\n";
}
- int n = PyTuple_Size(pValue);
+ Py_ssize_t n = PyTuple_Size(pValue);
if(n != 2)
{
errorMessage += "Parsing function should return two string lists.\n";
if(pAttribute = checkAndGetAttribute(fpy, "name", errorMessage))
{
- if(!PyString_Check(pAttribute))
+ if(!PyUnicode_Check(pAttribute))
{
errorMessage += "Attribute 'name' should be a string.\n";
Py_DECREF(pAttribute);
{
_functions.push_back(FunctionProperties());
FunctionProperties& fcpp = _functions.back();
- fcpp._name=PyString_AsString(pAttribute);
+ fcpp._name=std::string(PyUnicode_AsUTF8(pAttribute));
Py_DECREF(pAttribute);
if(pAttribute = checkAndGetAttribute(fpy, "inputs", errorMessage))
class v(ast.NodeVisitor):
def visit_Module(self, node):
- #print type(node).__name__, ":"
+ #print(type(node).__name__, ":")
accepted_tokens = ["Import", "ImportFrom", "FunctionDef", "ClassDef"]
#print "module body:"
self.global_errors=[]
error="py2yacs error at line %s: not accepted statement '%s'." % (
e.lineno, type_name)
self.global_errors.append(error)
- #print type_name
- #print "------------------------------------------------------------------"
+ #print(type_name)
+ #print("------------------------------------------------------------------")
self.functions=[]
self.lastfn=""
self.infunc=False
self.generic_visit(node)
pass
def visit_FunctionDef(self, node):
- #print type(node).__name__, ":", node.name
+ #print(type(node).__name__, ":", node.name)
if not self.infunc:
self.lastfn = FunctionProperties(node.name)
self.functions.append(self.lastfn)
self.lastfn = None
self.infunc=False
pass
- def visit_arguments(self, node):
- #print type(node).__name__, ":"
- self.inargs=True
- self.generic_visit(node)
- self.inargs=False
- pass
- def visit_Name(self, node):
- if self.inargs :
- #print type(node).__name__, ":", node.id
- self.lastname=node.id
- self.generic_visit(node)
- pass
- def visit_Param(self, node):
- #print type(node).__name__, ":", self.lastname
- self.lastfn.inputs.append(self.lastname)
+ def visit_arg(self, node):
+ #print(type(node).__name__, ":", node.arg)
+ self.lastfn.inputs.append(node.arg)
pass
def visit_Return(self, node):
- #print type(node).__name__, ":", node.value
+ #print(type(node).__name__, ":", node.value)
if self.lastfn.outputs is not None :
error="py2yacs error at line %s: multiple returns." % node.lineno
self.lastfn.errors.append(error)
fn_name = args.def_name
functions,errors = get_properties(text_file)
- print "global errors:", errors
+ print("global errors:", errors)
for f in functions:
- print f
+ print(f)
fn_properties = next((f for f in functions if f.name == fn_name), None)
if fn_properties is not None :
fn_properties.inputs, fn_properties.outputs,
args.output)
else:
- print "\n".join(fn_properties.errors)
+ print("\n".join(fn_properties.errors))
else:
- print "Function not found:", fn_name
-
\ No newline at end of file
+ print("Function not found:", fn_name)
${PROJECT_SOURCE_DIR}/src/py2yacs
${PROJECT_BINARY_DIR}/src/py2yacs
${GUI_INCLUDE_DIRS}
+ ${OMNIORB_INCLUDE_DIR}
+ ${OMNIORB_ROOT_DIR}/include/omniORB4/internal
+ ${OMNIORBPY_INCLUDE_DIR}
)
# additional preprocessor / compiler flags
ADD_DEFINITIONS(
${QT_DEFINITIONS}
${GUI_DEFINITIONS}
+ ${OMNIORB_DEFINITIONS}
${PYTHON_DEFINITIONS})
SET(_link_LIBRARIES
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
+#include "RuntimeSALOME.hxx"
#include "Py2YacsDialog.hxx"
#include <QApplication>
-#include "RuntimeSALOME.hxx"
#include "Proc.hxx"
#include <iostream>
"""
import sys,os
from qt import *
-import Tree
-import PanelManager
-import BoxManager
-import Icons
-import Items
-import adapt
-import Item
-import logview
+from . import Tree
+from . import PanelManager
+from . import BoxManager
+from . import Icons
+from . import Items
+from . import adapt
+from . import Item
+from . import logview
import pilot
import threading
import time
-import CONNECTOR
-import catalog
+from . import CONNECTOR
+from . import catalog
import traceback
import glob
def run(self):
try:
self.executor.RunW(self.proc,0)
- except ValueError,ex:
+ except ValueError as ex:
#traceback.print_exc()
QApplication.postEvent(self.parent, ErrorEvent('YACS execution error',str(ex)))
if __name__ == "__main__":
- from Item import Item
+ from .Item import Item
app = QApplication(sys.argv)
t=Appli()
t.objectBrowser.additem(Item("item1"))
#
from qt import *
-import CONNECTOR
+from . import CONNECTOR
class BoxManager(QWidgetStack):
""" A BoxManager manages a collection of widget
CONNECTOR.Connect(self.rootItem,"selected",self.setview,())
def setview(self,item):
- if not self.panels.has_key(item):
+ if item not in self.panels:
CONNECTOR.Connect(item,"changed",self.changePanel,(item,))
panel=item.box(self)
self.panels[item]=panel
self.raiseWidget(self.panels[item])
def changePanel(self,item):
- print "changePanel",item
- if self.panels.has_key(item):
+ print("changePanel",item)
+ if item in self.panels:
self.removeWidget(self.panels[item])
panel=item.box(self)
self.panels[item]=panel
from qtcanvas import *
import pilot
import pypilot
-import Item
+from . import Item
import math
dispatcher=pilot.Dispatcher.getDispatcher()
return menu
def delete(self):
- print "delete link"
+ print("delete link")
def tooltip(self,view,pos):
r = QRect(pos.x(), pos.y(), pos.x()+10, pos.y()+10)
return menu
def connect(self):
- print "ControlItem.connect",self.context
- print self.port
+ print("ControlItem.connect",self.context)
+ print(self.port)
item=Item.adapt(self.port)
- print item
+ print(item)
item.connect()
self.context.connecting(item)
#self.context.connecting(self)
#Protocol to link 2 objects (ports, at first)
#First, notify the canvas View (or any view that can select) we are connecting (see method connect above)
#Second (and last) make the link in the link method of object that was declared connecting
- print "link:",obj
+ print("link:",obj)
def tooltip(self,view,pos):
r = QRect(pos.x(), pos.y(), self.width(), self.height())
def link(self,obj):
#Here we create the link between self and obj.
#self has been declared connecting in connect method
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,OutControlItem):
#Connection possible
l=LinkItem(obj,self,self.canvas())
def link(self,obj):
#Here we create the link between self and obj.
#self has been declared connecting in connect method
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,InControlItem):
#Connection possible
l=LinkItem(self,obj,self.canvas())
return menu
def connect(self):
- print "PortItem.connect",self.context
- print self.port
+ print("PortItem.connect",self.context)
+ print(self.port)
item=Item.adapt(self.port)
- print item
+ print(item)
self.context.connecting(item)
#self.context.connecting(self)
def link(self,obj):
- print "PortItem.link:",obj
+ print("PortItem.link:",obj)
def tooltip(self,view,pos):
r = QRect(pos.x(),pos.y(),self.width(), self.height())
def link(self,obj):
#Here we create the link between self and obj.
#self has been declared connecting in connect method
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,OutPortItem):
#Connection possible
l=LinkItem(obj,self,self.canvas())
def link(self,obj):
#Here we create the link between self and obj.
#self has been declared connecting in connect method
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,InPortItem):
#Connection possible
l=LinkItem(self,obj,self.canvas())
color= self.colors.get(color,Qt.white)
self.setBrush(QBrush(color))
else:
- print "Unknown custom event type:", event.type()
+ print("Unknown custom event type:", event.type())
def moveBy(self,dx,dy):
QCanvasRectangle.moveBy(self,dx,dy)
#QToolTip(view).tip( r, s )
def browse(self):
- print "browse"
+ print("browse")
def selected(self):
"""The canvas item has been selected"""
# -*- coding: iso-8859-15 -*-
#
"""
- La classe CONNECTOR sert à enregistrer les observateurs d'objets et à délivrer
- les messages émis à ces objets.
+ La classe CONNECTOR sert à enregistrer les observateurs d'objets et à délivrer
+ les messages émis à ces objets.
- Le principe général est le suivant : un objet (subscriber) s'enregistre aupres du
+ Le principe général est le suivant : un objet (subscriber) s'enregistre aupres du
connecteur global (theconnector) pour observer un objet emetteur de messages (publisher)
- sur un canal donné (channel). Il demande à etre notifie par appel d'une fonction (listener).
- La séquence est donc :
+ sur un canal donné (channel). Il demande à etre notifie par appel d'une fonction (listener).
+ La séquence est donc :
- enregistrement du subscriber pour le publisher : theconnector.Connect(publisher,channel,listener,args)
- - émission du message par le publisher : theconnector.Emit(publisher,channel,cargs)
+ - émission du message par le publisher : theconnector.Emit(publisher,channel,cargs)
- args et cargs sont des tuples contenant les arguments de la fonction listener qui sera appelée
+ args et cargs sont des tuples contenant les arguments de la fonction listener qui sera appelée
comme suit::
listener(cargs+args)
def Connect(self, object, channel, function, args):
###print "Connect",object, channel, function, args
idx = id(object)
- if self.connections.has_key(idx):
+ if idx in self.connections:
channels = self.connections[idx]
else:
channels = self.connections[idx] = {}
- if channels.has_key(channel):
+ if channel in channels:
receivers = channels[channel]
else:
receivers = channels[channel] = []
try:
receivers = self.connections[id(object)][channel]
except KeyError:
- raise ConnectorError, \
- 'no receivers for channel %s of %s' % (channel, object)
+ raise ConnectorError('no receivers for channel %s of %s' % (channel, object))
for funct,fargs in receivers[:]:
if funct() is None:
del self.connections[id(object)]
return
- raise ConnectorError,\
- 'receiver %s%s is not connected to channel %s of %s' \
- % (function, args, channel, object)
+ raise ConnectorError('receiver %s%s is not connected to channel %s of %s' \
+ % (function, args, channel, object))
def Emit(self, object, channel, *args):
try:
func=rfunc()
if func:
- apply(func, args + fargs)
+ func(*args + fargs)
else:
# Le receveur a disparu
if (rfunc,fargs) in receivers:receivers.remove((rfunc,fargs))
class BoundMethodWeakref(object):
def __init__(self,callable):
- self.Self=weakref.ref(callable.im_self)
- self.Func=weakref.ref(callable.im_func)
+ self.Self=weakref.ref(callable.__self__)
+ self.Func=weakref.ref(callable.__func__)
def __call__(self):
target=self.Self()
class A:pass
class B:
def add(self,a):
- print "add",self,a
+ print("add",self,a)
def __del__(self):
- print "__del__",self
+ print("__del__",self)
def f(a):
- print f,a
- print "a=A()"
+ print(f,a)
+ print("a=A()")
a=A()
- print "b=B()"
+ print("b=B()")
b=B()
- print "c=B()"
+ print("c=B()")
c=B()
Connect(a,"add",b.add,())
Connect(a,"add",b.add,())
Connect(a,"add",c.add,())
Connect(a,"add",f,())
Emit(a,"add",1)
- print "del b"
+ print("del b")
del b
Emit(a,"add",1)
- print "del f"
+ print("del f")
del f
Emit(a,"add",1)
Disconnect(a,"add",c.add,())
#self.canvas().update()
def addNode(self):
- print "addNode"
+ print("addNode")
def zoomIn(self):
m = self.worldMatrix()
def connecting(self,obj):
"""Method called by an item to notify canvasView a connection has begun"""
- print "connecting",obj
+ print("connecting",obj)
self.__connecting=obj
def contentsMouseMoveEvent(self,e):
return menu
def delete(self):
- print "delete link"
+ print("delete link")
def tooltip(self,view,pos):
r = QRect(pos.x(), pos.y(), pos.x()+10, pos.y()+10)
return menu
def connect(self):
- print "connect",self.context
+ print("connect",self.context)
self.context.connecting(self)
def link(self,obj):
- print "link:",obj
+ print("link:",obj)
def tooltip(self,view,pos):
r = QRect(self.x(), self.y(), self.width(), self.height())
link.setToPoint( int(self.x()), int(self.y()) )
def link(self,obj):
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,OutPortItem):
#Connection possible
l=LinkItem(obj,self,self.canvas())
link.setFromPoint( int(self.x()), int(self.y()) )
def link(self,obj):
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,InPortItem):
#Connection possible
l=LinkItem(self,obj,self.canvas())
view.tip( r, s )
def browse(self):
- print "browse"
+ print("browse")
def selected(self):
- print "selected"
+ print("selected")
if __name__=='__main__':
app=QApplication(sys.argv)
import os
from qt import QPixmap
-from imagesxpm import dico_xpm
+from .imagesxpm import dico_xpm
dico_images={}
def get_image(name):
- if dico_images.has_key(name):
+ if name in dico_images:
return dico_images[name]
else :
- if dico_xpm.has_key(name):
+ if name in dico_xpm:
image=QPixmap(dico_xpm[name])
else:
fic_image = os.path.join(os.path.dirname(__file__),"icons",name)
import sys
from qt import *
-import CONNECTOR
-import adapt
+from . import CONNECTOR
+from . import adapt
class Item:
def __init__(self,label=""):
ADAPT=adapt.adapt
items={}
def adapt(obj):
- if items.has_key(obj.ptr()):
+ if obj.ptr() in items:
return items[obj.ptr()]
else:
item= ADAPT(obj,Item)
import sys
import pilot
import SALOMERuntime
-import Item
-import adapt
+from . import Item
+from . import adapt
from qt import *
from qtcanvas import *
-import Editor
-import CItems
+from . import Editor
+from . import CItems
import pygraphviz
import traceback
-import CONNECTOR
-import graph
-import panels
+from . import CONNECTOR
+from . import graph
+from . import panels
class DataLinkItem(Item.Item):
def __init__(self,pin,pout):
return tabWidget
def addNode(self,service):
- print "Composed.addNode",service
+ print("Composed.addNode",service)
#add node service in the parent self which is a ComposedNode
new_node=service.clone(None)
ItemComposedNode.n=ItemComposedNode.n+1
panels=[("Panel1",panel1)]
def addLink(self,link):
- print "Composed.addLink",link
+ print("Composed.addLink",link)
if isinstance(link,DataLinkItem):
self.datalinks.addLink(link)
elif isinstance(link,StreamLinkItem):
class ItemProc(ItemComposedNode):
"""Item pour la procedure"""
def connecting(self,item):
- print "ItemProc.connecting",item
+ print("ItemProc.connecting",item)
self._connecting=item
class ItemPort(Item.Item):
box=panel
def link(self,other):
- print "ItemPort.link:",self,other
+ print("ItemPort.link:",self,other)
def connect(self):
- print "ItemPort.connect:"
+ print("ItemPort.connect:")
self.root.connecting(self)
class ItemInPort(ItemPort):
if not cflink:
#add also a control flow link
fitem.addLink(ControlLinkItem(nodeS,nodeE))
- except ValueError,ex:
+ except ValueError as ex:
traceback.print_exc()
QMessageBox.warning(None,"YACS error",str(ex))
return
l=StreamLinkItem(other.port,self.port)
fitem=Item.adapt(father)
fitem.addLink(l)
- except ValueError,ex:
+ except ValueError as ex:
traceback.print_exc()
QMessageBox.warning(None,"YACS error",str(ex))
return
#
from qt import *
-import CONNECTOR
+from . import CONNECTOR
class PanelManager(QWidgetStack):
""" A PanelManager manages a collection of widget
CONNECTOR.Connect(self.rootItem,"dblselected",self.setview,())
def setview(self,item):
- if not self.panels.has_key(item):
+ if item not in self.panels:
panel=item.panel(self)
self.panels[item]=panel
idd=self.addWidget(panel)
# -*- coding: iso-8859-15 -*-
#
-"""Ce module permet de créer des vues sous forme d'arbre
- Ces vues sont construites à partir des informations
- fournies par un modèle
+"""Ce module permet de créer des vues sous forme d'arbre
+ Ces vues sont construites à partir des informations
+ fournies par un modèle
"""
import sys
from qt import *
-import Icons
-import CONNECTOR
+from . import Icons
+from . import CONNECTOR
class Tree(QListView):
"""Tree(parent=None)
if __name__ == "__main__":
- from Item import Item
+ from .Item import Item
app = QApplication(sys.argv)
t=Tree()
t.additem(Item("item1"))
else:
adapter = factory(obj, protocol, alternate)
if adapter is AdaptationError:
- raise AdaptationError,obj
+ raise AdaptationError(obj)
else:
return adapter
#
from qt import *
-import Tree
-from BoxManager import BoxManager
+from . import Tree
+from .BoxManager import BoxManager
class Browser(QVBox):
def __init__(self,parent,appli):
#
from qt import *
-import browser
-import cataitems
+from . import browser
+from . import cataitems
class Browser(browser.Browser):
def init(self):
self.connect( but1, SIGNAL("clicked()"), self.handleBut1 )
def handleBut1(self):
- print "handleBut1",self.selected
+ print("handleBut1",self.selected)
if hasattr(self.selected,"addNode"):
self.selected.addNode(self.appli)
return
import sys
from qt import *
-import browser
-import sessions
+from . import browser
+from . import sessions
import pilot
class Browser(browser.Browser):
from qt import *
-import Item
-import CONNECTOR
-import Items
+from . import Item
+from . import CONNECTOR
+from . import Items
class Obj(Item.Item):
def __init__(self,root=None):
def getChildren(self):
sublist=[]
- for service in self.compo._serviceMap.values():
+ for service in list(self.compo._serviceMap.values()):
itemservice=ItemService(service,self.root)
sublist.append(itemservice)
return sublist
def getChildren(self):
sublist=[]
- for name,typ in self.typeMap.items():
+ for name,typ in list(self.typeMap.items()):
itemtype=ItemType(typ,self.root,name)
sublist.append(itemtype)
return sublist
def getChildren(self):
sublist=[]
- for compo in self.compoMap.values():
+ for compo in list(self.compoMap.values()):
itemcompo=ItemCompo(compo,self.root)
sublist.append(itemcompo)
return sublist
def getChildren(self):
sublist=[]
- for node in self.nodesMap.values():
+ for node in list(self.nodesMap.values()):
itemnode=ItemNode(node,self.root)
sublist.append(itemnode)
return sublist
def getChildren(self):
sublist=[]
- for node in self.composedMap.values():
+ for node in list(self.composedMap.values()):
itemnode=ItemComposedNode(node,self.root)
sublist.append(itemnode)
return sublist
#
from qt import *
-import browser_session
-import browser_catalog
+from . import browser_session
+from . import browser_catalog
import pilot
class CatalogTool(QMainWindow):
return
filename = str(fn)
cata=pilot.getRuntime().loadCatalog("proc",filename)
- print cata
- print cata._nodeMap
- for name,node in cata._nodeMap.items():
- print name,node
+ print(cata)
+ print(cata._nodeMap)
+ for name,node in list(cata._nodeMap.items()):
+ print(name,node)
self.register(cata,filename)
def register(self,cata,name):
import sys
import pilot
-import Item
+from . import Item
from qt import *
from qtcanvas import *
-from GraphViewer import GraphViewer
-import Editor
-import CItems
+from .GraphViewer import GraphViewer
+from . import Editor
+from . import CItems
import pygraphviz
from pygraphviz import graphviz as gv
import traceback
-import CONNECTOR
+from . import CONNECTOR
import bisect
class MyCanvas(QCanvas):
citems[n.ptr()]=c
c.show()
- for k,n in citems.items():
+ for k,n in list(citems.items()):
for p in n.inports:
pitems[p.port.ptr()]=p
for p in n.outports:
self.layout("LR")
def addLink(self,link):
- print "graph.addLink",link
+ print("graph.addLink",link)
#CItem for outport
nodeS=self.citems[link.pout.getNode().ptr()]
nodeE=self.citems[link.pin.getNode().ptr()]
G.graph_attr["dpi"]="72"
dpi=72.
aspect=dpi/72
- for k,n in self.citems.items():
+ for k,n in list(self.citems.items()):
#k is node address (YACS)
#n is item in canvas
G.add_node(k)
continue
G.add_edge(pout.getNode().ptr(),pin.getNode().ptr())
- for k,n in self.citems.items():
+ for k,n in list(self.citems.items()):
for ndown in n.node.getOutNodes():
G.add_edge(n.node.ptr(),ndown.ptr())
self.canvas.update()
def clearLinks(self):
- items=self.citems.values()
+ items=list(self.citems.values())
for node in items:
for port in node.outports:
if not hasattr(port,"links"):
self.canvas.update()
def orthoLinks(self):
- items=self.citems.values()
+ items=list(self.citems.values())
g=grid(items)
for node in items:
for port in node.outports:
self.xs=xs
self.ys=ys
self.cols=[]
- for w in xrange(len(xs)-1):
+ for w in range(len(xs)-1):
col=[]
x=(xs[w]+xs[w+1])/2
- for h in xrange(len(ys)-1):
+ for h in range(len(ys)-1):
y=(ys[h]+ys[h+1])/2
col.append(node((x,y),(w,h)))
self.cols.append(col)
self.open.append((fromNode.total,fromNode))
toNode=self.get(toLoc)
if toNode.blocked:
- print "toNode is blocked"
+ print("toNode is blocked")
return []
destx,desty=toNode.coord
while self.open:
from qt import *
import traceback
-import Editor
-import Item
+from . import Editor
+from . import Item
class PanelScript(QVBox):
def __init__(self,parent,item):
from omniORB import CORBA
import CosNaming
-import Item
-import CONNECTOR
+from . import Item
+from . import CONNECTOR
class Sessions(Item.Item):
def __init__(self,port):
<inParameter-type>string</inParameter-type>
<inParameter-name>CreateHypothesis__anHyp</inParameter-name>
</inParameter>
- <inParameter>
- <inParameter-type>long</inParameter-type>
- <inParameter-name>CreateHypothesis__studyId</inParameter-name>
- </inParameter>
</inParameter-list>
<outParameter-list>
<outParameter>
<inParameter-type>string</inParameter-type>
<inParameter-name>anHyp</inParameter-name>
</inParameter>
- <inParameter>
- <inParameter-type>long</inParameter-type>
- <inParameter-name>studyId</inParameter-name>
- </inParameter>
</inParameter-list>
<outParameter-list>
<outParameter>
</data>
<data>
<fromnode-name>aNewDataFlow_1</fromnode-name>
- <fromserviceparameter-name>CreateHypothesis__studyId</fromserviceparameter-name>
<tonode-name>CreateHypothesis</tonode-name>
- <toserviceparameter-name>studyId</toserviceparameter-name>
<data-value>
<value-type>3</value-type>
<value>1</value>
<inParameter-type>string</inParameter-type>
<inParameter-name>CreateHypothesis__anHyp</inParameter-name>
</inParameter>
- <inParameter>
- <inParameter-type>long</inParameter-type>
- <inParameter-name>CreateHypothesis__studyId</inParameter-name>
- </inParameter>
<inParameter>
<inParameter-type>GEOM_Shape</inParameter-type>
<inParameter-name>AddHypothesis__aSubShape</inParameter-name>
<inParameter-type>string</inParameter-type>
<inParameter-name>anHyp</inParameter-name>
</inParameter>
- <inParameter>
- <inParameter-type>long</inParameter-type>
- <inParameter-name>studyId</inParameter-name>
- </inParameter>
</inParameter-list>
<outParameter-list>
<outParameter>
</data>
<data>
<fromnode-name>aNewDataFlow_1</fromnode-name>
- <fromserviceparameter-name>CreateHypothesis__studyId</fromserviceparameter-name>
<tonode-name>CreateHypothesis</tonode-name>
- <toserviceparameter-name>studyId</toserviceparameter-name>
<data-value>
<value-type>3</value-type>
<value>1</value>
<inParameter-type>string</inParameter-type>
<inParameter-name>CreateHypothesis__anHyp</inParameter-name>
</inParameter>
- <inParameter>
- <inParameter-type>long</inParameter-type>
- <inParameter-name>CreateHypothesis__studyId</inParameter-name>
- </inParameter>
</inParameter-list>
<outParameter-list>
<outParameter>
<inParameter-type>string</inParameter-type>
<inParameter-name>anHyp</inParameter-name>
</inParameter>
- <inParameter>
- <inParameter-type>long</inParameter-type>
- <inParameter-name>studyId</inParameter-name>
- </inParameter>
</inParameter-list>
<outParameter-list>
<outParameter>
</data>
<data>
<fromnode-name>aNewDataFlow_1</fromnode-name>
- <fromserviceparameter-name>CreateHypothesis__studyId</fromserviceparameter-name>
<tonode-name>CreateHypothesis</tonode-name>
- <toserviceparameter-name>studyId</toserviceparameter-name>
<data-value>
<value-type>3</value-type>
<value>1</value>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print "p1:",p1</code>
+ <code> print("p1:",p1)</code>
<code><![CDATA[ condition=p1 < 40.]]> </code>
<code> return p1,condition</code>
</function>
SalomeIDLKernel
SalomeNS
SalomeContainer
+ SalomeKernelHelpers
SALOMEBasics
SalomeResourcesManager
OpUtil
INCLUDE_DIRECTORIES(
${OMNIORB_INCLUDE_DIR}
${OMNIORB_ROOT_DIR}/include/omniORB4/internal
+ ${OMNIORBPY_INCLUDE_DIR}
${SALOME_INCL_PATH}
${PROJECT_SOURCE_DIR}/src/bases
${PROJECT_SOURCE_DIR}/src/engine
std::string InputCorbaPort::valToStr()
{
- int isString = PyString_Check(getPyObj());
+ int isString = PyBytes_Check(getPyObj());
PyObject *strPyObj = PyObject_Str(getPyObj());
- string val = PyString_AsString(strPyObj);
+ string val = PyBytes_AsString(strPyObj);
if (isString)
val = "\"" + val + "\"";
Py_DECREF(strPyObj);
std::string OutputCorbaPort::valToStr()
{
PyObject *strPyObj = PyObject_Str(getPyObj());
- string val = PyString_AsString(strPyObj);
+ string val = PyBytes_AsString(strPyObj);
Py_DECREF(strPyObj);
return val;
}
return false;
}
-CppComponent * CppContainer::createComponentInstance(const std::string & componentName, int /* studyID */)
+CppComponent * CppContainer::createComponentInstance(const std::string & componentName)
{
DEBTRACE("CppContainer::createComponentInstance");
if (_trueCont)
void checkCapabilityToDealWith(const ComponentInstance *inst) const throw (YACS::Exception);
bool loadComponentLibrary(const std::string & componentName) throw (YACS::Exception);
- CppComponent * createComponentInstance(const std::string & componentName, int studyID = 0);
+ CppComponent * createComponentInstance(const std::string & componentName);
void createInternalInstance(const std::string & componentName,
void *& obj, RunFunction &r, TerminateFunction &t);
void unregisterComponentInstance(CppComponent * C);
_errorDetails=msg.str();
throw Exception(msg.str());
}
- const char picklizeScript[]="import cPickle\ndef pickleForDistPyth2009(*args,**kws):\n return cPickle.dumps((args,kws),-1)\n\ndef unPickleForDistPyth2009(st):\n args=cPickle.loads(st)\n return args\n";
+ const char picklizeScript[]="import pickle\ndef pickleForDistPyth2009(*args,**kws):\n return pickle.dumps((args,kws),-1)\n\ndef unPickleForDistPyth2009(st):\n args=pickle.loads(st)\n return args\n";
PyObject *res=PyRun_String(picklizeScript,Py_file_input,_context,_context);
if(res == NULL)
{
PyTuple_SetItem(args,pos,ob);
}
PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
- std::string serializationInputC=PyString_AsString(serializationInput);
+ std::string serializationInputC=PyBytes_AsString(serializationInput);
serializationInputCorba=new Engines::pickledArgs;
int len=serializationInputC.length();
serializationInputCorba->length(serializationInputC.length());
{
AutoGIL agil;
args = PyTuple_New(1);
- PyObject* resultPython=PyString_FromString(resultCorbaC);
+ PyObject* resultPython=PyBytes_FromString(resultCorbaC);
delete [] resultCorbaC;
PyTuple_SetItem(args,0,resultPython);
PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
{
OutputPyPort *p=(OutputPyPort *)*iter;
DEBTRACE( "port name: " << p->getName() );
- DEBTRACE( "port kind: " << p->edGetType()->kind() );
+ DEBTRACE( "port kind: " << p->typeName() );
DEBTRACE( "port pos : " << pos );
if(PyTuple_Check(finalResult))ob=PyTuple_GetItem(finalResult,pos) ;
else ob=finalResult;
static PyTypeObject PyStdOut_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "PyOut", /*tp_name*/
- sizeof(PyStdOut), /*tp_basicsize*/
- 0, /*tp_itemsize*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /*0,*/ /*ob_size*/
+ "PyOut", /*tp_name*/
+ sizeof(PyStdOut), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
/* methods */
(destructor)PyStdOut_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr, /*tp_getattro*/
- /* softspace is writable: we must supply tp_setattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- PyStdOut_methods, /*tp_methods*/
- PyStdOut_memberlist, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ /* softspace is writable: we must supply tp_setattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ PyStdOut_methods, /*tp_methods*/
+ PyStdOut_memberlist, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
std::ostringstream oss; oss << "evalPy failed : " << errorDetails;
throw Exception(oss.str());
}
- AutoPyRef res(PyEval_EvalCode(reinterpret_cast<PyCodeObject *>((PyObject *)code),context,context));
+ AutoPyRef res(PyEval_EvalCode((PyObject *)code,context,context));
PyObject *ret(PyDict_GetItemString(context,funcName.c_str())); //borrowed ref
if(!ret)
throw YACS::Exception("evalPy : Error on returned func !");
using namespace YACS::ENGINE;
using namespace std;
-const char PythonEntry::SCRIPT_FOR_SIMPLE_SERIALIZATION[]="import cPickle\n"
+const char PythonEntry::SCRIPT_FOR_SIMPLE_SERIALIZATION[]="import pickle\n"
"def pickleForVarSimplePyth2009(val):\n"
- " return cPickle.dumps(val,-1)\n"
+ " return pickle.dumps(val,-1)\n"
"\n";
const char PythonNode::IMPL_NAME[]="Python";
const char PythonNode::KIND[]="Python";
-const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import cPickle\n"
+const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
"def pickleForDistPyth2009(kws):\n"
- " return cPickle.dumps(((),kws),-1)\n"
+ " return pickle.dumps(((),kws),-1)\n"
"\n"
"def unPickleForDistPyth2009(st):\n"
- " args=cPickle.loads(st)\n"
+ " args=pickle.loads(st)\n"
" return args\n";
const char PythonNode::REMOTE_NAME[]="remote";
const char PythonNode::DPL_INFO_NAME[]="my_dpl_localization";
-const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import cPickle\n"
+const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
"def pickleForDistPyth2009(*args,**kws):\n"
- " return cPickle.dumps((args,kws),-1)\n"
+ " return pickle.dumps((args,kws),-1)\n"
"\n"
"def unPickleForDistPyth2009(st):\n"
- " args=cPickle.loads(st)\n"
+ " args=pickle.loads(st)\n"
" return args\n";
//The pickled string may contain NULL characters so use PyString_AsStringAndSize
char *serializationInputC(0);
Py_ssize_t len;
- if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
+ if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
throw Exception("DistributedPythonNode problem in python pickle");
serializationInputCorba->length(len);
for(int i=0; i < len ; i++)
{
AutoGIL agil;
PyObject *args(0),*ob(0);
- PyObject* resultPython=PyString_FromStringAndSize(resultCorbaC,resultCorba->length());
+ PyObject* resultPython=PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length());
delete [] resultCorbaC;
args = PyTuple_New(1);
PyTuple_SetItem(args,0,resultPython);
PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
if(code == NULL)
{
- _errorDetails="";
+ _errorDetails="";
PyObject* new_stderr = newPyStdOut(_errorDetails);
PySys_SetObject((char*)"stderr", new_stderr);
PyErr_Print();
Py_DECREF(new_stderr);
throw Exception("Error during execution");
}
- PyObject *res = PyEval_EvalCode((PyCodeObject *)code, _context, _context);
+ PyObject *res = PyEval_EvalCode( code, _context, _context);
Py_DECREF(code);
Py_XDECREF(res);
{
const std::pair<std::string,int>& p(ret[i]);
PyObject *elt(PyTuple_New(2));
- PyTuple_SetItem(elt,0,PyString_FromString(p.first.c_str()));
+ PyTuple_SetItem(elt,0,PyBytes_FromString(p.first.c_str()));
PyTuple_SetItem(elt,1,PyLong_FromLong(p.second));
PyList_SetItem(ob,i,elt);
}
Py_XDECREF(ob);
char *serializationInputC(0);
Py_ssize_t len;
- if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
+ if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
throw Exception("DistributedPythonNode problem in python pickle");
serializationInputCorba->length(len);
for(int i=0; i < len ; i++)
Py_DECREF(new_stderr);
throw Exception("Error during execution");
}
- PyObject *res = PyEval_EvalCode((PyCodeObject *)code, _context, _context);
+ PyObject *res = PyEval_EvalCode( code, _context, _context);
Py_DECREF(code);
Py_XDECREF(res);
//The pickled string may contain NULL characters so use PyString_AsStringAndSize
char *serializationInputC(0);
Py_ssize_t len;
- if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
+ if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
throw Exception("DistributedPythonNode problem in python pickle");
serializationInputCorba->length(len);
{
AutoGIL agil;
- PyObject *resultPython(PyString_FromStringAndSize(resultCorbaC,resultCorba->length()));
+ PyObject *resultPython(PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length()));
delete [] resultCorbaC;
PyObject *args(PyTuple_New(1)),*ob(0);
PyTuple_SetItem(args,0,resultPython);
if (PyObject_HasAttrString(data, (char*)"_is_a"))
{
PyObject *result = PyObject_CallMethod(data, (char*)"_is_a", (char*)"s",(char*)"IDL:SALOME/GenericObj:1.0");
- if(result && PyInt_Check(result))
+ if(result && PyLong_Check(result))
{
- if(PyInt_AS_LONG(result))
+ if(PyLong_AS_LONG(result))
{
PyObject* o=PyObject_CallMethod(data, (char*)"Destroy", (char*)"");
if(o)
if (PyObject_HasAttrString(data, (char*)"_is_a"))
{
PyObject *result = PyObject_CallMethod(data, (char*)"_is_a", (char*)"s",(char*)"IDL:SALOME/GenericObj:1.0");
- if(result && PyInt_Check(result))
+ if(result && PyLong_Check(result))
{
- if(PyInt_AS_LONG(result))
+ if(PyLong_AS_LONG(result))
{
PyObject* o= PyObject_CallMethod(data, (char*)"Register", (char*)"") ;
if(o)
if(!ret)
return dump();
std::string retCpp;
- char *val(PyString_AsString(ret));
+ char *val(PyBytes_AsString(ret));
if(val)
retCpp=val;
Py_XDECREF(ret);
std::string InputPyPort::valToStr()
{
- int isString = PyString_Check(getPyObj());
+ int isString = PyBytes_Check(getPyObj());
//DEBTRACE("isString=" << isString);
PyObject *strPyObj = PyObject_Str(getPyObj());
//DEBTRACE(PyString_Size(strPyObj));
- string val = PyString_AsString(strPyObj);
+ string val = PyBytes_AsString(strPyObj);
if (isString)
val = "\"" + val + "\"";
//DEBTRACE(val);
std::string OutputPyPort::valToStr()
{
PyObject *strPyObj = PyObject_Str(getPyObj());
- string val = PyString_AsString(strPyObj);
+ string val = PyBytes_AsString(strPyObj);
Py_DECREF(strPyObj);
return val;
}
Py_InitializeEx(0); // do not install signal handlers
#endif
if (argc > 0 && argv != NULL)
- PySys_SetArgv(argc, argv);
+ {
+ wchar_t **changed_argv = new wchar_t*[argc];
+ for (int i = 0; i < argc; i++)
+ {
+ changed_argv[i] = Py_DecodeLocale(argv[i], NULL);
+ }
+ PySys_SetArgv(argc, changed_argv);
+ }
else
{
int pyArgc = 1;
char* pyArgv[1];
char defaultName[] = "SALOME_YACS_RUNTIME";
+ wchar_t **changed_pyArgv = new wchar_t*[pyArgc];
pyArgv[0] = defaultName;
- PySys_SetArgv(pyArgc, pyArgv);
+ for (int i = 0; i < pyArgc; i++)
+ {
+ changed_pyArgv[i] = Py_DecodeLocale(pyArgv[i], NULL);
+ }
+ PySys_SetArgv(pyArgc, changed_pyArgv);
}
PyEval_InitThreads(); /* Create (and acquire) the interpreter lock (for threads)*/
PyEval_SaveThread(); /* Release the thread state */
if (PyDict_GetItemString(globals, "__builtins__") == NULL)
{
- PyObject *bimod = PyImport_ImportModule("__builtin__");
+ PyObject *bimod = PyImport_ImportModule("builtins");
if (bimod == NULL || PyDict_SetItemString(globals, "__builtins__", bimod) != 0)
Py_FatalError("can't add __builtins__ to __main__");
Py_DECREF(bimod);
{
goto out;
}
- _api = (omniORBpyAPI*)PyCObject_AsVoidPtr(pyapi);
+ _api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
res=PyRun_String("\n"
"from omniORB import CORBA\n"
"from omniORB import any\n"
"orb = CORBA.ORB_init([], CORBA.ORB_ID)\n"
- "#print sys.getrefcount(orb)\n"
+ "#print(sys.getrefcount(orb))\n"
"try:\n"
" import SALOME\n"
"except:\n"
#ifndef _RUNTIMESALOME_HXX_
#define _RUNTIMESALOME_HXX_
+#include <Python.h>
#include "YACSRuntimeSALOMEExport.hxx"
#undef _XOPEN_SOURCE
#endif
-#include <Python.h>
#include <omniORB4/CORBA.h>
+#include <omniORBpy.h>
#include "Runtime.hxx"
#include<string>
#include<set>
-
-//--- from omniORBpy.h (not present on Debian Sarge packages)
-struct omniORBpyAPI
-{
- PyObject* (*cxxObjRefToPyObjRef)(const CORBA::Object_ptr cxx_obj,
- CORBA::Boolean hold_lock);
- // Convert a C++ object reference to a Python object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- CORBA::Object_ptr (*pyObjRefToCxxObjRef)(PyObject* py_obj,
- CORBA::Boolean hold_lock);
- // Convert a Python object reference to a C++ object reference.
- // Raises BAD_PARAM if the Python object is not an object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- PyObject* (*handleCxxSystemException)(const CORBA::SystemException& ex);
- // Sets the Python exception state to reflect the given C++ system
- // exception. Always returns NULL. The caller must hold the Python
- // interpreter lock.
-};
-//--- end of from omniORBpy.h (not present on Debian Sarge packages)
namespace YACS
{
YACS::BASES::AutoLocker<Container> alck(this);//To be sure
std::string compoName(inst->getCompoName());
Engines::Container_var container(_launchModeType->getContainer(askingNode));
- objComponent=container->find_component_instance(compoName.c_str(),0);
+ objComponent=container->find_component_instance(compoName.c_str());
if(CORBA::is_nil(objComponent))
{
char *reason;
env[item].value <<= itm->second.c_str();
}
- objComponent=contPtr->create_component_instance_env(compoName.c_str(), studyid, env, reason);
+ objComponent=contPtr->create_component_instance_env(compoName.c_str(), env, reason);
if(CORBA::is_nil(objComponent))
{
std::string text="Error while trying to create a new component: component '"+ compoName;
vss.closeFileSchema();
}
-//! Get the default study id for the proc
-/*!
- * \return the study id
- */
-int SalomeProc::getDefaultStudyId()
-{
- std::string value=getProperty("DefaultStudyID");
- if(value.empty())
- return 1;
- else
- return atoi(value.c_str());
-}
-
//! Initialise the proc
void SalomeProc::init(bool start)
{
- std::string value=getProperty("DefaultStudyID");
- if(!value.empty())
- {
- //initialise Python module salome with the study id given by value
- std::string cmd="import salome;salome.salome_init("+value+")";
- PyGILState_STATE gstate = PyGILState_Ensure(); // acquire the Global Interpreter Lock
- PyRun_SimpleString(cmd.c_str());
- PyGILState_Release(gstate); // Release the Global Interpreter Lock
- }
+ //initialise Python module salome with the study id given by value
+ std::string cmd="import salome;salome.salome_init()";
+ PyGILState_STATE gstate = PyGILState_Ensure(); // acquire the Global Interpreter Lock
+ PyRun_SimpleString(cmd.c_str());
+ PyGILState_Release(gstate); // Release the Global Interpreter Lock
Proc::init(start);
}
virtual TypeCode * createStructTc(const std::string& id, const std::string& name);
virtual std::string typeName() {return "YACS__ENGINE__SalomeProc";}
virtual void saveSchema(std::string xmlSchemaFile);
- virtual int getDefaultStudyId();
virtual void init(bool start=true);
};
}
cerr << "---------------SalomePythonNode::load function---------------" << endl;
list<OutputPort *>::iterator iter;
string value2Export=((SalomePythonComponent*)_component)->getStringValueToExportInInterp(this);
- PyObject* ob=PyString_FromString(value2Export.c_str());
+ PyObject* ob=PyBytes_FromString(value2Export.c_str());
PyDict_SetItemString(_context,PLACEMENT_VAR_NAME_IN_INTERP,ob);
for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
{
#include "TypeCode.hxx"
#include "SalomeProc.hxx"
+#include "Basics_Utils.hxx"
#include "SALOME_NamingService.hxx"
+#include "SALOME_KernelServices.hxx"
#include "SALOMEDS.hh"
#include "SALOMEDS_Attributes.hh"
void StudyInNode::execute()
{
DEBTRACE("+++++++ StudyInNode::execute +++++++++++");
- SALOME_NamingService NS(getSALOMERuntime()->getOrb());
- CORBA::Object_var obj=NS.Resolve("/myStudyManager");
- if(CORBA::is_nil(obj))
- {
- _errorDetails="Execution problem: no naming service";
- throw Exception(_errorDetails);
- }
-
- SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow(obj);
- if(CORBA::is_nil(aStudyManager))
- {
- _errorDetails="Execution problem: no naming service";
- throw Exception(_errorDetails);
- }
-
- int studyid=1;
- if (getProperty("StudyID") != "")
- {
- // StudyId is specified
- studyid=atoi(getProperty("StudyID").c_str());
- }
- else
- {
- Proc* p=getProc();
- if(p)
- {
- std::string value=p->getProperty("DefaultStudyID");
- if(!value.empty())
- studyid= atoi(value.c_str());
- }
- }
-
-
- SALOMEDS::Study_var myStudy =aStudyManager->GetStudyByID(studyid);
- if(CORBA::is_nil(myStudy))
- {
- std::stringstream msg;
- msg << "Execution problem: no study with id " << studyid;
- _errorDetails=msg.str();
- throw Exception(_errorDetails);
- }
std::list<OutputPort *>::const_iterator iter;
for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
OutputStudyPort *outp = dynamic_cast<OutputStudyPort *>(*iter);
try
{
- outp->getDataFromStudy(myStudy);
+ outp->getDataFromStudy();
}
catch(Exception& e)
{
}
/*
-SALOMEDS::SObject_ptr findOrCreateSoWithName(SALOMEDS::Study_ptr study, SALOMEDS::StudyBuilder_ptr builder,
+SALOMEDS::SObject_ptr findOrCreateSoWithName(SALOMEDS::StudyBuilder_ptr builder,
SALOMEDS::SObject_ptr sobj, const std::string& name)
{
- SALOMEDS::ChildIterator_var anIterator= study->NewChildIterator(sobj);
+ SALOMEDS::ChildIterator_var anIterator= KERNEL::getStudyServant()->NewChildIterator(sobj);
SALOMEDS::GenericAttribute_var anAttr;
SALOMEDS::AttributeName_var namAttr ;
SALOMEDS::SObject_var result=SALOMEDS::SObject::_nil();
void StudyOutNode::execute()
{
DEBTRACE("+++++++ StudyOutNode::execute +++++++++++");
- SALOME_NamingService NS(getSALOMERuntime()->getOrb());
- CORBA::Object_var obj=NS.Resolve("/myStudyManager");
- if(CORBA::is_nil(obj))
- {
- _errorDetails="Execution problem: no naming service";
- throw Exception(_errorDetails);
- }
-
- SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow(obj);
- if(CORBA::is_nil(aStudyManager))
- {
- _errorDetails="Execution problem: no naming service";
- throw Exception(_errorDetails);
- }
-
- int studyid=1;
- if (getProperty("StudyID") != "")
- {
- // StudyId is specified
- studyid=atoi(getProperty("StudyID").c_str());
- }
- else
- {
- Proc* p=getProc();
- if(p)
- {
- std::string value=p->getProperty("DefaultStudyID");
- if(!value.empty())
- studyid= atoi(value.c_str());
- }
- }
-
- SALOMEDS::Study_var myStudy =aStudyManager->GetStudyByID(studyid);
- if(CORBA::is_nil(myStudy))
- {
- //open a new one
- std::stringstream msg;
- msg << "Study" << studyid;
- myStudy=aStudyManager->NewStudy(msg.str().c_str());
- if(CORBA::is_nil(myStudy))
- {
- _errorDetails="Execution problem: can not create new study " + msg.str();
- throw Exception(_errorDetails);
- }
- }
- DEBTRACE(myStudy->StudyId());
- SALOMEDS::StudyBuilder_var aBuilder =myStudy->NewBuilder() ;
+ SALOMEDS::StudyBuilder_var aBuilder =KERNEL::getStudyServant()->NewBuilder() ;
if(CORBA::is_nil(aBuilder))
{
_errorDetails="Execution problem: can not create StudyBuilder";
for(iter = _setOfInputPort.begin(); iter != _setOfInputPort.end(); iter++)
{
InputStudyPort *inp = dynamic_cast<InputStudyPort *>(*iter);
- inp->putDataInStudy(myStudy,aBuilder);
+ inp->putDataInStudy(aBuilder);
}
// save in file if ref is given
if(_ref != "")
{
- aStudyManager->SaveAs(_ref.c_str(),myStudy, false);
+ KERNEL::getStudyServant()->SaveAs(Kernel_Utils::decode_s( _ref ), false, false);
}
DEBTRACE("+++++++ end StudyOutNode::execute +++++++++++" );
}
#include "RuntimeSALOME.hxx"
#include "SALOMEDS_Attributes.hh"
+#include "SALOME_KernelServices.hxx"
#include <iostream>
#include <iomanip>
return getData();
}
-void OutputStudyPort::getDataFromStudy(SALOMEDS::Study_var myStudy)
+void OutputStudyPort::getDataFromStudy()
{
std::string data = getData();
DEBTRACE("data: " << data );
//try an id
- SALOMEDS::SObject_var aSO = myStudy->FindObjectID(data.c_str());
+ SALOMEDS::SObject_var aSO = KERNEL::getStudyServant()->FindObjectID(data.c_str());
if(CORBA::is_nil(aSO))
{
//try a path
- aSO=myStudy->FindObjectByPath(data.c_str());
+ aSO=KERNEL::getStudyServant()->FindObjectByPath(data.c_str());
if(CORBA::is_nil(aSO))
{
std::stringstream msg;
- msg << "Execution problem: no id or path: " << data << " in study " << myStudy->StudyId();
+ msg << "Execution problem: no id or path: " << data << " in study";
throw Exception(msg.str());
}
}
- CORBA::String_var path=myStudy->GetObjectPath(aSO);
+ CORBA::String_var path=KERNEL::getStudyServant()->GetObjectPath(aSO);
DEBTRACE(path);
CORBA::String_var id=aSO->GetID();
DEBTRACE(id);
-SALOMEDS::SObject_ptr findOrCreateSoWithName(SALOMEDS::Study_ptr study, SALOMEDS::StudyBuilder_ptr builder,
+SALOMEDS::SObject_ptr findOrCreateSoWithName(SALOMEDS::StudyBuilder_ptr builder,
SALOMEDS::SObject_ptr sobj, const std::string& name)
{
- SALOMEDS::ChildIterator_var anIterator= study->NewChildIterator(sobj);
+ SALOMEDS::ChildIterator_var anIterator= KERNEL::getStudyServant()->NewChildIterator(sobj);
SALOMEDS::GenericAttribute_var anAttr;
SALOMEDS::AttributeName_var namAttr ;
SALOMEDS::SObject_var result=SALOMEDS::SObject::_nil();
return getData();
}
-void InputStudyPort::putDataInStudy(SALOMEDS::Study_var myStudy,SALOMEDS::StudyBuilder_var aBuilder)
+void InputStudyPort::putDataInStudy(SALOMEDS::StudyBuilder_var aBuilder)
{
SALOMEDS::GenericAttribute_var aGAttr;
SALOMEDS::SObject_var aSO ;
std::string data = getData();
DEBTRACE("data: " << data );
//try to find an existing id (i:j:k...)
- aSO = myStudy->FindObjectID(data.c_str());
+ aSO = KERNEL::getStudyServant()->FindObjectID(data.c_str());
if(CORBA::is_nil(aSO))
{
// the id does not exist. Try to create it by id
- aSO=myStudy->CreateObjectID(data.c_str());
+ aSO=KERNEL::getStudyServant()->CreateObjectID(data.c_str());
if(!CORBA::is_nil(aSO))
{
aGAttr=aBuilder->FindOrCreateAttribute(aSO,"AttributeName");
SALOMEDS::SObject_var aTmpSO; // initialized to nil
try
{
- aTmpSO = aDriver->PublishInStudy(myStudy, aTmpSO, anObject,objname.c_str() );
+ aTmpSO = aDriver->PublishInStudy(aTmpSO, anObject,objname.c_str() );
return;
}
catch ( ... )
}
// Does component entry exist ?
- aSO=myStudy->FindObjectByPath(pname.c_str());
+ aSO=KERNEL::getStudyServant()->FindObjectByPath(pname.c_str());
if(CORBA::is_nil(aSO))
{
// We have not been able to publish the object with Salome Driver, make it the light way
aGAttr=aBuilder->FindOrCreateAttribute(aFather,"AttributeName");
anAttr = SALOMEDS::AttributeName::_narrow( aGAttr );
anAttr->SetValue(name.c_str());
- aSO=myStudy->FindObjectByPath(pname.c_str());
+ aSO=KERNEL::getStudyServant()->FindObjectByPath(pname.c_str());
}
begin=data.find_first_not_of("/",pos);
name=data.substr(begin,pos-begin);
else
name=data.substr(begin);
- aSO=findOrCreateSoWithName(myStudy,aBuilder,aSO,name);
+ aSO=findOrCreateSoWithName(aBuilder,aSO,name);
begin=data.find_first_not_of("/",pos);
}
}
virtual std::string getPyObj();
virtual std::string getAsString();
virtual std::string typeName() {return "YACS__ENGINE__OutputStudyPort";}
- virtual void getDataFromStudy(SALOMEDS::Study_var myStudy);
+ virtual void getDataFromStudy();
protected:
std::string _storeData;
};
virtual std::string getPyObj();
virtual std::string getAsString();
virtual std::string typeName() {return "YACS__ENGINE__InputStudyPort";}
- virtual void putDataInStudy(SALOMEDS::Study_var myStudy,SALOMEDS::StudyBuilder_var aBuilder);
+ virtual void putDataInStudy(SALOMEDS::StudyBuilder_var aBuilder);
protected:
std::string _storeData;
};
${CPPUNIT_INCLUDE_DIRS}
${PYTHON_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${KERNEL_INCLUDE_DIRS}
${CMAKE_CURRENT_SOURCE_DIR}/..
${CMAKE_CURRENT_SOURCE_DIR}/../../bases
INSTALL(TARGETS echo_clt DESTINATION ${LOCAL_TEST_DIR})
INSTALL(FILES CTestTestfileInstall.cmake
DESTINATION ${LOCAL_TEST_DIR}
- RENAME CTestTestfile.cmake)
\ No newline at end of file
+ RENAME CTestTestfile.cmake)
string s = ss.str();
ElementaryNode* node = _myRuntime->createScriptNode("",s);
_nodeMap[s] = node;
- ((InlineNode*) node)->setScript("print 'node 13'\n"
+ ((InlineNode*) node)->setScript("print('node 13')\n"
"import eo\n"
- "print ob\n"
+ "print(ob)\n"
"o=ob._narrow(eo.Obj)\n"
- "print o\n"
- "print o.echoLong(13)\n"
+ "print(o)\n"
+ "print(o.echoLong(13))\n"
"a=dble+1\n"
"dble=2*a\n"
- "print lng\n"
- "print '++++++++',s,'+++++++++++++'\n"
+ "print(lng)\n"
+ "print('++++++++',s,'+++++++++++++')\n"
"ob=o\n"
"seqstr=['aaa','bbb']\n"
"seqobj=[o,o,o,o]\n"
string s = ss.str();
ElementaryNode* node = _myRuntime->createScriptNode("",s);
_nodeMap[s] = node;
- ((InlineNode*) node)->setScript("print li\n"
- "print 'lili=',lili\n"
- "print 'lstr=',lstr\n"
- "print 'lobj=',lobj\n"
- "print 'llobj=',llobj\n"
- "print 'objc=',objc\n"
+ ((InlineNode*) node)->setScript("print(li)\n"
+ "print('lili=',lili)\n"
+ "print('lstr=',lstr)\n"
+ "print('lobj=',lobj)\n"
+ "print('llobj=',llobj)\n"
+ "print('objc=',objc)\n"
"li=2*li\n"
);
InputPort *i1 = node->edAddInputPort("li", _tc_seqdble);
string s = ss.str();
ElementaryNode* node = _myRuntime->createScriptNode("",s);
_nodeMap[s] = node;
- ((InlineNode*) node)->setScript("print li\n"
+ ((InlineNode*) node)->setScript("print(li)\n"
"li=[2*e for e in li]\n"
- "print 'obj=',obj\n"
- "print li\n"
- "print lngvec\n"
- "print dblevec\n"
+ "print('obj=',obj)\n"
+ "print(li)\n"
+ "print(lngvec)\n"
+ "print(dblevec)\n"
);
InputPort *i1 = node->edAddInputPort("li", _tc_seqdble);
InputPort *i2 = node->edAddInputPort("obj", _tc_obj);
((ElementaryNode*)_nodeMap["Node_10"])->load();
((ElementaryNode*)_nodeMap["Node_10"])->execute();
// CPPUNIT_ASSERT_DOUBLES_EQUAL(10.51, (ElementaryNode*)_nodeMap["Node_10"])
-
DEBTRACE(" --- execution Python Node_11" );
((ElementaryNode*)_nodeMap["Node_11"])->load();
((ElementaryNode*)_nodeMap["Node_11"])->execute();
((ElementaryNode*)_nodeMap["Node_15"])->load();
((ElementaryNode*)_nodeMap["Node_15"])->execute();
+ std::cerr << __LINE__ << std::endl;
DEBTRACE(" --- execution XML Node_36" );
((ElementaryNode*)_nodeMap["Node_36"])->load();
((ElementaryNode*)_nodeMap["Node_36"])->execute();
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import xmlrpclib,sys
+import xmlrpc.client,sys
data="""
<methodCall>
</methodCall>
"""
def echo(args):
- print args
+ print(args)
return args
-f=open("input")
-data=f.read()
-f.close()
-print data
+with open("input",'r') as f:
+ data=f.read()
+print(data)
class Objref:
"""Wrapper for objrefs """
self.data=data
def __str__(self):
return self.data or ""
- def __cmp__(self, other):
+
+# __cmp__ is not defined in Python 3 : strict ordering
+ def __le__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data <= other
+ def __lt__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data < other
+ def __ge__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data >= other
+ def __gt__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data > other
+ def __eq__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data == other
+ def __ne__(self, other):
if isinstance(other, Binary):
other = other.data
- return cmp(self.data, other)
+ return self.data != other
def decode(self, data):
self.data = data
out.write(self.data or "")
out.write("</objref></value>\n")
-xmlrpclib.WRAPPERS=xmlrpclib.WRAPPERS+(Objref,)
+xmlrpc.client.WRAPPERS=xmlrpc.client.WRAPPERS+(Objref,)
def end_objref(self,data):
self.append(Objref(data))
self._value=0
-xmlrpclib.Unmarshaller.end_objref=end_objref
-xmlrpclib.Unmarshaller.dispatch["objref"]=end_objref
+xmlrpc.client.Unmarshaller.end_objref=end_objref
+xmlrpc.client.Unmarshaller.dispatch["objref"]=end_objref
-params, method = xmlrpclib.loads(data)
+params, method = xmlrpc.client.loads(data)
try:
- call=eval(method)
- response=call(params)
- response = (response,)
+ call=eval(method)
+ response=call(params)
+ response = (response,)
except:
- # report exception back to server
- response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2]))
+ # report exception back to server
+ response = xmlrpc.client.dumps( xmlrpc.client.Fault(1, "%s:%s" % sys.exc_info()[:2]))
else:
- response = xmlrpclib.dumps( response, methodresponse=1)
+ response = xmlrpc.client.dumps( response, methodresponse=1)
-print response
-f=open("output",'w')
-f.write(response)
-f.close()
+print(response)
+with open("output",'w') as f:
+ f.write(response)
double x;
if (PyFloat_Check(o))
x=PyFloat_AS_DOUBLE(o);
- else if (PyInt_Check(o))
- x=PyInt_AS_LONG(o);
else if(PyLong_Check(o))
x=PyLong_AsLong(o);
else
static inline long convert(const TypeCode *t,PyObject* o,void*)
{
long l;
- if (PyInt_Check(o))
- l=PyInt_AS_LONG(o);
- else if(PyLong_Check(o))
+ if(PyLong_Check(o))
l=PyLong_AsLong(o);
else
{
static inline std::string convert(const TypeCode *t,PyObject* o,void*)
{
std::string s;
- if (PyString_Check(o))
- s= PyString_AS_STRING(o);
+ if (PyUnicode_Check(o))
+ {
+ Py_ssize_t size;
+ char *ptr = PyUnicode_AsUTF8AndSize(o, &size);
+ if (!ptr)
+ throw YACS::ENGINE::ConversionException("Conversion from PyUnicode to string failed");
+ s.assign(ptr, size);
+ }
else
{
stringstream msg;
bool l;
if (PyBool_Check(o))
l=(o==Py_True);
- else if (PyInt_Check(o))
- l=(PyInt_AS_LONG(o)!=0);
else if(PyLong_Check(o))
l=(PyLong_AsLong(o)!=0);
else
{
static inline std::string convert(const TypeCode *t,PyObject* o,void*,int protocol)
{
- if (PyString_Check(o) && strncmp(t->id(),"python",6)!=0)
+ if (PyUnicode_Check(o) && strncmp(t->id(),"python",6)!=0)
{
// the objref is used by Python as a string (prefix:value) keep it as a string
- return PyString_AS_STRING(o);
+ Py_ssize_t size;
+ std::string s;
+ char *ptr = PyUnicode_AsUTF8AndSize(o, &size);
+ if (!ptr)
+ throw YACS::ENGINE::ConversionException("Conversion from PyUnicode to string failed");
+ s.assign(ptr, size);
+ return s;
}
if(strncmp(t->id(),"python",6)==0)
{
// It's a native Python object pickle it
- PyObject* mod=PyImport_ImportModule("cPickle");
+ PyObject* mod=PyImport_ImportModule("pickle");
PyObject *pickled=PyObject_CallMethod(mod,(char *)"dumps",(char *)"Oi",o,protocol);
- DEBTRACE(PyObject_REPR(pickled) );
+ DEBTRACE(PyObject_Repr(pickled) );
Py_DECREF(mod);
if(pickled==NULL)
{
PyErr_Print();
throw YACS::ENGINE::ConversionException("Problem in convertToYacsObjref<PYTHONImpl");
}
- std::string mystr(PyString_AsString(pickled),PyString_Size(pickled));
+ std::string mystr(PyBytes_AsString(pickled),PyBytes_Size(pickled));
Py_DECREF(pickled);
return mystr;
}
PyErr_Print();
throw YACS::ENGINE::ConversionException("Problem in convertToYacsObjref<PYTHONImpl");
}
- std::string mystr=PyString_AsString(pickled);
+ std::string mystr=PyBytes_AsString(pickled);
Py_DECREF(pickled);
return mystr;
}
PyErr_Print();
throw YACS::ENGINE::ConversionException("Problem in convertToYacsObjref<PYTHONImpl");
}
- std::string mystr=PyString_AsString(pystring);
+ Py_ssize_t size;
+ std::string mystr;
+ char *ptr = PyUnicode_AsUTF8AndSize(pystring, &size);
+ if (!ptr)
+ throw YACS::ENGINE::ConversionException("Conversion from PyUnicode to string failed");
+ mystr.assign(ptr, size);
Py_DECREF(pystring);
return mystr;
}
{
static inline PyObject* convert(const TypeCode *t,std::string& o)
{
- return PyString_FromString(o.c_str());
+ return PyUnicode_FromString(o.c_str());
}
};
template <>
if(t->isA(Runtime::_tc_file))
{
//It's an objref file. Convert it specially
- return PyString_FromString(o.c_str());
+ return PyUnicode_FromString(o.c_str());
}
- if(strncmp(t->id(),"python",6)==0)
+ if(strncmp(t->id(),"python",6)==0) //ex: "python:obj:1.0"
{
//It's a python pickled object, unpickled it
- PyObject* mod=PyImport_ImportModule("cPickle");
- PyObject *ob=PyObject_CallMethod(mod,(char *)"loads",(char *)"s#",o.c_str(),o.length());
- DEBTRACE(PyObject_REPR(ob));
+ PyObject* mod=PyImport_ImportModule("pickle");
+ PyObject *ob=PyObject_CallMethod(mod,(char *)"loads",(char *)"y#",o.c_str(),o.length());
+ DEBTRACE(PyObject_Repr(ob));
Py_DECREF(mod);
if(ob==NULL)
{
PyErr_Print();
throw YACS::ENGINE::ConversionException("Problem in convertToYacsObjref<PYTHONImpl: no simplejson module");
}
- PyObject *ob=PyObject_CallMethod(mod,(char *)"loads",(char *)"s",o.c_str());
+ PyObject *ob=PyObject_CallMethod(mod,(char *)"loads",(char *)"y",o.c_str());
Py_DECREF(mod);
if(ob==NULL)
{
}
PyGILState_STATE gstate = PyGILState_Ensure();
- PyObject* mod=PyImport_ImportModule("cPickle");
- PyObject *ob=PyObject_CallMethod(mod,(char *)"loads",(char *)"s#",s,buffer->length());
+ PyObject* mod=PyImport_ImportModule("pickle");
+ PyObject *ob=PyObject_CallMethod(mod,(char *)"loads",(char *)"y#",s,buffer->length());
PyObject *pickled=PyObject_CallMethod(mod,(char *)"dumps",(char *)"Oi",ob,protocol);
- DEBTRACE(PyObject_REPR(pickled));
- std::string mystr=PyString_AsString(pickled);
+ DEBTRACE(PyObject_Repr(pickled));
+ std::string mystr=PyBytes_AsString(pickled);
Py_DECREF(mod);
Py_DECREF(ob);
Py_DECREF(pickled);
{
PyObject *s;
PyGILState_STATE gstate = PyGILState_Ensure();
- s=PyObject_Str(ob);
- std::string ss(PyString_AsString(s),PyString_Size(s));
+ //s=PyObject_Repr(ob);
+ s=PyObject_ASCII(ob);
+ Py_ssize_t size;
+ char* characters=PyUnicode_AsUTF8AndSize(s, &size);
+ std::string ss( characters, size);
Py_DECREF(s);
PyGILState_Release(gstate);
return ss;
{
if (PyFloat_Check(o))
return true;
- else if (PyInt_Check(o))
- return true;
else if(PyLong_Check(o))
return true;
else
template<>
inline bool checkInt<PYTHONImpl,PyObject*,void*>(const TypeCode *t,PyObject* o,void* aux)
{
- if (PyInt_Check(o) || PyLong_Check(o))
+ if (PyLong_Check(o))
return true;
else
{
{
if (PyBool_Check(o))
return true;
- else if (PyInt_Check(o))
- return true;
else if(PyLong_Check(o))
return true;
else
template<>
inline bool checkString<PYTHONImpl,PyObject*,void*>(const TypeCode *t,PyObject* o,void* aux)
{
- if (PyString_Check(o))
+ if (PyUnicode_Check(o))
return true;
else
{
template<>
inline bool checkObjref<PYTHONImpl,PyObject*,void*>(const TypeCode *t,PyObject* o,void* aux)
{
- if (PyString_Check(o))
+ if (PyUnicode_Check(o))
return true;
if(strncmp(t->id(),"python",6)==0) // a Python object is expected (it's always true)
return true;
#include <libxml/parser.h>
#include <string>
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *arg, size_t *size)
+{
+ return _Py_wchar2char(arg, size);
+}
+static wchar_t*
+Py_DecodeLocale(const char *arg, size_t *size)
+{
+ return _Py_char2wchar(arg, size);
+}
+#endif
+
namespace YACS
{
namespace ENGINE
${SALOME_INCL_PATH}
${PTHREAD_INCLUDE_DIRS}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${LIBXML2_INCLUDE_DIR}
${PYTHON_INCLUDE_DIRS}
${PROJECT_BINARY_DIR}/idl
if (!omnipy)
{
PyErr_SetString(PyExc_ImportError,(char*)"Cannot import _omnipy");
- return;
+ return NULL;
}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
- api = (omniORBPYAPI*)PyCObject_AsVoidPtr(pyapi);
+ api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
%}
using namespace std;
using namespace YACS::HMI;
-int Yacsgui::_oldStudyId = -1;
-
Yacsgui::Yacsgui() :
SalomeWrap_Module( "YACS" ) // default name
{
_wrapper = 0;
_genericGui = 0;
_selectFromTree = false;
- _studyContextMap.clear();
+ _studyContext = 0;
}
Yacsgui::~Yacsgui()
_genericGui->createActions();
_genericGui->createMenus();
_genericGui->createTools();
- this->studyActivated();
+ _studyContext = QtGuiContext::getQtCurrent();
// VSR 23/10/2014: note that this is not a good way to create SComponent from this point
// as initialize() method can be potentially called when there's no yet open study;
setToolShown( false );
_genericGui->showDockWidgets(false);
QtGuiContext *context = QtGuiContext::getQtCurrent();
- _studyContextMap[theStudy->id()] = context;
- DEBTRACE("_studyContextMap[theStudy] " << theStudy << " " << context);
+ _studyContext = context;
+ DEBTRACE("_studyContext " << theStudy << " " << context);
return SalomeApp_Module::deactivateModule( theStudy );
}
YASSERT(_genericGui);
_genericGui->switchContext(viewWindow);
- _studyContextMap[getApp()->activeStudy()->id()] = QtGuiContext::getQtCurrent();
+ _studyContext = QtGuiContext::getQtCurrent();
if (_selectFromTree) return;
SalomeWrap_DataModel *model = dynamic_cast<SalomeWrap_DataModel*>(dataModel());
}
}
-void Yacsgui::studyActivated()
-{
- int newStudyId = getApp()->activeStudy()->id();
- DEBTRACE("Yacsgui::studyActivated " << _oldStudyId << " " << newStudyId);
-
- if (_oldStudyId != -1)
- {
- _studyContextMap[_oldStudyId] = QtGuiContext::getQtCurrent();
- if (_studyContextMap.count(newStudyId))
- {
- DEBTRACE("switch to valid context " << QtGuiContext::getQtCurrent() << " " << _studyContextMap[newStudyId]);
- QtGuiContext::setQtCurrent(_studyContextMap[newStudyId]);
- }
- else
- {
- DEBTRACE("no switch to null context");
- }
- }
- _oldStudyId = newStudyId;
-}
-
void Yacsgui::loadSchema(const std::string& filename,bool edit, bool arrangeLocalNodes)
{
_genericGui->loadSchema(filename,edit,arrangeLocalNodes);
virtual void createPreferences();
virtual void preferencesChanged( const QString& sect, const QString& name );
virtual void loadSchema(const std::string& filename,bool edit=true, bool arrangeLocalNodes=false);
- virtual void studyActivated();
public slots:
bool deactivateModule( SUIT_Study* theStudy);
bool _selectFromTree;
Yacsgui_Resource* _myresource;
SUIT_ViewWindow* _currentSVW;
- std::map<int, YACS::HMI::QtGuiContext*> _studyContextMap;
- static int _oldStudyId;
+ YACS::HMI::QtGuiContext* _studyContext;
};
#endif
<component-author>P. RASCLE</component-author>
<component-version>@SALOMEYACS_VERSION@</component-version>
<component-comment>EDF - RD</component-comment>
- <component-multistudy>1</component-multistudy>
<component-icone>ModuleYacs.png</component-icone>
<constraint>'linux' ~ OS</constraint>
<?xml version='1.0'?>
<proc>
- <property name="DefaultStudyID" value="1"/>
<objref name="GEOM_Shape" id="IDL:GEOM/GEOM_Object:1.0"/>
<type name="bool" kind="bool"/>
<sequence name="boolvec" content="bool"/>
SET(salomeloader_PYTHON
salomeloader.py
- ElementTree.py
- ElementPath.py
graph.py
)
+++ /dev/null
-#
-# ElementTree
-# $Id$
-#
-# limited xpath support for element trees
-#
-# history:
-# 2003-05-23 fl created
-# 2003-05-28 fl added support for // etc
-# 2003-08-27 fl fixed parsing of periods in element names
-#
-# Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved.
-#
-# fredrik@pythonware.com
-# http://www.pythonware.com
-#
-# --------------------------------------------------------------------
-# The ElementTree toolkit is
-#
-# Copyright (c) 1999-2004 by Fredrik Lundh
-#
-# By obtaining, using, and/or copying this software and/or its
-# associated documentation, you agree that you have read, understood,
-# and will comply with the following terms and conditions:
-#
-# Permission to use, copy, modify, and distribute this software and
-# its associated documentation for any purpose and without fee is
-# hereby granted, provided that the above copyright notice appears in
-# all copies, and that both that copyright notice and this permission
-# notice appear in supporting documentation, and that the name of
-# Secret Labs AB or the author not be used in advertising or publicity
-# pertaining to distribution of the software without specific, written
-# prior permission.
-#
-# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
-# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
-# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
-# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
-# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
-# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
-# OF THIS SOFTWARE.
-# --------------------------------------------------------------------
-
-##
-# Implementation module for XPath support. There's usually no reason
-# to import this module directly; the <b>ElementTree</b> does this for
-# you, if needed.
-##
-
-import re
-
-xpath_tokenizer = re.compile(
- "(::|\.\.|\(\)|[/.*:\[\]\(\)@=])|((?:\{[^}]+\})?[^/:\[\]\(\)@=\s]+)|\s+"
- ).findall
-
-class xpath_descendant_or_self:
- pass
-
-##
-# Wrapper for a compiled XPath.
-
-class Path:
-
- ##
- # Create an Path instance from an XPath expression.
-
- def __init__(self, path):
- tokens = xpath_tokenizer(path)
- # the current version supports 'path/path'-style expressions only
- self.path = []
- self.tag = None
- if tokens and tokens[0][0] == "/":
- raise SyntaxError("cannot use absolute path on element")
- while tokens:
- op, tag = tokens.pop(0)
- if tag or op == "*":
- self.path.append(tag or op)
- elif op == ".":
- pass
- elif op == "/":
- self.path.append(xpath_descendant_or_self())
- continue
- else:
- raise SyntaxError("unsupported path syntax (%s)" % op)
- if tokens:
- op, tag = tokens.pop(0)
- if op != "/":
- raise SyntaxError(
- "expected path separator (%s)" % (op or tag)
- )
- if self.path and isinstance(self.path[-1], xpath_descendant_or_self):
- raise SyntaxError("path cannot end with //")
- if len(self.path) == 1 and isinstance(self.path[0], type("")):
- self.tag = self.path[0]
-
- ##
- # Find first matching object.
-
- def find(self, element):
- tag = self.tag
- if tag is None:
- nodeset = self.findall(element)
- if not nodeset:
- return None
- return nodeset[0]
- for elem in element:
- if elem.tag == tag:
- return elem
- return None
-
- ##
- # Find text for first matching object.
-
- def findtext(self, element, default=None):
- tag = self.tag
- if tag is None:
- nodeset = self.findall(element)
- if not nodeset:
- return default
- return nodeset[0].text or ""
- for elem in element:
- if elem.tag == tag:
- return elem.text or ""
- return default
-
- ##
- # Find all matching objects.
-
- def findall(self, element):
- nodeset = [element]
- index = 0
- while 1:
- try:
- path = self.path[index]
- index = index + 1
- except IndexError:
- return nodeset
- set = []
- if isinstance(path, xpath_descendant_or_self):
- try:
- tag = self.path[index]
- if not isinstance(tag, type("")):
- tag = None
- else:
- index = index + 1
- except IndexError:
- tag = None # invalid path
- for node in nodeset:
- new = list(node.getiterator(tag))
- if new and new[0] is node:
- set.extend(new[1:])
- else:
- set.extend(new)
- else:
- for node in nodeset:
- for node in node:
- if path == "*" or node.tag == path:
- set.append(node)
- if not set:
- return []
- nodeset = set
-
-_cache = {}
-
-##
-# (Internal) Compile path.
-
-def _compile(path):
- p = _cache.get(path)
- if p is not None:
- return p
- p = Path(path)
- if len(_cache) >= 100:
- _cache.clear()
- _cache[path] = p
- return p
-
-##
-# Find first matching object.
-
-def find(element, path):
- return _compile(path).find(element)
-
-##
-# Find text for first matching object.
-
-def findtext(element, path, default=None):
- return _compile(path).findtext(element, default)
-
-##
-# Find all matching objects.
-
-def findall(element, path):
- return _compile(path).findall(element)
-
+++ /dev/null
-#
-# ElementTree
-# $Id$
-#
-# light-weight XML support for Python 1.5.2 and later.
-#
-# history:
-# 2001-10-20 fl created (from various sources)
-# 2001-11-01 fl return root from parse method
-# 2002-02-16 fl sort attributes in lexical order
-# 2002-04-06 fl TreeBuilder refactoring, added PythonDoc markup
-# 2002-05-01 fl finished TreeBuilder refactoring
-# 2002-07-14 fl added basic namespace support to ElementTree.write
-# 2002-07-25 fl added QName attribute support
-# 2002-10-20 fl fixed encoding in write
-# 2002-11-24 fl changed default encoding to ascii; fixed attribute encoding
-# 2002-11-27 fl accept file objects or file names for parse/write
-# 2002-12-04 fl moved XMLTreeBuilder back to this module
-# 2003-01-11 fl fixed entity encoding glitch for us-ascii
-# 2003-02-13 fl added XML literal factory
-# 2003-02-21 fl added ProcessingInstruction/PI factory
-# 2003-05-11 fl added tostring/fromstring helpers
-# 2003-05-26 fl added ElementPath support
-# 2003-07-05 fl added makeelement factory method
-# 2003-07-28 fl added more well-known namespace prefixes
-# 2003-08-15 fl fixed typo in ElementTree.findtext (Thomas Dartsch)
-# 2003-09-04 fl fall back on emulator if ElementPath is not installed
-# 2003-10-31 fl markup updates
-# 2003-11-15 fl fixed nested namespace bug
-# 2004-03-28 fl added XMLID helper
-# 2004-06-02 fl added default support to findtext
-# 2004-06-08 fl fixed encoding of non-ascii element/attribute names
-# 2004-08-23 fl take advantage of post-2.1 expat features
-# 2005-02-01 fl added iterparse implementation
-# 2005-03-02 fl fixed iterparse support for pre-2.2 versions
-#
-# Copyright (c) 1999-2005 by Fredrik Lundh. All rights reserved.
-#
-# fredrik@pythonware.com
-# http://www.pythonware.com
-#
-# --------------------------------------------------------------------
-# The ElementTree toolkit is
-#
-# Copyright (c) 1999-2005 by Fredrik Lundh
-#
-# By obtaining, using, and/or copying this software and/or its
-# associated documentation, you agree that you have read, understood,
-# and will comply with the following terms and conditions:
-#
-# Permission to use, copy, modify, and distribute this software and
-# its associated documentation for any purpose and without fee is
-# hereby granted, provided that the above copyright notice appears in
-# all copies, and that both that copyright notice and this permission
-# notice appear in supporting documentation, and that the name of
-# Secret Labs AB or the author not be used in advertising or publicity
-# pertaining to distribution of the software without specific, written
-# prior permission.
-#
-# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
-# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
-# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
-# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
-# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
-# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
-# OF THIS SOFTWARE.
-# --------------------------------------------------------------------
-
-__all__ = [
- # public symbols
- "Comment",
- "dump",
- "Element", "ElementTree",
- "fromstring",
- "iselement", "iterparse",
- "parse",
- "PI", "ProcessingInstruction",
- "QName",
- "SubElement",
- "tostring",
- "TreeBuilder",
- "VERSION", "XML",
- "XMLTreeBuilder",
- ]
-
-##
-# The <b>Element</b> type is a flexible container object, designed to
-# store hierarchical data structures in memory. The type can be
-# described as a cross between a list and a dictionary.
-# <p>
-# Each element has a number of properties associated with it:
-# <ul>
-# <li>a <i>tag</i>. This is a string identifying what kind of data
-# this element represents (the element type, in other words).</li>
-# <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
-# <li>a <i>text</i> string.</li>
-# <li>an optional <i>tail</i> string.</li>
-# <li>a number of <i>child elements</i>, stored in a Python sequence</li>
-# </ul>
-#
-# To create an element instance, use the {@link #Element} or {@link
-# #SubElement} factory functions.
-# <p>
-# The {@link #ElementTree} class can be used to wrap an element
-# structure, and convert it from and to XML.
-##
-
-import string, sys, re
-
-class _SimpleElementPath:
- # emulate pre-1.2 find/findtext/findall behaviour
- def find(self, element, tag):
- for elem in element:
- if elem.tag == tag:
- return elem
- return None
- def findtext(self, element, tag, default=None):
- for elem in element:
- if elem.tag == tag:
- return elem.text or ""
- return default
- def findall(self, element, tag):
- if tag[:3] == ".//":
- return element.getiterator(tag[3:])
- result = []
- for elem in element:
- if elem.tag == tag:
- result.append(elem)
- return result
-
-try:
- import ElementPath
-except ImportError:
- # FIXME: issue warning in this case?
- ElementPath = _SimpleElementPath()
-
-# TODO: add support for custom namespace resolvers/default namespaces
-# TODO: add improved support for incremental parsing
-
-VERSION = "1.2.6"
-
-##
-# Internal element class. This class defines the Element interface,
-# and provides a reference implementation of this interface.
-# <p>
-# You should not create instances of this class directly. Use the
-# appropriate factory functions instead, such as {@link #Element}
-# and {@link #SubElement}.
-#
-# @see Element
-# @see SubElement
-# @see Comment
-# @see ProcessingInstruction
-
-class _ElementInterface:
- # <tag attrib>text<child/>...</tag>tail
-
- ##
- # (Attribute) Element tag.
-
- tag = None
-
- ##
- # (Attribute) Element attribute dictionary. Where possible, use
- # {@link #_ElementInterface.get},
- # {@link #_ElementInterface.set},
- # {@link #_ElementInterface.keys}, and
- # {@link #_ElementInterface.items} to access
- # element attributes.
-
- attrib = None
-
- ##
- # (Attribute) Text before first subelement. This is either a
- # string or the value None, if there was no text.
-
- text = None
-
- ##
- # (Attribute) Text after this element's end tag, but before the
- # next sibling element's start tag. This is either a string or
- # the value None, if there was no text.
-
- tail = None # text after end tag, if any
-
- def __init__(self, tag, attrib):
- self.tag = tag
- self.attrib = attrib
- self._children = []
-
- def __repr__(self):
- return "<Element %s at %x>" % (self.tag, id(self))
-
- ##
- # Creates a new element object of the same type as this element.
- #
- # @param tag Element tag.
- # @param attrib Element attributes, given as a dictionary.
- # @return A new element instance.
-
- def makeelement(self, tag, attrib):
- return Element(tag, attrib)
-
- ##
- # Returns the number of subelements.
- #
- # @return The number of subelements.
-
- def __len__(self):
- return len(self._children)
-
- ##
- # Returns the given subelement.
- #
- # @param index What subelement to return.
- # @return The given subelement.
- # @exception IndexError If the given element does not exist.
-
- def __getitem__(self, index):
- return self._children[index]
-
- ##
- # Replaces the given subelement.
- #
- # @param index What subelement to replace.
- # @param element The new element value.
- # @exception IndexError If the given element does not exist.
- # @exception AssertionError If element is not a valid object.
-
- def __setitem__(self, index, element):
- assert iselement(element)
- self._children[index] = element
-
- ##
- # Deletes the given subelement.
- #
- # @param index What subelement to delete.
- # @exception IndexError If the given element does not exist.
-
- def __delitem__(self, index):
- del self._children[index]
-
- ##
- # Returns a list containing subelements in the given range.
- #
- # @param start The first subelement to return.
- # @param stop The first subelement that shouldn't be returned.
- # @return A sequence object containing subelements.
-
- def __getslice__(self, start, stop):
- return self._children[start:stop]
-
- ##
- # Replaces a number of subelements with elements from a sequence.
- #
- # @param start The first subelement to replace.
- # @param stop The first subelement that shouldn't be replaced.
- # @param elements A sequence object with zero or more elements.
- # @exception AssertionError If a sequence member is not a valid object.
-
- def __setslice__(self, start, stop, elements):
- for element in elements:
- assert iselement(element)
- self._children[start:stop] = list(elements)
-
- ##
- # Deletes a number of subelements.
- #
- # @param start The first subelement to delete.
- # @param stop The first subelement to leave in there.
-
- def __delslice__(self, start, stop):
- del self._children[start:stop]
-
- ##
- # Adds a subelement to the end of this element.
- #
- # @param element The element to add.
- # @exception AssertionError If a sequence member is not a valid object.
-
- def append(self, element):
- assert iselement(element)
- self._children.append(element)
-
- ##
- # Inserts a subelement at the given position in this element.
- #
- # @param index Where to insert the new subelement.
- # @exception AssertionError If the element is not a valid object.
-
- def insert(self, index, element):
- assert iselement(element)
- self._children.insert(index, element)
-
- ##
- # Removes a matching subelement. Unlike the <b>find</b> methods,
- # this method compares elements based on identity, not on tag
- # value or contents.
- #
- # @param element What element to remove.
- # @exception ValueError If a matching element could not be found.
- # @exception AssertionError If the element is not a valid object.
-
- def remove(self, element):
- assert iselement(element)
- self._children.remove(element)
-
- ##
- # Returns all subelements. The elements are returned in document
- # order.
- #
- # @return A list of subelements.
- # @defreturn list of Element instances
-
- def getchildren(self):
- return self._children
-
- ##
- # Finds the first matching subelement, by tag name or path.
- #
- # @param path What element to look for.
- # @return The first matching element, or None if no element was found.
- # @defreturn Element or None
-
- def find(self, path):
- return ElementPath.find(self, path)
-
- ##
- # Finds text for the first matching subelement, by tag name or path.
- #
- # @param path What element to look for.
- # @param default What to return if the element was not found.
- # @return The text content of the first matching element, or the
- # default value no element was found. Note that if the element
- # has is found, but has no text content, this method returns an
- # empty string.
- # @defreturn string
-
- def findtext(self, path, default=None):
- return ElementPath.findtext(self, path, default)
-
- ##
- # Finds all matching subelements, by tag name or path.
- #
- # @param path What element to look for.
- # @return A list or iterator containing all matching elements,
- # in document order.
- # @defreturn list of Element instances
-
- def findall(self, path):
- return ElementPath.findall(self, path)
-
- ##
- # Resets an element. This function removes all subelements, clears
- # all attributes, and sets the text and tail attributes to None.
-
- def clear(self):
- self.attrib.clear()
- self._children = []
- self.text = self.tail = None
-
- ##
- # Gets an element attribute.
- #
- # @param key What attribute to look for.
- # @param default What to return if the attribute was not found.
- # @return The attribute value, or the default value, if the
- # attribute was not found.
- # @defreturn string or None
-
- def get(self, key, default=None):
- return self.attrib.get(key, default)
-
- ##
- # Sets an element attribute.
- #
- # @param key What attribute to set.
- # @param value The attribute value.
-
- def set(self, key, value):
- self.attrib[key] = value
-
- ##
- # Gets a list of attribute names. The names are returned in an
- # arbitrary order (just like for an ordinary Python dictionary).
- #
- # @return A list of element attribute names.
- # @defreturn list of strings
-
- def keys(self):
- return self.attrib.keys()
-
- ##
- # Gets element attributes, as a sequence. The attributes are
- # returned in an arbitrary order.
- #
- # @return A list of (name, value) tuples for all attributes.
- # @defreturn list of (string, string) tuples
-
- def items(self):
- return self.attrib.items()
-
- ##
- # Creates a tree iterator. The iterator loops over this element
- # and all subelements, in document order, and returns all elements
- # with a matching tag.
- # <p>
- # If the tree structure is modified during iteration, the result
- # is undefined.
- #
- # @param tag What tags to look for (default is to return all elements).
- # @return A list or iterator containing all the matching elements.
- # @defreturn list or iterator
-
- def getiterator(self, tag=None):
- nodes = []
- if tag == "*":
- tag = None
- if tag is None or self.tag == tag:
- nodes.append(self)
- for node in self._children:
- nodes.extend(node.getiterator(tag))
- return nodes
-
-# compatibility
-_Element = _ElementInterface
-
-##
-# Element factory. This function returns an object implementing the
-# standard Element interface. The exact class or type of that object
-# is implementation dependent, but it will always be compatible with
-# the {@link #_ElementInterface} class in this module.
-# <p>
-# The element name, attribute names, and attribute values can be
-# either 8-bit ASCII strings or Unicode strings.
-#
-# @param tag The element name.
-# @param attrib An optional dictionary, containing element attributes.
-# @param **extra Additional attributes, given as keyword arguments.
-# @return An element instance.
-# @defreturn Element
-
-def Element(tag, attrib={}, **extra):
- attrib = attrib.copy()
- attrib.update(extra)
- return _ElementInterface(tag, attrib)
-
-##
-# Subelement factory. This function creates an element instance, and
-# appends it to an existing element.
-# <p>
-# The element name, attribute names, and attribute values can be
-# either 8-bit ASCII strings or Unicode strings.
-#
-# @param parent The parent element.
-# @param tag The subelement name.
-# @param attrib An optional dictionary, containing element attributes.
-# @param **extra Additional attributes, given as keyword arguments.
-# @return An element instance.
-# @defreturn Element
-
-def SubElement(parent, tag, attrib={}, **extra):
- attrib = attrib.copy()
- attrib.update(extra)
- element = parent.makeelement(tag, attrib)
- parent.append(element)
- return element
-
-##
-# Comment element factory. This factory function creates a special
-# element that will be serialized as an XML comment.
-# <p>
-# The comment string can be either an 8-bit ASCII string or a Unicode
-# string.
-#
-# @param text A string containing the comment string.
-# @return An element instance, representing a comment.
-# @defreturn Element
-
-def Comment(text=None):
- element = Element(Comment)
- element.text = text
- return element
-
-##
-# PI element factory. This factory function creates a special element
-# that will be serialized as an XML processing instruction.
-#
-# @param target A string containing the PI target.
-# @param text A string containing the PI contents, if any.
-# @return An element instance, representing a PI.
-# @defreturn Element
-
-def ProcessingInstruction(target, text=None):
- element = Element(ProcessingInstruction)
- element.text = target
- if text:
- element.text = element.text + " " + text
- return element
-
-PI = ProcessingInstruction
-
-##
-# QName wrapper. This can be used to wrap a QName attribute value, in
-# order to get proper namespace handling on output.
-#
-# @param text A string containing the QName value, in the form {uri}local,
-# or, if the tag argument is given, the URI part of a QName.
-# @param tag Optional tag. If given, the first argument is interpreted as
-# an URI, and this argument is interpreted as a local name.
-# @return An opaque object, representing the QName.
-
-class QName:
- def __init__(self, text_or_uri, tag=None):
- if tag:
- text_or_uri = "{%s}%s" % (text_or_uri, tag)
- self.text = text_or_uri
- def __str__(self):
- return self.text
- def __hash__(self):
- return hash(self.text)
- def __cmp__(self, other):
- if isinstance(other, QName):
- return cmp(self.text, other.text)
- return cmp(self.text, other)
-
-##
-# ElementTree wrapper class. This class represents an entire element
-# hierarchy, and adds some extra support for serialization to and from
-# standard XML.
-#
-# @param element Optional root element.
-# @keyparam file Optional file handle or name. If given, the
-# tree is initialized with the contents of this XML file.
-
-class ElementTree:
-
- def __init__(self, element=None, file=None):
- assert element is None or iselement(element)
- self._root = element # first node
- if file:
- self.parse(file)
-
- ##
- # Gets the root element for this tree.
- #
- # @return An element instance.
- # @defreturn Element
-
- def getroot(self):
- return self._root
-
- ##
- # Replaces the root element for this tree. This discards the
- # current contents of the tree, and replaces it with the given
- # element. Use with care.
- #
- # @param element An element instance.
-
- def _setroot(self, element):
- assert iselement(element)
- self._root = element
-
- ##
- # Loads an external XML document into this element tree.
- #
- # @param source A file name or file object.
- # @param parser An optional parser instance. If not given, the
- # standard {@link XMLTreeBuilder} parser is used.
- # @return The document root element.
- # @defreturn Element
-
- def parse(self, source, parser=None):
- if not hasattr(source, "read"):
- source = open(source, "rb")
- if not parser:
- parser = XMLTreeBuilder()
- while 1:
- data = source.read(32768)
- if not data:
- break
- parser.feed(data)
- self._root = parser.close()
- return self._root
-
- ##
- # Creates a tree iterator for the root element. The iterator loops
- # over all elements in this tree, in document order.
- #
- # @param tag What tags to look for (default is to return all elements)
- # @return An iterator.
- # @defreturn iterator
-
- def getiterator(self, tag=None):
- assert self._root is not None
- return self._root.getiterator(tag)
-
- ##
- # Finds the first toplevel element with given tag.
- # Same as getroot().find(path).
- #
- # @param path What element to look for.
- # @return The first matching element, or None if no element was found.
- # @defreturn Element or None
-
- def find(self, path):
- assert self._root is not None
- if path[:1] == "/":
- path = "." + path
- return self._root.find(path)
-
- ##
- # Finds the element text for the first toplevel element with given
- # tag. Same as getroot().findtext(path).
- #
- # @param path What toplevel element to look for.
- # @param default What to return if the element was not found.
- # @return The text content of the first matching element, or the
- # default value no element was found. Note that if the element
- # has is found, but has no text content, this method returns an
- # empty string.
- # @defreturn string
-
- def findtext(self, path, default=None):
- assert self._root is not None
- if path[:1] == "/":
- path = "." + path
- return self._root.findtext(path, default)
-
- ##
- # Finds all toplevel elements with the given tag.
- # Same as getroot().findall(path).
- #
- # @param path What element to look for.
- # @return A list or iterator containing all matching elements,
- # in document order.
- # @defreturn list of Element instances
-
- def findall(self, path):
- assert self._root is not None
- if path[:1] == "/":
- path = "." + path
- return self._root.findall(path)
-
- ##
- # Writes the element tree to a file, as XML.
- #
- # @param file A file name, or a file object opened for writing.
- # @param encoding Optional output encoding (default is US-ASCII).
-
- def write(self, file, encoding="us-ascii"):
- assert self._root is not None
- if not hasattr(file, "write"):
- file = open(file, "wb")
- if not encoding:
- encoding = "us-ascii"
- elif encoding != "utf-8" and encoding != "us-ascii":
- file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
- self._write(file, self._root, encoding, {})
-
- def _write(self, file, node, encoding, namespaces):
- # write XML to file
- tag = node.tag
- if tag is Comment:
- file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
- elif tag is ProcessingInstruction:
- file.write("<?%s?>" % _escape_cdata(node.text, encoding))
- else:
- items = node.items()
- xmlns_items = [] # new namespaces in this scope
- try:
- if isinstance(tag, QName) or tag[:1] == "{":
- tag, xmlns = fixtag(tag, namespaces)
- if xmlns: xmlns_items.append(xmlns)
- except TypeError:
- _raise_serialization_error(tag)
- file.write("<" + _encode(tag, encoding))
- if items or xmlns_items:
- items.sort() # lexical order
- for k, v in items:
- try:
- if isinstance(k, QName) or k[:1] == "{":
- k, xmlns = fixtag(k, namespaces)
- if xmlns: xmlns_items.append(xmlns)
- except TypeError:
- _raise_serialization_error(k)
- try:
- if isinstance(v, QName):
- v, xmlns = fixtag(v, namespaces)
- if xmlns: xmlns_items.append(xmlns)
- except TypeError:
- _raise_serialization_error(v)
- file.write(" %s=\"%s\"" % (_encode(k, encoding),
- _escape_attrib(v, encoding)))
- for k, v in xmlns_items:
- file.write(" %s=\"%s\"" % (_encode(k, encoding),
- _escape_attrib(v, encoding)))
- if node.text or len(node):
- file.write(">")
- if node.text:
- file.write(_escape_cdata(node.text, encoding))
- for n in node:
- self._write(file, n, encoding, namespaces)
- file.write("</" + _encode(tag, encoding) + ">")
- else:
- file.write(" />")
- for k, v in xmlns_items:
- del namespaces[v]
- if node.tail:
- file.write(_escape_cdata(node.tail, encoding))
-
-# --------------------------------------------------------------------
-# helpers
-
-##
-# Checks if an object appears to be a valid element object.
-#
-# @param An element instance.
-# @return A true value if this is an element object.
-# @defreturn flag
-
-def iselement(element):
- # FIXME: not sure about this; might be a better idea to look
- # for tag/attrib/text attributes
- return isinstance(element, _ElementInterface) or hasattr(element, "tag")
-
-##
-# Writes an element tree or element structure to sys.stdout. This
-# function should be used for debugging only.
-# <p>
-# The exact output format is implementation dependent. In this
-# version, it's written as an ordinary XML file.
-#
-# @param elem An element tree or an individual element.
-
-def dump(elem):
- # debugging
- if not isinstance(elem, ElementTree):
- elem = ElementTree(elem)
- elem.write(sys.stdout)
- tail = elem.getroot().tail
- if not tail or tail[-1] != "\n":
- sys.stdout.write("\n")
-
-def _encode(s, encoding):
- try:
- return s.encode(encoding)
- except AttributeError:
- return s # 1.5.2: assume the string uses the right encoding
-
-if sys.version[:3] == "1.5":
- _escape = re.compile(r"[&<>\"\x80-\xff]+") # 1.5.2
-else:
- _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"'))
-
-_escape_map = {
- "&": "&",
- "<": "<",
- ">": ">",
- '"': """,
-}
-
-_namespace_map = {
- # "well-known" namespace prefixes
- "http://www.w3.org/XML/1998/namespace": "xml",
- "http://www.w3.org/1999/xhtml": "html",
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
- "http://schemas.xmlsoap.org/wsdl/": "wsdl",
-}
-
-def _raise_serialization_error(text):
- raise TypeError(
- "cannot serialize %r (type %s)" % (text, type(text).__name__)
- )
-
-def _encode_entity(text, pattern=_escape):
- # map reserved and non-ascii characters to numerical entities
- def escape_entities(m, map=_escape_map):
- out = []
- append = out.append
- for char in m.group():
- text = map.get(char)
- if text is None:
- text = "&#%d;" % ord(char)
- append(text)
- return string.join(out, "")
- try:
- return _encode(pattern.sub(escape_entities, text), "ascii")
- except TypeError:
- _raise_serialization_error(text)
-
-#
-# the following functions assume an ascii-compatible encoding
-# (or "utf-16")
-
-def _escape_cdata(text, encoding=None, replace=string.replace):
- # escape character data
- try:
- if encoding:
- try:
- text = _encode(text, encoding)
- except UnicodeError:
- return _encode_entity(text)
- text = replace(text, "&", "&")
- text = replace(text, "<", "<")
- text = replace(text, ">", ">")
- return text
- except (TypeError, AttributeError):
- _raise_serialization_error(text)
-
-def _escape_attrib(text, encoding=None, replace=string.replace):
- # escape attribute value
- try:
- if encoding:
- try:
- text = _encode(text, encoding)
- except UnicodeError:
- return _encode_entity(text)
- text = replace(text, "&", "&")
- text = replace(text, "'", "'") # FIXME: overkill
- text = replace(text, "\"", """)
- text = replace(text, "<", "<")
- text = replace(text, ">", ">")
- return text
- except (TypeError, AttributeError):
- _raise_serialization_error(text)
-
-def fixtag(tag, namespaces):
- # given a decorated tag (of the form {uri}tag), return prefixed
- # tag and namespace declaration, if any
- if isinstance(tag, QName):
- tag = tag.text
- namespace_uri, tag = string.split(tag[1:], "}", 1)
- prefix = namespaces.get(namespace_uri)
- if prefix is None:
- prefix = _namespace_map.get(namespace_uri)
- if prefix is None:
- prefix = "ns%d" % len(namespaces)
- namespaces[namespace_uri] = prefix
- if prefix == "xml":
- xmlns = None
- else:
- xmlns = ("xmlns:%s" % prefix, namespace_uri)
- else:
- xmlns = None
- return "%s:%s" % (prefix, tag), xmlns
-
-##
-# Parses an XML document into an element tree.
-#
-# @param source A filename or file object containing XML data.
-# @param parser An optional parser instance. If not given, the
-# standard {@link XMLTreeBuilder} parser is used.
-# @return An ElementTree instance
-
-def parse(source, parser=None):
- tree = ElementTree()
- tree.parse(source, parser)
- return tree
-
-##
-# Parses an XML document into an element tree incrementally, and reports
-# what's going on to the user.
-#
-# @param source A filename or file object containing XML data.
-# @param events A list of events to report back. If omitted, only "end"
-# events are reported.
-# @return A (event, elem) iterator.
-
-class iterparse:
-
- def __init__(self, source, events=None):
- if not hasattr(source, "read"):
- source = open(source, "rb")
- self._file = source
- self._events = []
- self._index = 0
- self.root = self._root = None
- self._parser = XMLTreeBuilder()
- # wire up the parser for event reporting
- parser = self._parser._parser
- append = self._events.append
- if events is None:
- events = ["end"]
- for event in events:
- if event == "start":
- try:
- parser.ordered_attributes = 1
- parser.specified_attributes = 1
- def handler(tag, attrib_in, event=event, append=append,
- start=self._parser._start_list):
- append((event, start(tag, attrib_in)))
- parser.StartElementHandler = handler
- except AttributeError:
- def handler(tag, attrib_in, event=event, append=append,
- start=self._parser._start):
- append((event, start(tag, attrib_in)))
- parser.StartElementHandler = handler
- elif event == "end":
- def handler(tag, event=event, append=append,
- end=self._parser._end):
- append((event, end(tag)))
- parser.EndElementHandler = handler
- elif event == "start-ns":
- def handler(prefix, uri, event=event, append=append):
- try:
- uri = _encode(uri, "ascii")
- except UnicodeError:
- pass
- append((event, (prefix or "", uri)))
- parser.StartNamespaceDeclHandler = handler
- elif event == "end-ns":
- def handler(prefix, event=event, append=append):
- append((event, None))
- parser.EndNamespaceDeclHandler = handler
-
- def next(self):
- while 1:
- try:
- item = self._events[self._index]
- except IndexError:
- if self._parser is None:
- self.root = self._root
- try:
- raise StopIteration
- except NameError:
- raise IndexError
- # load event buffer
- del self._events[:]
- self._index = 0
- data = self._file.read(16384)
- if data:
- self._parser.feed(data)
- else:
- self._root = self._parser.close()
- self._parser = None
- else:
- self._index = self._index + 1
- return item
-
- try:
- iter
- def __iter__(self):
- return self
- except NameError:
- def __getitem__(self, index):
- return self.next()
-
-##
-# Parses an XML document from a string constant. This function can
-# be used to embed "XML literals" in Python code.
-#
-# @param source A string containing XML data.
-# @return An Element instance.
-# @defreturn Element
-
-def XML(text):
- parser = XMLTreeBuilder()
- parser.feed(text)
- return parser.close()
-
-##
-# Parses an XML document from a string constant, and also returns
-# a dictionary which maps from element id:s to elements.
-#
-# @param source A string containing XML data.
-# @return A tuple containing an Element instance and a dictionary.
-# @defreturn (Element, dictionary)
-
-def XMLID(text):
- parser = XMLTreeBuilder()
- parser.feed(text)
- tree = parser.close()
- ids = {}
- for elem in tree.getiterator():
- id = elem.get("id")
- if id:
- ids[id] = elem
- return tree, ids
-
-##
-# Parses an XML document from a string constant. Same as {@link #XML}.
-#
-# @def fromstring(text)
-# @param source A string containing XML data.
-# @return An Element instance.
-# @defreturn Element
-
-fromstring = XML
-
-##
-# Generates a string representation of an XML element, including all
-# subelements.
-#
-# @param element An Element instance.
-# @return An encoded string containing the XML data.
-# @defreturn string
-
-def tostring(element, encoding=None):
- class dummy:
- pass
- data = []
- file = dummy()
- file.write = data.append
- ElementTree(element).write(file, encoding)
- return string.join(data, "")
-
-##
-# Generic element structure builder. This builder converts a sequence
-# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
-# #TreeBuilder.end} method calls to a well-formed element structure.
-# <p>
-# You can use this class to build an element structure using a custom XML
-# parser, or a parser for some other XML-like format.
-#
-# @param element_factory Optional element factory. This factory
-# is called to create new Element instances, as necessary.
-
-class TreeBuilder:
-
- def __init__(self, element_factory=None):
- self._data = [] # data collector
- self._elem = [] # element stack
- self._last = None # last element
- self._tail = None # true if we're after an end tag
- if element_factory is None:
- element_factory = _ElementInterface
- self._factory = element_factory
-
- ##
- # Flushes the parser buffers, and returns the toplevel documen
- # element.
- #
- # @return An Element instance.
- # @defreturn Element
-
- def close(self):
- assert len(self._elem) == 0, "missing end tags"
- assert self._last != None, "missing toplevel element"
- return self._last
-
- def _flush(self):
- if self._data:
- if self._last is not None:
- text = string.join(self._data, "")
- if self._tail:
- assert self._last.tail is None, "internal error (tail)"
- self._last.tail = text
- else:
- assert self._last.text is None, "internal error (text)"
- self._last.text = text
- self._data = []
-
- ##
- # Adds text to the current element.
- #
- # @param data A string. This should be either an 8-bit string
- # containing ASCII text, or a Unicode string.
-
- def data(self, data):
- self._data.append(data)
-
- ##
- # Opens a new element.
- #
- # @param tag The element name.
- # @param attrib A dictionary containing element attributes.
- # @return The opened element.
- # @defreturn Element
-
- def start(self, tag, attrs):
- self._flush()
- self._last = elem = self._factory(tag, attrs)
- if self._elem:
- self._elem[-1].append(elem)
- self._elem.append(elem)
- self._tail = 0
- return elem
-
- ##
- # Closes the current element.
- #
- # @param tag The element name.
- # @return The closed element.
- # @defreturn Element
-
- def end(self, tag):
- self._flush()
- self._last = self._elem.pop()
- assert self._last.tag == tag,\
- "end tag mismatch (expected %s, got %s)" % (
- self._last.tag, tag)
- self._tail = 1
- return self._last
-
-##
-# Element structure builder for XML source data, based on the
-# <b>expat</b> parser.
-#
-# @keyparam target Target object. If omitted, the builder uses an
-# instance of the standard {@link #TreeBuilder} class.
-# @keyparam html Predefine HTML entities. This flag is not supported
-# by the current implementation.
-# @see #ElementTree
-# @see #TreeBuilder
-
-class XMLTreeBuilder:
-
- def __init__(self, html=0, target=None):
- try:
- from xml.parsers import expat
- except ImportError:
- raise ImportError(
- "No module named expat; use SimpleXMLTreeBuilder instead"
- )
- self._parser = parser = expat.ParserCreate(None, "}")
- if target is None:
- target = TreeBuilder()
- self._target = target
- self._names = {} # name memo cache
- # callbacks
- parser.DefaultHandlerExpand = self._default
- parser.StartElementHandler = self._start
- parser.EndElementHandler = self._end
- parser.CharacterDataHandler = self._data
- # let expat do the buffering, if supported
- try:
- self._parser.buffer_text = 1
- except AttributeError:
- pass
- # use new-style attribute handling, if supported
- try:
- self._parser.ordered_attributes = 1
- self._parser.specified_attributes = 1
- parser.StartElementHandler = self._start_list
- except AttributeError:
- pass
- encoding = None
- if not parser.returns_unicode:
- encoding = "utf-8"
- # target.xml(encoding, None)
- self._doctype = None
- self.entity = {}
-
- def _fixtext(self, text):
- # convert text string to ascii, if possible
- try:
- return _encode(text, "ascii")
- except UnicodeError:
- return text
-
- def _fixname(self, key):
- # expand qname, and convert name string to ascii, if possible
- try:
- name = self._names[key]
- except KeyError:
- name = key
- if "}" in name:
- name = "{" + name
- self._names[key] = name = self._fixtext(name)
- return name
-
- def _start(self, tag, attrib_in):
- fixname = self._fixname
- tag = fixname(tag)
- attrib = {}
- for key, value in attrib_in.items():
- attrib[fixname(key)] = self._fixtext(value)
- return self._target.start(tag, attrib)
-
- def _start_list(self, tag, attrib_in):
- fixname = self._fixname
- tag = fixname(tag)
- attrib = {}
- if attrib_in:
- for i in range(0, len(attrib_in), 2):
- attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1])
- return self._target.start(tag, attrib)
-
- def _data(self, text):
- return self._target.data(self._fixtext(text))
-
- def _end(self, tag):
- return self._target.end(self._fixname(tag))
-
- def _default(self, text):
- prefix = text[:1]
- if prefix == "&":
- # deal with undefined entities
- try:
- self._target.data(self.entity[text[1:-1]])
- except KeyError:
- from xml.parsers import expat
- raise expat.error(
- "undefined entity %s: line %d, column %d" %
- (text, self._parser.ErrorLineNumber,
- self._parser.ErrorColumnNumber)
- )
- elif prefix == "<" and text[:9] == "<!DOCTYPE":
- self._doctype = [] # inside a doctype declaration
- elif self._doctype is not None:
- # parse doctype contents
- if prefix == ">":
- self._doctype = None
- return
- text = string.strip(text)
- if not text:
- return
- self._doctype.append(text)
- n = len(self._doctype)
- if n > 2:
- type = self._doctype[1]
- if type == "PUBLIC" and n == 4:
- name, type, pubid, system = self._doctype
- elif type == "SYSTEM" and n == 3:
- name, type, system = self._doctype
- pubid = None
- else:
- return
- if pubid:
- pubid = pubid[1:-1]
- self.doctype(name, pubid, system[1:-1])
- self._doctype = None
-
- ##
- # Handles a doctype declaration.
- #
- # @param name Doctype name.
- # @param pubid Public identifier.
- # @param system System identifier.
-
- def doctype(self, name, pubid, system):
- pass
-
- ##
- # Feeds data to the parser.
- #
- # @param data Encoded data.
-
- def feed(self, data):
- self._parser.Parse(data, 0)
-
- ##
- # Finishes feeding data to the parser.
- #
- # @return An element structure.
- # @defreturn Element
-
- def close(self):
- self._parser.Parse("", 1) # end of data
- tree = self._target.close()
- del self._target, self._parser # get rid of circular references
- return tree
}
display(G)
I=invert(G)
- print reachable(G,2)
- print reachable(I,6)
- print reachable(G,2) & reachable(I,6)
+ print(reachable(G,2))
+ print(reachable(I,6))
+ print(reachable(G,2) & reachable(I,6))
if __name__ == "__main__":
test()
import sys,os
try:
- import cElementTree as ElementTree
+ from xml.etree import cElementTree as ElementTree
except ImportError:
- import ElementTree
+ from xml.etree import ElementTree
#from sets import Set
Set=set
"""
tree = ElementTree.ElementTree(file=filename)
root = tree.getroot()
- if debug:print "root.tag:",root.tag,root
+ if debug:print("root.tag:",root.tag,root)
procs=[]
if root.tag == "dataflow":
#only one dataflow
dataflow=root
- if debug:print dataflow
+ if debug:print(dataflow)
proc=SalomeProc(dataflow)
procs.append(proc)
else:
#one or more dataflows. The graph contains macros.
#All macros are defined at the same level in the XML file.
for dataflow in root.findall("dataflow"):
- if debug:print dataflow
+ if debug:print(dataflow)
proc=SalomeProc(dataflow)
- if debug:print "dataflow name:",proc.name
+ if debug:print("dataflow name:",proc.name)
procs.append(proc)
return procs
#Put macros in macro_dict
macro_dict={}
for p in procs:
- if debug:print "proc_name:",p.name,"coupled_node:",p.coupled_node
+ if debug:print("proc_name:",p.name,"coupled_node:",p.coupled_node)
macro_dict[p.name]=p
- if debug:print filename
+ if debug:print(filename)
yacsproc=ProcNode(proc,macro_dict,filename)
return yacsproc.createNode()
n.setScript(self.codes[0])
self.node=n
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
n.edAddInputPort(para.name,typeMap[para.type])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
n.edAddOutputPort(para.name,typeMap[para.type])
return self.node
r = pilot.getRuntime()
- if self.container.components.has_key(self.sComponent):
+ if self.sComponent in self.container.components:
#a node for this component already exists
compo_node=self.container.components[self.sComponent]
#It's a node associated with another node of the same component instance
#add dataflow ports in out
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#Create the missing type and adds it into types table
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
n.edAddInputPort(para.name,typeMap[para.type])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#Create the missing type and adds it into types table
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
pout=n.edAddOutputPort(para.name,typeMap[para.type])
#add datastream ports in and out
for para in self.inStreams:
- if debug:print para.name,para.type,para.dependency,para.schema, para.interpolation,
- if debug:print para.extrapolation
+ if debug:print(para.name,para.type,para.dependency,para.schema, para.interpolation, end=' ')
+ if debug:print(para.extrapolation)
pin=n.edAddInputDataStreamPort(para.name,typeMap[streamTypes[para.type]])
for para in self.outStreams:
- if debug:print para.name,para.type,para.dependency,para.values
+ if debug:print(para.name,para.type,para.dependency,para.values)
pout=n.edAddOutputDataStreamPort(para.name,typeMap[streamTypes[para.type]])
for d in self.datas:
n.inner_nodes=loops[n]
n.G=graph.InducedSubgraph(loops[n],G)
- if debug:print "all loops"
- if debug:print loops
+ if debug:print("all loops")
+ if debug:print(loops)
#Get most external loops
- outer_loops=loops.keys()
+ outer_loops=list(loops.keys())
for l in loops:
for ll in outer_loops:
if loops[l] < loops[ll]:
break
#In the end all remaining loops in outer_loops are the most external
- if debug:print outer_loops
+ if debug:print(outer_loops)
#We remove all internal nodes of most external loops
for l in outer_loops:
#outcoming links of internal nodes. Probably not complete.
inputs={}
for link in l.endloop.links:
- if debug:print link.from_node,link.to_node,link.from_param,link.to_param
+ if debug:print(link.from_node,link.to_node,link.from_param,link.to_param)
inputs[link.to_param]=link.from_node,link.from_param
for s in suiv:
for link in s.links:
if link.from_node == l.endloop:
link.from_node,link.from_param=inputs[link.from_param]
- if debug:print link.from_node,link.to_node,link.from_param,link.to_param
+ if debug:print(link.from_node,link.to_node,link.from_param,link.to_param)
if debug:graph.display(G)
"""This method connects the salome macros in macro_dict to the master YACS Proc.
"""
- if debug:print "connect_macros",self.node,macro_dict
+ if debug:print("connect_macros",self.node,macro_dict)
for node in self.G:
if isinstance(node,MacroNode):
#node is a macro, connect its definition to self.
#node.node is the YACS Bloc equivalent to node
p=macro_dict[node.coupled_node]
bloc=node.node
- if debug:print "macronode:",node.name,node.coupled_node,p
+ if debug:print("macronode:",node.name,node.coupled_node,p)
#Create a hierarchical graph from the salome graph
G=p.create_graph()
node.G=G
init.setScript(self.codes[0])
init.setFname(self.fnames[0])
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
init.edAddInputPort(para.name,typeMap[para.type])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
init.edAddOutputPort(para.name,typeMap[para.type])
bloop.edAddChild(init)
next.setScript(self.codes[2])
next.setFname(self.fnames[2])
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
next.edAddInputPort(para.name,typeMap[para.type])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
next.edAddOutputPort(para.name,typeMap[para.type])
blnode.edAddChild(next)
more.setScript(self.codes[1])
more.setFname(self.fnames[1])
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
more.edAddInputPort(para.name,typeMap[para.type])
more.edAddOutputPort("DoLoop",typeMap["int"])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
more.edAddOutputPort(para.name,typeMap[para.type])
blnode.edAddChild(more)
currentProc.typeMap["CALCIUM_real"]=typeMap["CALCIUM_real"]
#create all containers
- for name,container in _containers.items():
+ for name,container in list(_containers.items()):
cont=r.createContainer()
cont.setName(name)
cont.setProperty("hostname",container.mach)
#each node has 2 lists of datastream links (inStreams, outStreams)
def parse(self,dataflow):
- if debug:print "All XML nodes"
+ if debug:print("All XML nodes")
for node in dataflow:
- if debug:print node.tag,node
+ if debug:print(node.tag,node)
#Parse dataflow info-list
self.dataflow_info=self.parseService(dataflow.find("info-list/node/service"))
- if debug:print self.dataflow_info
- if debug:print self.dataflow_info.inParameters
- if debug:print self.dataflow_info.outParameters
+ if debug:print(self.dataflow_info)
+ if debug:print(self.dataflow_info.inParameters)
+ if debug:print(self.dataflow_info.outParameters)
if debug:
for para in self.dataflow_info.inParameters:
- print "inParam:",para.name,para.name.split("__",1)
+ print("inParam:",para.name,para.name.split("__",1))
self.name=dataflow.findtext("info-list/node/node-name")
self.coupled_node=dataflow.findtext("info-list/node/coupled-node")
- if debug:print "All XML nodes dataflow/node-list"
+ if debug:print("All XML nodes dataflow/node-list")
nodes=[]
node_dict={}
#Parse all nodes
node.container= getContainer(container)
if not node.container:
node.container=addContainer(container)
- if debug:print "\tcontainer",node.container
+ if debug:print("\tcontainer",node.container)
elif kind == "3":
#It's a python function
node=MacroNode()
node.kind=10
else:
- raise UnknownKind,kind
+ raise UnknownKind(kind)
node.name=name
node.service=None
node.coupled_node=coupled_node
#Put nodes in a dict to ease search
node_dict[node.name]=node
- if debug:print "\tnode-name",node.name
- if debug:print "\tkind",node.kind,node.__class__.__name__
+ if debug:print("\tnode-name",node.name)
+ if debug:print("\tkind",node.kind,node.__class__.__name__)
s=n.find("service")
if s:
#Parse datastream ports
- if debug:print "DataStream ports"
+ if debug:print("DataStream ports")
inStreams=[]
for indata in n.findall("DataStream-list/inParameter"):
inStreams.append(self.parseInData(indata))
outStreams_dict[p.name]=p
node.outStreams=outStreams
node.outStreams_dict=outStreams_dict
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
nodes.append(node)
self.nodes=nodes
<coord-list/>
</link>
"""
- if debug:print "All XML nodes dataflow/link-list"
+ if debug:print("All XML nodes dataflow/link-list")
links=[]
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
for link in dataflow.findall('link-list/link'):
l=Link()
l.from_name=link.findtext("fromnode-name")
l.from_param=link.findtext("fromserviceparameter-name")
l.to_param=link.findtext("toserviceparameter-name")
links.append(l)
- if debug:print "\tfromnode-name",l.from_name
- if debug:print "\tfromserviceparameter-name",l.from_param
- if debug:print "\ttonode-name",l.to_name
- if debug:print "\ttoserviceparameter-name",l.to_param
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\tfromnode-name",l.from_name)
+ if debug:print("\tfromserviceparameter-name",l.from_param)
+ if debug:print("\ttonode-name",l.to_name)
+ if debug:print("\ttoserviceparameter-name",l.to_param)
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
self.links=links
- if debug:print "All XML nodes dataflow/data-list"
+ if debug:print("All XML nodes dataflow/data-list")
datas=[]
for data in dataflow.findall('data-list/data'):
d=self.parseData(data)
datas.append(d)
- if debug:print "\ttonode-name",d.tonode
- if debug:print "\ttoserviceparameter-name",d.tonodeparam
- if debug:print "\tparameter-value",d.value
- if debug:print "\tparameter-type",d.type
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\ttonode-name",d.tonode)
+ if debug:print("\ttoserviceparameter-name",d.tonodeparam)
+ if debug:print("\tparameter-value",d.value)
+ if debug:print("\tparameter-type",d.type)
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
self.datas=datas
def parseService(self,s):
service=Service()
service.name=s.findtext("service-name")
- if debug:print "\tservice-name",service.name
+ if debug:print("\tservice-name",service.name)
inParameters=[]
for inParam in s.findall("inParameter-list/inParameter"):
p=Parameter()
p.name=inParam.findtext("inParameter-name")
p.type=typeName(inParam.findtext("inParameter-type"))
- if debug:print "\tinParameter-name",p.name
- if debug:print "\tinParameter-type",p.type
+ if debug:print("\tinParameter-name",p.name)
+ if debug:print("\tinParameter-type",p.type)
inParameters.append(p)
service.inParameters=inParameters
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
outParameters=[]
for outParam in s.findall("outParameter-list/outParameter"):
p=Parameter()
p.name=outParam.findtext("outParameter-name")
p.type=typeName(outParam.findtext("outParameter-type"))
- if debug:print "\toutParameter-name",p.name
- if debug:print "\toutParameter-type",p.type
+ if debug:print("\toutParameter-name",p.name)
+ if debug:print("\toutParameter-type",p.type)
outParameters.append(p)
service.outParameters=outParameters
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
return service
def parseData(self,d):
return da
def parsePyFunction(self,pyfunc):
- if debug:print pyfunc.tag,":",pyfunc
- if debug:print "\tFuncName",pyfunc.findtext("FuncName")
+ if debug:print(pyfunc.tag,":",pyfunc)
+ if debug:print("\tFuncName",pyfunc.findtext("FuncName"))
text=""
for cdata in pyfunc.findall("PyFunc"):
if text:text=text+'\n'
"""
def parseInData(self,d):
- if debug:print d.tag,":",d
+ if debug:print(d.tag,":",d)
p=Parameter()
p.name=d.findtext("inParameter-name")
p.type=typeName(d.findtext("inParameter-type"))
p.schema=d.findtext("inParameter-schema")
p.interpolation=d.findtext("inParameter-interpolation")
p.extrapolation=d.findtext("inParameter-extrapolation")
- if debug:print "\tinParameter-name",p.name
+ if debug:print("\tinParameter-name",p.name)
return p
def parseOutData(self,d):
- if debug:print d.tag,":",d
+ if debug:print(d.tag,":",d)
p=Parameter()
p.name=d.findtext("outParameter-name")
p.type=typeName(d.findtext("outParameter-type"))
p.dependency=d.findtext("outParameter-dependency")
p.values=d.findtext("outParameter-values")
- if debug:print "\toutParameter-name",p.name
+ if debug:print("\toutParameter-name",p.name)
return p
def create_graph(self):
from_node=self.node_dict[link.from_name]
if link.from_param == "Gate" or link.to_param == "Gate":
#control link salome : add to_name node to neighbours
- if debug:print "add control link",link.from_name,link.to_name
+ if debug:print("add control link",link.from_name,link.to_name)
G[self.node_dict[link.from_name]].add(self.node_dict[link.to_name])
- elif from_node.outStreams_dict.has_key(link.from_param):
+ elif link.from_param in from_node.outStreams_dict:
# datastream link :
# 1- add link in link list
# 2- add in link references on from_node and to_node
- if debug:print "add stream link",link.from_name,link.to_name
+ if debug:print("add stream link",link.from_name,link.to_name)
self.node_dict[link.to_name].inStreamLinks.append(link)
self.node_dict[link.from_name].outStreamLinks.append(link)
link.from_node=self.node_dict[link.from_name]
if isinstance(to_node,LoopNode):
# If it's the link from EndOfLoop to Loop , we ignore it
if to_node.coupled_node == from_node.name:
- if debug:print "backlink loop:",from_node,to_node
+ if debug:print("backlink loop:",from_node,to_node)
#ignored
continue
- if debug:print "add dataflow link",link.from_name,link.to_name
+ if debug:print("add dataflow link",link.from_name,link.to_name)
G[self.node_dict[link.from_name]].add(self.node_dict[link.to_name])
if link.from_param != "DoLoop" and link.to_param != "DoLoop":
and isinstance(self.node_dict[link.to_name],InlineNode):
#Store the end loop inline node in attribute endloop
#self.node_dict[link.to_name] is the end node of the head loop node self.node_dict[link.from_name]
- if debug:print "add loop",link.from_name,link.to_name
+ if debug:print("add loop",link.from_name,link.to_name)
self.node_dict[link.from_name].endloop=self.node_dict[link.to_name]
self.node_dict[link.to_name].loop=self.node_dict[link.from_name]
for data in self.datas:
- if debug:print "datas",data
+ if debug:print("datas",data)
self.node_dict[data.tonode].datas.append(data)
self.G=G
salomeFile=sys.argv[1]
convertedFile=sys.argv[2]
except :
- print usage%(sys.argv[0])
+ print(usage%(sys.argv[0]))
sys.exit(3)
SALOMERuntime.RuntimeSALOME_setRuntime()
logger=p.getLogger("parser")
if not logger.isEmpty():
- print logger.getStr()
+ print(logger.getStr())
sys.exit(1)
if __name__ == "__main__":
<service>
<service-name>GeomGraph</service-name>
<inParameter-list>
-<inParameter>
-<inParameter-type>long</inParameter-type>
- <inParameter-name>SetStudyID__theStudyID</inParameter-name> </inParameter>
<inParameter>
<inParameter-type>double</inParameter-type>
<inParameter-name>MakeBox__theX1</inParameter-name> </inParameter>
<x-position>0</x-position>
<y-position>0</y-position> </node> </info-list>
<node-list>
-<node>
-<component-name>GEOM_Superv</component-name>
- <interface-name>GEOM_Superv</interface-name>
- <node-name>SetStudyID</node-name>
- <kind>0</kind>
- <coupled-node>?</coupled-node>
- <service>
-<service-name>SetStudyID</service-name>
- <inParameter-list>
-<inParameter>
-<inParameter-type>long</inParameter-type>
- <inParameter-name>theStudyID</inParameter-name> </inParameter> </inParameter-list>
- <outParameter-list/> </service>
- <DataStream-list/>
- <PyFunction-list/>
- <creation-date>6/6/2005 - 10:39:55</creation-date>
- <lastmodification-date>6/6/2005 - 10:39:55</lastmodification-date>
- <editor-release>2.0</editor-release>
- <author>?</author>
- <container>localhost/FactoryServer</container>
- <comment>SetStudyID from GEOM_Superv</comment>
- <x-position>14</x-position>
- <y-position>241</y-position> </node>
+
<node>
<component-name>GEOM_Superv</component-name>
<interface-name>GEOM_Superv</interface-name>
<x-position>993</x-position>
<y-position>312</y-position> </node> </node-list>
<link-list>
-<link>
-<fromnode-name>SetStudyID</fromnode-name>
- <fromserviceparameter-name>Gate</fromserviceparameter-name>
- <tonode-name>MakeBox</tonode-name>
- <toserviceparameter-name>Gate</toserviceparameter-name>
- <coord-list/> </link>
- <link>
-<fromnode-name>SetStudyID</fromnode-name>
- <fromserviceparameter-name>Gate</fromserviceparameter-name>
- <tonode-name>MakeSphere_1</tonode-name>
- <toserviceparameter-name>Gate</toserviceparameter-name>
- <coord-list/> </link>
<link>
<fromnode-name>MakeBox</fromnode-name>
<fromserviceparameter-name>return</fromserviceparameter-name>
<toserviceparameter-name>theShape1</toserviceparameter-name>
<coord-list/> </link> </link-list>
<data-list>
-<data>
-<fromnode-name>GeomGraph</fromnode-name>
- <fromserviceparameter-name>SetStudyID__theStudyID</fromserviceparameter-name>
- <tonode-name>SetStudyID</tonode-name>
- <toserviceparameter-name>theStudyID</toserviceparameter-name>
- <data-value>
-<value-type>3</value-type>
- <value>1</value> </data-value>
- <coord-list/> </data>
<data>
<fromnode-name>GeomGraph</fromnode-name>
<fromserviceparameter-name>MakeBox__theX1</fromserviceparameter-name>
<service>
<service-name>GeomGraph</service-name>
<inParameter-list>
- <inParameter>
- <inParameter-type>long</inParameter-type>
- <inParameter-name>SetStudyID__theStudyID</inParameter-name>
- </inParameter>
<inParameter>
<inParameter-type>double</inParameter-type>
<inParameter-name>MakeBox__theX1</inParameter-name>
</node>
</info-list>
<node-list>
- <node>
- <component-name>GEOM_Superv</component-name>
- <interface-name>GEOM_Superv</interface-name>
- <node-name>SetStudyID</node-name>
- <kind>0</kind>
- <coupled-node>?</coupled-node>
- <service>
- <service-name>SetStudyID</service-name>
- <inParameter-list>
- <inParameter>
- <inParameter-type>long</inParameter-type>
- <inParameter-name>theStudyID</inParameter-name>
- </inParameter>
- </inParameter-list>
- <outParameter-list/>
- </service>
- <DataStream-list/>
- <PyFunction-list/>
- <creation-date>14/12/2005 - 14:39:18</creation-date>
- <lastmodification-date>14/12/2005 - 14:39:18</lastmodification-date>
- <editor-release>2.0</editor-release>
- <author>?</author>
- <container>localhost/FactoryServer</container>
- <comment>SetStudyID from GEOM_Superv</comment>
- <x-position>14</x-position>
- <y-position>241</y-position>
- </node>
<node>
<component-name>GEOM_Superv</component-name>
<interface-name>GEOM_Superv</interface-name>
</node>
</node-list>
<link-list>
- <link>
- <fromnode-name>SetStudyID</fromnode-name>
- <fromserviceparameter-name>Gate</fromserviceparameter-name>
- <tonode-name>MakeBox</tonode-name>
- <toserviceparameter-name>Gate</toserviceparameter-name>
- <coord-list/>
- </link>
<link>
<fromnode-name>MakeBox</fromnode-name>
<fromserviceparameter-name>return</fromserviceparameter-name>
</link>
</link-list>
<data-list>
- <data>
- <fromnode-name>GeomGraph</fromnode-name>
- <fromserviceparameter-name>SetStudyID__theStudyID</fromserviceparameter-name>
- <tonode-name>SetStudyID</tonode-name>
- <toserviceparameter-name>theStudyID</toserviceparameter-name>
- <data-value>
- <value-type>3</value-type>
- <value>1</value>
- </data-value>
- <coord-list/>
- </data>
<data>
<fromnode-name>GeomGraph</fromnode-name>
<fromserviceparameter-name>MakeBox__theX1</fromserviceparameter-name>
<PyFunc><![CDATA[ shape = MakeBoolean(shape1,shape2,3) ]]></PyFunc>
<PyFunc><![CDATA[ from SALOME_NamingServicePy import SALOME_NamingServicePy_i ]]></PyFunc>
<PyFunc><![CDATA[ myNamingService = SALOME_NamingServicePy_i(orb) ]]></PyFunc>
- <PyFunc><![CDATA[ aSession = myNamingService.Resolve('/Kernel/Session') ]]></PyFunc>
- <PyFunc><![CDATA[ aStudyId = aSession.GetActiveStudyId() ]]></PyFunc>
- <PyFunc><![CDATA[ myStudyManager = myNamingService.Resolve('/myStudyManager') ]]></PyFunc>
- <PyFunc><![CDATA[ aStudy = myStudyManager.GetStudyByID(aStudyId) ]]></PyFunc>
+ <PyFunc><![CDATA[ aStudy = myNamingService.Resolve('/Study') ]]</PyFunc>
<PyFunc><![CDATA[ aSObject = geom.AddInStudy(aStudy, shape, "shape", None) ]]></PyFunc>
<PyFunc><![CDATA[ return shape ]]></PyFunc>
</PyFunction>
<PyFunc><![CDATA[ # fuse operation 3 ]]></PyFunc>
<PyFunc><![CDATA[ shape = MakeBoolean(shape1,shape2,3) ]]></PyFunc>
<PyFunc><![CDATA[ myNamingService = SALOME_NamingServicePy_i(orb) ]]></PyFunc>
- <PyFunc><![CDATA[ aSession = myNamingService.Resolve('/Kernel/Session') ]]></PyFunc>
- <PyFunc><![CDATA[ if aSession == None : ]]></PyFunc>
- <PyFunc><![CDATA[ aStudyId = 1 ]]></PyFunc>
- <PyFunc><![CDATA[ else : ]]></PyFunc>
- <PyFunc><![CDATA[ aStudyId = aSession.GetActiveStudyId() ]]></PyFunc>
- <PyFunc><![CDATA[ myStudyManager = myNamingService.Resolve('/myStudyManager') ]]></PyFunc>
- <PyFunc><![CDATA[ aStudy = myStudyManager.GetStudyByID(aStudyId) ]]></PyFunc>
+ <PyFunc><![CDATA[ aStudy = myNamingService.Resolve('/Study') ]]</PyFunc>
<PyFunc><![CDATA[ aSObject = geom.AddInStudy(aStudy, shape, "shape", None) ]]></PyFunc>
<PyFunc><![CDATA[ return shape ]]></PyFunc> </PyFunction> </PyFunction-list>
<creation-date>29/10/2004 - 10:50:25</creation-date>
<PyFunc><![CDATA[ index = min ]]></PyFunc>
<PyFunc><![CDATA[ else : ]]></PyFunc>
<PyFunc><![CDATA[ index = max ]]></PyFunc>
- <PyFunc><![CDATA[ print "Init :" ]]></PyFunc>
- <PyFunc><![CDATA[ print index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
+ <PyFunc><![CDATA[ print("Init :") ]]></PyFunc>
+ <PyFunc><![CDATA[ print(index,min,max,couronne,Rcouronne,Rsphere) ]]></PyFunc>
<PyFunc><![CDATA[ couronne.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
<PyFunc><![CDATA[?]]></PyFunc>
<PyFunc><![CDATA[ OutLoop = 0 ]]></PyFunc>
<PyFunc><![CDATA[ if max > index : ]]></PyFunc>
<PyFunc><![CDATA[ OutLoop = 1 ]]></PyFunc>
- <PyFunc><![CDATA[ print "More :" ]]></PyFunc>
- <PyFunc><![CDATA[ print OutLoop,index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
+ <PyFunc><![CDATA[ print("More :") ]]></PyFunc>
+ <PyFunc><![CDATA[ print(OutLoop,index,min,max,couronne,Rcouronne,Rsphere) ]]></PyFunc>
<PyFunc><![CDATA[ couronne.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return OutLoop,index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
<PyFunc><![CDATA[?]]></PyFunc>
<FuncName>Next</FuncName>
<PyFunc><![CDATA[def Next(index,min,max,couronne,Rcouronne,Rsphere): ]]></PyFunc>
<PyFunc><![CDATA[ index = index + 1 ]]></PyFunc>
- <PyFunc><![CDATA[ print "Next :" ]]></PyFunc>
- <PyFunc><![CDATA[ print index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
+ <PyFunc><![CDATA[ print("Next :") ]]></PyFunc>
+ <PyFunc><![CDATA[ print(index,min,max,couronne,Rcouronne,Rsphere) ]]></PyFunc>
<PyFunc><![CDATA[ couronne.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
<PyFunc><![CDATA[?]]></PyFunc>
<PyFunc><![CDATA[ lcc = LifeCycleCORBA(orb) ]]></PyFunc>
<PyFunc><![CDATA[ # --- create a naming service instance ]]></PyFunc>
<PyFunc><![CDATA[ naming_service = SALOME_NamingServicePy_i(orb) ]]></PyFunc>
- <PyFunc><![CDATA[ # --- get Study Manager reference ]]></PyFunc>
- <PyFunc><![CDATA[ obj = naming_service.Resolve('myStudyManager') ]]></PyFunc>
- <PyFunc><![CDATA[ StudyManager = obj._narrow(SALOMEDS.StudyManager) ]]></PyFunc>
<PyFunc><![CDATA[ # --- load visu component ]]></PyFunc>
<PyFunc><![CDATA[ aVisu = lcc.FindOrLoadComponent("FactoryServer","VISU") ]]></PyFunc>
- <PyFunc><![CDATA[ aStudy = StudyManager.GetStudyByID(1) ]]></PyFunc>
- <PyFunc><![CDATA[ aVisu.SetCurrentStudy(aStudy) ]]></PyFunc>
- <PyFunc><![CDATA[ print "InitDisplay --> aVisu ", aVisu ]]></PyFunc>
+ <PyFunc><![CDATA[ print("InitDisplay --> aVisu ", aVisu) ]]></PyFunc>
<PyFunc><![CDATA[ time.sleep(2) ]]></PyFunc>
<PyFunc><![CDATA[ aViewManager=aVisu.GetViewManager() ]]></PyFunc>
- <PyFunc><![CDATA[ print "InitDisplay --> aViewManager ", aViewManager ]]></PyFunc>
+ <PyFunc><![CDATA[ print("InitDisplay --> aViewManager ", aViewManager) ]]></PyFunc>
<PyFunc><![CDATA[ #time.sleep(2) ]]></PyFunc>
<PyFunc><![CDATA[ #aView=aViewManager.GetCurrentView() ]]></PyFunc>
<PyFunc><![CDATA[ aView=aViewManager.Create3DView() ]]></PyFunc>
- <PyFunc><![CDATA[ print "InitDisplay --> aView ", aView ]]></PyFunc>
+ <PyFunc><![CDATA[ print("InitDisplay --> aView ", aView) ]]></PyFunc>
<PyFunc><![CDATA[ #time.sleep(2) ]]></PyFunc>
<PyFunc><![CDATA[ medFile = "TimeStamps.med" ]]></PyFunc>
<PyFunc><![CDATA[ medFile = os.getenv('DATA_DIR') + '/MedFiles/' + medFile ]]></PyFunc>
<PyFunc><![CDATA[ myResult = aVisu.ImportFile(medFile) ]]></PyFunc>
- <PyFunc><![CDATA[ print "InitDisplay --> myResult ", myResult ]]></PyFunc>
+ <PyFunc><![CDATA[ print("InitDisplay --> myResult ", myResult) ]]></PyFunc>
<PyFunc><![CDATA[ return aVisu,aView,myResult ]]></PyFunc>
</PyFunction> </PyFunction-list>
<creation-date>8/4/2005 - 14:3:47</creation-date>
<PyFunc><![CDATA[ index = min ]]></PyFunc>
<PyFunc><![CDATA[ else : ]]></PyFunc>
<PyFunc><![CDATA[ index = max ]]></PyFunc>
- <PyFunc><![CDATA[ print "---- Init ",index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc>
+ <PyFunc><![CDATA[ print("---- Init ",index,min,max,aVisu,aView,myResult,x1) ]]></PyFunc>
<PyFunc><![CDATA[ aView.Register() ]]></PyFunc>
<PyFunc><![CDATA[ myResult.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc> </PyFunction>
<PyFunc><![CDATA[ DoLoop = 1 ]]></PyFunc>
<PyFunc><![CDATA[ else : ]]></PyFunc>
<PyFunc><![CDATA[ DoLoop = 0 ]]></PyFunc>
- <PyFunc><![CDATA[ print "---- More",index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc>
+ <PyFunc><![CDATA[ print("---- More",index,min,max,aVisu,aView,myResult,x1) ]]></PyFunc>
<PyFunc><![CDATA[ aView.Register() ]]></PyFunc>
<PyFunc><![CDATA[ myResult.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return DoLoop,index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc> </PyFunction>
<PyFunc><![CDATA[def Next(index,min,max,aVisu,aView,myResult,x1): ]]></PyFunc>
<PyFunc><![CDATA[ index = index + 1 ]]></PyFunc>
<PyFunc><![CDATA[ x1=x1+1.0 ]]></PyFunc>
- <PyFunc><![CDATA[ print "---- Next",index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc>
+ <PyFunc><![CDATA[ print("---- Next",index,min,max,aVisu,aView,myResult,x1) ]]></PyFunc>
<PyFunc><![CDATA[ aView.Register() ]]></PyFunc>
<PyFunc><![CDATA[ myResult.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc> </PyFunction> </PyFunction-list>
<PyFunc><![CDATA[import os ]]></PyFunc>
<PyFunc><![CDATA[import time ]]></PyFunc>
<PyFunc><![CDATA[def DisplayVitesse(index,aVisu,aView,aResult,x1): ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 1 index = ", index,aVisu,aView,aResult,x1 ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 1 index = ", index,aVisu,aView,aResult,x1) ]]></PyFunc>
<PyFunc><![CDATA[ aMeshName ="dom" ]]></PyFunc>
<PyFunc><![CDATA[ myFieldName = "vitesse" ]]></PyFunc>
<PyFunc><![CDATA[ anEntity = VISU.NODE ]]></PyFunc>
<PyFunc><![CDATA[ aMesh = aVisu.MeshOnEntity(aResult, aMeshName, anEntity) ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 2 ", aMesh ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 2 ", aMesh) ]]></PyFunc>
<PyFunc><![CDATA[ x1=int(x1) ]]></PyFunc>
<PyFunc><![CDATA[ aScalarMap=aVisu.ScalarMapOnField(aResult,aMeshName,anEntity,myFieldName,x1) ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 4" ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 4") ]]></PyFunc>
<PyFunc><![CDATA[ if aScalarMap is not None: ]]></PyFunc>
<PyFunc><![CDATA[ aScalarMap.SetScaling(VISU.LINEAR) ]]></PyFunc>
<PyFunc><![CDATA[ else: ]]></PyFunc>
- <PyFunc><![CDATA[ print "Null scalar map is created" ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 5" ]]></PyFunc>
+ <PyFunc><![CDATA[ print("Null scalar map is created") ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 5") ]]></PyFunc>
<PyFunc><![CDATA[ aView.DisplayOnly(aScalarMap) ]]></PyFunc>
<PyFunc><![CDATA[ aView.FitAll() ]]></PyFunc>
<PyFunc><![CDATA[ aView.Update() ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 6" ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 6") ]]></PyFunc>
<PyFunc><![CDATA[ theResult=aResult ]]></PyFunc>
<PyFunc><![CDATA[ #time.sleep(2) ]]></PyFunc>
<PyFunc><![CDATA[ theResult.Register() ]]></PyFunc>
p.saveSchema("tata.xml")
U = os.getenv('USER')
-f=open("/tmp/" + U + "/UnitTestsResult", 'a')
-f.write(" --- TEST src/salomeloader: testSalomeLoader.py\n")
-suite = unittest.makeSuite(TestSalomeLoader)
-result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
-f.close()
+with open("/tmp/" + U + "/UnitTestsResult", 'a') as f:
+ f.write(" --- TEST src/salomeloader: testSalomeLoader.py\n")
+ suite = unittest.makeSuite(TestSalomeLoader)
+ result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
sys.exit(not result.wasSuccessful())
return aView;
}
-int SalomeWrap_Module::AssociateViewToWindow(QGraphicsView* gView,
+void SalomeWrap_Module::AssociateViewToWindow(QGraphicsView* gView,
QxScene_ViewWindow* viewWindow)
{
viewWindow->setSceneView(gView);
viewWindow->setCentralWidget(gView);
- return viewWindow->getViewManager()->study()->id();
-}
-
-int SalomeWrap_Module::activeStudyId()
-{
- return getApp()->activeStudy()->id();
}
QDockWidget* SalomeWrap_Module::objectBrowser() {
QxScene_ViewWindow* getNewWindow(QGraphicsScene *scene);
- int AssociateViewToWindow(QGraphicsView* gView,
+ void AssociateViewToWindow(QGraphicsView* gView,
QxScene_ViewWindow* viewWindow);
- int activeStudyId();
-
QDockWidget* objectBrowser();
QAction* wCreateAction(const int id,
return module->getNewWindow(scene);
}
-/*!
- * return studyId used in context delete when study is closed.
- */
-int SuitWrapper::AssociateViewToWindow(QGraphicsView* gView, QWidget* viewWindow)
+void SuitWrapper::AssociateViewToWindow(QGraphicsView* gView, QWidget* viewWindow)
{
SalomeWrap_Module* module = dynamic_cast<SalomeWrap_Module*>(_wrapped);
QxScene_ViewWindow *svw = dynamic_cast<QxScene_ViewWindow*>(viewWindow);
YASSERT(svw);
- int studyId = module->AssociateViewToWindow(gView, svw);
+ module->AssociateViewToWindow(gView, svw);
WrapGraphicsView* wgv = dynamic_cast<WrapGraphicsView*>(gView);
YASSERT(wgv);
QObject::disconnect(svw->toolMgr()->action(QxScene_ViewWindow::FitAllId),
QObject::connect(svw->toolMgr()->action(QxScene_ViewWindow::ResetId),
SIGNAL(triggered(bool)),
wgv, SLOT(onViewReset()));
- return studyId;
-}
-
-int SuitWrapper::activeStudyId()
-{
- SalomeWrap_Module* module = dynamic_cast<SalomeWrap_Module*>(_wrapped);
- return module->activeStudyId();
}
QDockWidget* SuitWrapper::objectBrowser()
virtual ~SuitWrapper();
QWidget* getNewWindow(QGraphicsScene *scene);
- int AssociateViewToWindow(QGraphicsView* gView, QWidget* viewWindow);
- int activeStudyId();
+ void AssociateViewToWindow(QGraphicsView* gView, QWidget* viewWindow);
+
QDockWidget* objectBrowser();
QAction* createAction(const int id,
AC_MSG_CHECKING(python extra libraries)
PYTHON_EXTRA_LIBS=`$PYTHON -c "import distutils.sysconfig; \
conf = distutils.sysconfig.get_config_var; \
- print conf('LOCALMODLIBS')+' '+conf('LIBS')"
+ print(conf('LOCALMODLIBS')+' '+conf('LIBS'))"
AC_MSG_RESULT($PYTHON_EXTRA_LIBS)`
AC_SUBST(PYTHON_EXTRA_LIBS)
])
AC_SUBST(PYTHONHOME)
changequote(<<, >>)dnl
- PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"`
+ PYTHON_VERSION=`$PYTHON -c "import sys; print(sys.version[:3])"`
changequote([, ])dnl
AC_SUBST(PYTHON_VERSION)
dnl to know which OS Python thinks this is.
AC_SUBST(PYTHON_PLATFORM)
- PYTHON_PLATFORM=`$PYTHON -c "import sys; print sys.platform"`
+ PYTHON_PLATFORM=`$PYTHON -c "import sys; print(sys.platform)"`
AC_SUBST(PYTHON_SITE)
AC_ARG_WITH(python-site,
class Cpp_Template_
{
-// Méthodes publiques
+// Méthodes publiques
public:
Cpp_Template_();
MEDMEM::FIELD<double>* createField();
pass
#
#
-print "Test Program of Cpp_Template_ component"
+print("Test Program of Cpp_Template_ component")
# ...
AC_MSG_CHECKING(python extra libraries)
PYTHON_EXTRA_LIBS=`$PYTHON -c "import distutils.sysconfig; \
conf = distutils.sysconfig.get_config_var; \
- print conf('LOCALMODLIBS')+' '+conf('LIBS')"
+ print(conf('LOCALMODLIBS')+' '+conf('LIBS'))"
AC_MSG_RESULT($PYTHON_EXTRA_LIBS)`
AC_SUBST(PYTHON_EXTRA_LIBS)
])
[command line options] :
--help : affichage de l'aide
--gui : lancement du GUI
---logger : redirection des messages dans un fichier
---xterm : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre
---modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue
+--logger : redirection des messages dans un fichier
+--xterm : les serveurs ouvrent une fen??tre xterm et les messages sont affich??s dans cette fen??tre
+--modules=module1,module2,... : o?? modulen est le nom d'un module Salome ?? charger dans le catalogue
--containers=cpp,python,superv: lancement des containers cpp, python et de supervision
---killall : arrêt des serveurs de salome
+--killall : arr??t des serveurs de salome
- La variable d'environnement <modulen>_ROOT_DIR doit etre préalablement
- positionnée (modulen doit etre en majuscule).
+ La variable d'environnement <modulen>_ROOT_DIR doit etre pr??alablement
+ positionn??e (modulen doit etre en majuscule).
KERNEL_ROOT_DIR est obligatoire.
"""
# -----------------------------------------------------------------------------
#
-# Fonction d'arrêt de salome
+# Fonction d'arr??t de salome
#
def killSalome():
- print "arret des serveurs SALOME"
- for pid, cmd in process_id.items():
- print "arret du process %s : %s"% (pid, cmd[0])
- try:
- os.kill(pid,signal.SIGKILL)
- except:
- print " ------------------ process %s : %s inexistant"% (pid, cmd[0])
- print "arret du naming service"
- os.system("killall -9 omniNames")
-
+ print("arret des serveurs SALOME")
+ for pid, cmd in list(process_id.items()):
+ print("arret du process %s : %s"% (pid, cmd[0]))
+ try:
+ os.kill(pid,signal.SIGKILL)
+ except:
+ print(" ------------------ process %s : %s inexistant"% (pid, cmd[0]))
+ print("arret du naming service")
+ os.system("killall -9 omniNames")
+
# -----------------------------------------------------------------------------
#
# Fonction message
#
def message(code, msg=''):
- if msg: print msg
+ if msg: print(msg)
sys.exit(code)
import sys,os,string,glob,time,signal,pickle,getopt
with_container_superv=0
try:
- for o, a in opts:
- if o in ('-h', '--help'):
- print usage
- sys.exit(1)
- elif o in ('-g', '--gui'):
- with_gui=1
- elif o in ('-l', '--logger'):
- with_logger=1
- elif o in ('-x', '--xterm'):
- with_xterm=1
- elif o in ('-m', '--modules'):
- liste_modules = [x.upper() for x in a.split(',')]
- elif o in ('-c', '--containers'):
- liste_containers = [x.lower() for x in a.split(',')]
- for r in liste_containers:
- if r not in ('cpp', 'python', 'superv'):
- message(1, 'Invalid -c/--containers option: %s' % a)
- if 'cpp' in liste_containers:
- with_container_cpp=1
- else:
- with_container_cpp=0
- if 'python' in liste_containers:
- with_container_python=1
- else:
- with_container_python=0
- if 'superv' in liste_containers:
- with_container_superv=1
- else:
- with_container_superv=0
- elif o in ('-k', '--killall'):
- filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
- #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
- found = 0
- try:
- fpid=open(filedict, 'r')
- found = 1
- except:
- print "le fichier %s des process SALOME n'est pas accessible"% filedict
-
- if found:
- process_id=pickle.load(fpid)
- fpid.close()
- killSalome()
- process_id={}
- os.remove(filedict)
-
-except getopt.error, msg:
- print usage
- sys.exit(1)
+ for o, a in opts:
+ if o in ('-h', '--help'):
+ print(usage)
+ sys.exit(1)
+ elif o in ('-g', '--gui'):
+ with_gui=1
+ elif o in ('-l', '--logger'):
+ with_logger=1
+ elif o in ('-x', '--xterm'):
+ with_xterm=1
+ elif o in ('-m', '--modules'):
+ liste_modules = [x.upper() for x in a.split(',')]
+ elif o in ('-c', '--containers'):
+ liste_containers = [x.lower() for x in a.split(',')]
+ for r in liste_containers:
+ if r not in ('cpp', 'python', 'superv'):
+ message(1, 'Invalid -c/--containers option: %s' % a)
+ if 'cpp' in liste_containers:
+ with_container_cpp=1
+ else:
+ with_container_cpp=0
+ if 'python' in liste_containers:
+ with_container_python=1
+ else:
+ with_container_python=0
+ if 'superv' in liste_containers:
+ with_container_superv=1
+ else:
+ with_container_superv=0
+ elif o in ('-k', '--killall'):
+ filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
+ #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
+ found = 0
+ try:
+ fpid=open(filedict, 'r')
+ found = 1
+ except:
+ print("le fichier %s des process SALOME n'est pas accessible"% filedict)
+
+ if found:
+ process_id=pickle.load(fpid)
+ fpid.close()
+ killSalome()
+ process_id={}
+ os.remove(filedict)
+
+except getopt.error as msg:
+ print(usage)
+ sys.exit(1)
# -----------------------------------------------------------------------------
#
-# Vérification des variables d'environnement
+# V??rification des variables d'environnement
#
try:
- kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
- modules_root_dir["KERNEL"]=kernel_root_dir
+ kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
+ modules_root_dir["KERNEL"]=kernel_root_dir
except:
- print usage
- sys.exit(1)
+ print(usage)
+ sys.exit(1)
for module in liste_modules :
- try:
- module=module.upper()
- module_root_dir=os.environ[module +"_ROOT_DIR"]
- modules_root_dir[module]=module_root_dir
- except:
- print usage
- sys.exit(1)
+ try:
+ module=module.upper()
+ module_root_dir=os.environ[module +"_ROOT_DIR"]
+ modules_root_dir[module]=module_root_dir
+ except:
+ print(usage)
+ sys.exit(1)
# il faut KERNEL en premier dans la liste des modules
# - l'ordre des modules dans le catalogue sera identique
-# - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python,
+# - la liste des modules presents dans le catalogue est exploit??e pour charger les modules CORBA python,
# il faut charger les modules python du KERNEL en premier
if "KERNEL" in liste_modules:liste_modules.remove("KERNEL")
#print liste_modules
#print modules_root_dir
-os.environ["SALOMEPATH"]=":".join(modules_root_dir.values())
+os.environ["SALOMEPATH"]=":".join(list(modules_root_dir.values()))
if "SUPERV" in liste_modules:with_container_superv=1
# -----------------------------------------------------------------------------
#
-# Définition des classes d'objets pour le lancement des Server CORBA
+# D??finition des classes d'objets pour le lancement des Server CORBA
#
class Server:
- CMD=[]
- if with_xterm:
- ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
- else:
- ARGS=[]
-
- def run(self):
- args = self.ARGS+self.CMD
- #print "args = ", args
- pid = os.spawnvp(os.P_NOWAIT, args[0], args)
- process_id[pid]=self.CMD
+ CMD=[]
+ if with_xterm:
+ ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
+ else:
+ ARGS=[]
+
+ def run(self):
+ args = self.ARGS+self.CMD
+ #print "args = ", args
+ pid = os.spawnvp(os.P_NOWAIT, args[0], args)
+ process_id[pid]=self.CMD
class CatalogServer(Server):
- SCMD1=['SALOME_ModuleCatalog_Server','-common']
- SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml']
-
- def setpath(self,liste_modules):
- cata_path=[]
- for module in liste_modules:
- module_root_dir=modules_root_dir[module]
- module_cata=module+"Catalog.xml"
- print " ", module_cata
- cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
- self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+ SCMD1=['SALOME_ModuleCatalog_Server','-common']
+ SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml']
+
+ def setpath(self,liste_modules):
+ cata_path=[]
+ for module in liste_modules:
+ module_root_dir=modules_root_dir[module]
+ module_cata=module+"Catalog.xml"
+ print(" ", module_cata)
+ cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
+ self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
class SalomeDSServer(Server):
- CMD=['SALOMEDS_Server']
+ CMD=['SALOMEDS_Server']
class RegistryServer(Server):
- CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+ CMD=['SALOME_Registry_Server', '--salome_session','theSession']
class ContainerCPPServer(Server):
- CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
class ContainerPYServer(Server):
- CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
class ContainerSUPERVServer(Server):
- CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
class LoggerServer(Server):
- CMD=['SALOME_Logger_Server', 'logger.log']
+ CMD=['SALOME_Logger_Server', 'logger.log']
class SessionLoader(Server):
- CMD=['SALOME_Session_Loader']
- if with_container_cpp:
- CMD=CMD+['CPP']
- if with_container_python:
- CMD=CMD+['PY']
- if with_container_superv:
- CMD=CMD+['SUPERV']
- if with_gui:
- CMD=CMD+['GUI']
+ CMD=['SALOME_Session_Loader']
+ if with_container_cpp:
+ CMD=CMD+['CPP']
+ if with_container_python:
+ CMD=CMD+['PY']
+ if with_container_superv:
+ CMD=CMD+['SUPERV']
+ if with_gui:
+ CMD=CMD+['GUI']
class SessionServer(Server):
- CMD=['SALOME_Session_Server']
+ CMD=['SALOME_Session_Server']
class NotifyServer(Server):
- CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
+ CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
# -----------------------------------------------------------------------------
#
#
def test(clt):
- """
- Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
- usage : hello=test(clt)
- """
- # create an LifeCycleCORBA instance
- import LifeCycleCORBA
- lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
- import HXX2SALOME_GENERIC_CLASS_NAME_ORB
- hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
- return hello
+ """
+ Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
+ usage : hello=test(clt)
+ """
+ # create an LifeCycleCORBA instance
+ import LifeCycleCORBA
+ lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
+ import HXX2SALOME_GENERIC_CLASS_NAME_ORB
+ hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
+ return hello
# -----------------------------------------------------------------------------
#
#
def add_path(directory):
- os.environ["PATH"]=directory + ":" + os.environ["PATH"]
+ os.environ["PATH"]=directory + ":" + os.environ["PATH"]
def add_ld_library_path(directory):
- os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
+ os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
def add_python_path(directory):
- os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
- sys.path[:0]=[directory]
+ os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
+ sys.path[:0]=[directory]
# -----------------------------------------------------------------------------
#
#
def startGUI():
- import SALOME
- session=clt.waitNS("/Kernel/Session",SALOME.Session)
+ import SALOME
+ session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+ #
+ # Activation du GUI de Session Server
+ #
+
+ session.GetInterface()
- #
- # Activation du GUI de Session Server
- #
-
- session.GetInterface()
-
#
# -----------------------------------------------------------------------------
#
def startSalome():
- #
- # Lancement Session Loader
- #
- SessionLoader().run()
-
- #
- # Initialisation ORB et Naming Service
- #
- clt=orbmodule.client()
-
- # (non obligatoire) Lancement Logger Server et attente de sa
- # disponibilite dans le naming service
- #
- if with_logger:
- LoggerServer().run()
- clt.waitLogger("Logger")
-
- #
- # Lancement Registry Server
- #
- RegistryServer().run()
-
- #
- # Attente de la disponibilité du Registry dans le Naming Service
- #
- clt.waitNS("/Registry")
-
- #
- # Lancement Catalog Server
- #
- cataServer=CatalogServer()
- cataServer.setpath(liste_modules)
- cataServer.run()
-
- #
- # Attente de la disponibilité du Catalog Server dans le Naming Service
- #
- import SALOME_ModuleCatalog
- clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
-
- #
- # Lancement SalomeDS Server
- #
- os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
- os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
- SalomeDSServer().run()
-
- if "GEOM" in liste_modules:
- print "GEOM OCAF Resources"
- os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
-
-
- #
- # Attente de la disponibilité du SalomeDS dans le Naming Service
- #
- clt.waitNS("/myStudyManager")
-
- #
- # Lancement Session Server
- #
- SessionServer().run()
-
- #
- # Attente de la disponibilité du Session Server dans le Naming Service
- #
- import SALOME
- session=clt.waitNS("/Kernel/Session",SALOME.Session)
-
- #
- # Lancement containers
- #
- theComputer = os.getenv("HOSTNAME")
- theComputer = theComputer.split('.')[0]
-
- #
- # Lancement Container C++ local
- #
- if with_container_cpp:
- ContainerCPPServer().run()
- #
- # Attente de la disponibilité du Container C++ local
- # dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
- #
- # Lancement Container Python local
- #
- if with_container_python:
- ContainerPYServer().run()
- #
- # Attente de la disponibilité du Container Python local
- # dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
-
- if with_container_superv:
- #
- # Lancement Container Supervision local
- #
- ContainerSUPERVServer().run()
- #
- # Attente de la disponibilité du Container Supervision local
+ #
+ # Lancement Session Loader
+ #
+ SessionLoader().run()
+
+ #
+ # Initialisation ORB et Naming Service
+ #
+ clt=orbmodule.client()
+
+ # (non obligatoire) Lancement Logger Server et attente de sa
+ # disponibilite dans le naming service
+ #
+ if with_logger:
+ LoggerServer().run()
+ clt.waitLogger("Logger")
+
+ #
+ # Lancement Registry Server
+ #
+ RegistryServer().run()
+
+ #
+ # Attente de la disponibilit?? du Registry dans le Naming Service
+ #
+ clt.waitNS("/Registry")
+
+ #
+ # Lancement Catalog Server
+ #
+ cataServer=CatalogServer()
+ cataServer.setpath(liste_modules)
+ cataServer.run()
+
+ #
+ # Attente de la disponibilit?? du Catalog Server dans le Naming Service
+ #
+ import SALOME_ModuleCatalog
+ clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
+
+ #
+ # Lancement SalomeDS Server
+ #
+ os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
+ os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
+ SalomeDSServer().run()
+
+ if "GEOM" in liste_modules:
+ print("GEOM OCAF Resources")
+ os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
+
+
+ #
+ # Attente de la disponibilit?? du SalomeDS dans le Naming Service
+ #
+ clt.waitNS("/myStudyManager")
+
+ #
+ # Lancement Session Server
+ #
+ SessionServer().run()
+
+ #
+ # Attente de la disponibilit?? du Session Server dans le Naming Service
+ #
+ import SALOME
+ session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+ #
+ # Lancement containers
+ #
+ theComputer = os.getenv("HOSTNAME")
+ theComputer = theComputer.split('.')[0]
+
+ #
+ # Lancement Container C++ local
+ #
+ if with_container_cpp:
+ ContainerCPPServer().run()
+ #
+ # Attente de la disponibilit?? du Container C++ local
# dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
- #
- # Activation du GUI de Session Server
- #
- #session.GetInterface()
+ #
+ clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
+ #
+ # Lancement Container Python local
+ #
+ if with_container_python:
+ ContainerPYServer().run()
+ #
+ # Attente de la disponibilit?? du Container Python local
+ # dans le Naming Service
+ #
+ clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
+
+ if with_container_superv:
+ #
+ # Lancement Container Supervision local
+ #
+ ContainerSUPERVServer().run()
+ #
+ # Attente de la disponibilit?? du Container Supervision local
+ # dans le Naming Service
+ #
+ clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
+ #
+ # Activation du GUI de Session Server
+ #
+ #session.GetInterface()
- end_time = os.times()
- print
- print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4])
+ end_time = os.times()
+ print()
+ print("Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4]))
- return clt
+ return clt
#
# -----------------------------------------------------------------------------
#
if __name__ == "__main__":
- clt=None
- try:
- clt = startSalome()
- except:
- print
- print
- print "--- erreur au lancement Salome ---"
-
- #print process_id
-
-
- filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
- #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
-
- fpid=open(filedict, 'w')
- pickle.dump(process_id,fpid)
- fpid.close()
-
- print """
-
-Sauvegarde du dictionnaire des process dans , %s
-Pour tuer les process SALOME, executer : python killSalome.py depuis
-une console, ou bien killSalome() depuis le present interpreteur,
-s'il n'est pas fermé.
-
-runSalome, avec l'option --killall, commence par tuer les process restants
-d'une execution précédente.
-
-Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
-s'il n'est pas fermé.
-
-""" % filedict
-
- #
- # Impression arborescence Naming Service
- #
-
- if clt != None:
- print
- print " --- registered objects tree in Naming Service ---"
- clt.showNS()
- session=clt.waitNS("/Kernel/Session")
- catalog=clt.waitNS("/Kernel/ModulCatalog")
- import socket
- container = clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
-
- if os.path.isfile("~/.salome/pystartup"):
- f=open(os.path.expanduser("~/.salome/pystartup"),'w')
- PYTHONSTARTUP=f.read()
- f.close()
- else:
- PYTHONSTARTUP="""
-# Add auto-completion and a stored history file of commands to your Python
-# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
-# bound to the TAB key by default (you can change it - see readline docs).
-#
-# Store the history in ~/.salome/pyhistory,
-#
-import atexit
-import os
-import readline
-import rlcompleter
-readline.parse_and_bind('tab: complete')
+ clt=None
+ try:
+ clt = startSalome()
+ except:
+ print()
+ print()
+ print("--- erreur au lancement Salome ---")
+
+ #print process_id
+
+
+ filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
+ #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
+
+ fpid=open(filedict, 'w')
+ pickle.dump(process_id,fpid)
+ fpid.close()
+
+ print("""
+
+ Sauvegarde du dictionnaire des process dans , %s
+ Pour tuer les process SALOME, executer : python killSalome.py depuis
+ une console, ou bien killSalome() depuis le present interpreteur,
+ s'il n'est pas ferm??.
+
+ runSalome, avec l'option --killall, commence par tuer les process restants
+ d'une execution pr??c??dente.
+
+ Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
+ s'il n'est pas ferm??.
+
+ """ % filedict)
+
+ #
+ # Impression arborescence Naming Service
+ #
+
+ if clt != None:
+ print()
+ print(" --- registered objects tree in Naming Service ---")
+ clt.showNS()
+ session=clt.waitNS("/Kernel/Session")
+ catalog=clt.waitNS("/Kernel/ModulCatalog")
+ import socket
+ container = clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
+
+ if os.path.isfile("~/.salome/pystartup"):
+ f=open(os.path.expanduser("~/.salome/pystartup"),'w')
+ PYTHONSTARTUP=f.read()
+ f.close()
+ else:
+ PYTHONSTARTUP="""
+ # Add auto-completion and a stored history file of commands to your Python
+ # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
+ # bound to the TAB key by default (you can change it - see readline docs).
+ #
+ # Store the history in ~/.salome/pyhistory,
+ #
+ import atexit
+ import os
+ import readline
+ import rlcompleter
+ readline.parse_and_bind('tab: complete')
-historyPath = os.path.expanduser("~/.salome/pyhistory")
+ historyPath = os.path.expanduser("~/.salome/pyhistory")
-def save_history(historyPath=historyPath):
- import readline
- readline.write_history_file(historyPath)
+ def save_history(historyPath=historyPath):
+ import readline
+ readline.write_history_file(historyPath)
-if os.path.exists(historyPath):
- readline.read_history_file(historyPath)
+ if os.path.exists(historyPath):
+ readline.read_history_file(historyPath)
-atexit.register(save_history)
-del os, atexit, readline, rlcompleter, save_history, historyPath
-"""
- f=open(os.path.expanduser("~/.salome/pystartup"),'w')
- f.write(PYTHONSTARTUP)
- f.close()
+ atexit.register(save_history)
+ del os, atexit, readline, rlcompleter, save_history, historyPath
+ """
+ f=open(os.path.expanduser("~/.salome/pystartup"),'w')
+ f.write(PYTHONSTARTUP)
+ f.close()
- exec PYTHONSTARTUP in {}
-
+ exec(PYTHONSTARTUP, {})
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-mport salome
+import salome
import HXX2SALOME_GENERIC_CLASS_NAME_ORB
myHXX2SALOME_GENERIC_CLASS_NAME = salome.lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
#
#
-print "Hello HXX2SALOME_GENERIC_CLASS_NAME"
+print("Hello HXX2SALOME_GENERIC_CLASS_NAME")
# Test here some of HXX2SALOME_GENERIC_CLASS_NAME methods ...
msgstr "Ceci est un simple test"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::INF_HXX2SALOME_GENERIC_CLASS_NAME_CHECK"
-msgstr "Cochée"
+msgstr "Cochée"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::INF_HXX2SALOME_GENERIC_CLASS_NAME_UNCHECK"
-msgstr "Décochée"
+msgstr "Décochée"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::RES_HXX2SALOME_GENERIC_CLASS_NAME_TITLE"
msgstr "Dialogue example de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::RES_HXX2SALOME_GENERIC_CLASS_NAME_TEXT"
-msgstr "Les préférences sont : \n\tCase à cocher : %1\n\tEntier : %2\n\tEntier2 : %3\n\tDouble : %4\n\tTexte : %5"
+msgstr "Les préférences sont : \n\tCase à cocher : %1\n\tEntier : %2\n\tEntier2 : %3\n\tDouble : %4\n\tTexte : %5"
msgid "TLT_MY_NEW_ITEM"
-msgstr "Un article de menu propre à HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Un article de menu propre à HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_MY_NEW_ITEM"
msgstr "Mon menu"
msgid "STS_MY_NEW_ITEM"
-msgstr "Affiche une boîte de dialogue simple"
+msgstr "Affiche une boîte de dialogue simple"
msgid "TLT_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "STS_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_FILE"
msgstr "&File"
#-------------------------------------------------------------------------
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_TAB_GENERAL"
-msgstr "Général"
+msgstr "Général"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_GROUP_DEFAULTS"
-msgstr "Valeurs par défaut"
+msgstr "Valeurs par défaut"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_BOOL"
msgstr "Cochez-moi"
msgstr "Entrez un entier :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SPININT"
-msgstr "Cliquez sur les flèches (entier) :"
+msgstr "Cliquez sur les flèches (entier) :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SPINDBL"
-msgstr "Cliquez sur les flèches (double) :"
+msgstr "Cliquez sur les flèches (double) :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SELECTOR"
msgstr "Choisissez une option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_0"
-msgstr "Première option"
+msgstr "Première option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_1"
msgstr "Seconde option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_2"
-msgstr "Troisième option"
+msgstr "Troisième option"
AC_SUBST(PYTHONHOME)
changequote(<<, >>)dnl
- PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"`
+ PYTHON_VERSION=`$PYTHON -c "import sys; print(sys.version[:3])"`
changequote([, ])dnl
AC_SUBST(PYTHON_VERSION)
dnl to know which OS Python thinks this is.
AC_SUBST(PYTHON_PLATFORM)
- PYTHON_PLATFORM=`$PYTHON -c "import sys; print sys.platform"`
+ PYTHON_PLATFORM=`$PYTHON -c "import sys; print(sys.platform)"`
AC_SUBST(PYTHON_SITE)
AC_ARG_WITH(python-site,
import sys, os, string, py_compile
files = '''$*'''
-print 'Byte-compiling python modules...'
+print('Byte-compiling python modules...')
for file in string.split(files):
$trans
if not os.path.exists(path) or not (len(path) >= 3 and path[-3:] == '.py'):
continue
- print file,
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(path)
print" || exit $?
import sys, os, string, py_compile
files = '''$*'''
-print 'Byte-compiling python modules (optimized versions) ...'
+print('Byte-compiling python modules (optimized versions) ...')
for file in string.split(files):
$trans
if not os.path.exists(path) or not (len(path) >= 3 and path[-3:] == '.py'):
continue
- print file,
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(path)
print" 2>/dev/null || :
[command line options] :
--help : affichage de l'aide
--gui : lancement du GUI
---logger : redirection des messages dans un fichier
---xterm : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre
---modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue
+--logger : redirection des messages dans un fichier
+--xterm : les serveurs ouvrent une fen??tre xterm et les messages sont affich??s dans cette fen??tre
+--modules=module1,module2,... : o?? modulen est le nom d'un module Salome ?? charger dans le catalogue
--containers=cpp,python,superv: lancement des containers cpp, python et de supervision
---killall : arrêt des serveurs de salome
+--killall : arr??t des serveurs de salome
- La variable d'environnement <modulen>_ROOT_DIR doit etre préalablement
- positionnée (modulen doit etre en majuscule).
+ La variable d'environnement <modulen>_ROOT_DIR doit etre pr??alablement
+ positionn??e (modulen doit etre en majuscule).
KERNEL_ROOT_DIR est obligatoire.
"""
# -----------------------------------------------------------------------------
#
-# Fonction d'arrêt de salome
+# Fonction d'arr??t de salome
#
def killSalome():
- print "arret des serveurs SALOME"
- for pid, cmd in process_id.items():
- print "arret du process %s : %s"% (pid, cmd[0])
- try:
- os.kill(pid,signal.SIGKILL)
- except:
- print " ------------------ process %s : %s inexistant"% (pid, cmd[0])
- print "arret du naming service"
- os.system("killall -9 omniNames")
-
+ print("arret des serveurs SALOME")
+ for pid, cmd in list(process_id.items()):
+ print("arret du process %s : %s"% (pid, cmd[0]))
+ try:
+ os.kill(pid,signal.SIGKILL)
+ except:
+ print(" ------------------ process %s : %s inexistant"% (pid, cmd[0]))
+ print("arret du naming service")
+ os.system("killall -9 omniNames")
+
# -----------------------------------------------------------------------------
#
# Fonction message
#
def message(code, msg=''):
- if msg: print msg
+ if msg: print(msg)
sys.exit(code)
import sys,os,string,glob,time,signal,pickle,getopt
with_container_superv=0
try:
- for o, a in opts:
- if o in ('-h', '--help'):
- print usage
- sys.exit(1)
- elif o in ('-g', '--gui'):
- with_gui=1
- elif o in ('-l', '--logger'):
- with_logger=1
- elif o in ('-x', '--xterm'):
- with_xterm=1
- elif o in ('-m', '--modules'):
- liste_modules = [x.upper() for x in a.split(',')]
- elif o in ('-c', '--containers'):
- liste_containers = [x.lower() for x in a.split(',')]
- for r in liste_containers:
- if r not in ('cpp', 'python', 'superv'):
- message(1, 'Invalid -c/--containers option: %s' % a)
- if 'cpp' in liste_containers:
- with_container_cpp=1
- else:
- with_container_cpp=0
- if 'python' in liste_containers:
- with_container_python=1
- else:
- with_container_python=0
- if 'superv' in liste_containers:
- with_container_superv=1
- else:
- with_container_superv=0
- elif o in ('-k', '--killall'):
- filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
- #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
- found = 0
- try:
- fpid=open(filedict, 'r')
- found = 1
- except:
- print "le fichier %s des process SALOME n'est pas accessible"% filedict
-
- if found:
- process_id=pickle.load(fpid)
- fpid.close()
- killSalome()
- process_id={}
- os.remove(filedict)
-
-except getopt.error, msg:
- print usage
- sys.exit(1)
+ for o, a in opts:
+ if o in ('-h', '--help'):
+ print(usage)
+ sys.exit(1)
+ elif o in ('-g', '--gui'):
+ with_gui=1
+ elif o in ('-l', '--logger'):
+ with_logger=1
+ elif o in ('-x', '--xterm'):
+ with_xterm=1
+ elif o in ('-m', '--modules'):
+ liste_modules = [x.upper() for x in a.split(',')]
+ elif o in ('-c', '--containers'):
+ liste_containers = [x.lower() for x in a.split(',')]
+ for r in liste_containers:
+ if r not in ('cpp', 'python', 'superv'):
+ message(1, 'Invalid -c/--containers option: %s' % a)
+ if 'cpp' in liste_containers:
+ with_container_cpp=1
+ else:
+ with_container_cpp=0
+ if 'python' in liste_containers:
+ with_container_python=1
+ else:
+ with_container_python=0
+ if 'superv' in liste_containers:
+ with_container_superv=1
+ else:
+ with_container_superv=0
+ elif o in ('-k', '--killall'):
+ filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
+ #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
+ found = 0
+ try:
+ fpid=open(filedict, 'r')
+ found = 1
+ except:
+ print("le fichier %s des process SALOME n'est pas accessible"% filedict)
+
+ if found:
+ process_id=pickle.load(fpid)
+ fpid.close()
+ killSalome()
+ process_id={}
+ os.remove(filedict)
+
+except getopt.error as msg:
+ print(usage)
+ sys.exit(1)
# -----------------------------------------------------------------------------
#
-# Vérification des variables d'environnement
+# V??rification des variables d'environnement
#
try:
- kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
- modules_root_dir["KERNEL"]=kernel_root_dir
+ kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
+ modules_root_dir["KERNEL"]=kernel_root_dir
except:
- print usage
- sys.exit(1)
+ print(usage)
+ sys.exit(1)
for module in liste_modules :
- try:
- module=module.upper()
- module_root_dir=os.environ[module +"_ROOT_DIR"]
- modules_root_dir[module]=module_root_dir
- except:
- print usage
- sys.exit(1)
+ try:
+ module=module.upper()
+ module_root_dir=os.environ[module +"_ROOT_DIR"]
+ modules_root_dir[module]=module_root_dir
+ except:
+ print(usage)
+ sys.exit(1)
# il faut KERNEL en premier dans la liste des modules
# - l'ordre des modules dans le catalogue sera identique
-# - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python,
+# - la liste des modules presents dans le catalogue est exploit??e pour charger les modules CORBA python,
# il faut charger les modules python du KERNEL en premier
if "KERNEL" in liste_modules:liste_modules.remove("KERNEL")
#print liste_modules
#print modules_root_dir
-os.environ["SALOMEPATH"]=":".join(modules_root_dir.values())
+os.environ["SALOMEPATH"]=":".join(list(modules_root_dir.values()))
if "SUPERV" in liste_modules:with_container_superv=1
# -----------------------------------------------------------------------------
#
-# Définition des classes d'objets pour le lancement des Server CORBA
+# D??finition des classes d'objets pour le lancement des Server CORBA
#
class Server:
- CMD=[]
- if with_xterm:
- ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
- else:
- ARGS=[]
-
- def run(self):
- args = self.ARGS+self.CMD
- #print "args = ", args
- pid = os.spawnvp(os.P_NOWAIT, args[0], args)
- process_id[pid]=self.CMD
+ CMD=[]
+ if with_xterm:
+ ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
+ else:
+ ARGS=[]
+
+ def run(self):
+ args = self.ARGS+self.CMD
+ #print "args = ", args
+ pid = os.spawnvp(os.P_NOWAIT, args[0], args)
+ process_id[pid]=self.CMD
class CatalogServer(Server):
- SCMD1=['SALOME_ModuleCatalog_Server','-common']
- SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml']
-
- def setpath(self,liste_modules):
- cata_path=[]
- for module in liste_modules:
- module_root_dir=modules_root_dir[module]
- module_cata=module+"Catalog.xml"
- print " ", module_cata
- cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
- self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+ SCMD1=['SALOME_ModuleCatalog_Server','-common']
+ SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml']
+
+ def setpath(self,liste_modules):
+ cata_path=[]
+ for module in liste_modules:
+ module_root_dir=modules_root_dir[module]
+ module_cata=module+"Catalog.xml"
+ print(" ", module_cata)
+ cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
+ self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
class SalomeDSServer(Server):
- CMD=['SALOMEDS_Server']
+ CMD=['SALOMEDS_Server']
class RegistryServer(Server):
- CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+ CMD=['SALOME_Registry_Server', '--salome_session','theSession']
class ContainerCPPServer(Server):
- CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
class ContainerPYServer(Server):
- CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
class ContainerSUPERVServer(Server):
- CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
class LoggerServer(Server):
- CMD=['SALOME_Logger_Server', 'logger.log']
+ CMD=['SALOME_Logger_Server', 'logger.log']
class SessionLoader(Server):
- CMD=['SALOME_Session_Loader']
- if with_container_cpp:
- CMD=CMD+['CPP']
- if with_container_python:
- CMD=CMD+['PY']
- if with_container_superv:
- CMD=CMD+['SUPERV']
- if with_gui:
- CMD=CMD+['GUI']
+ CMD=['SALOME_Session_Loader']
+ if with_container_cpp:
+ CMD=CMD+['CPP']
+ if with_container_python:
+ CMD=CMD+['PY']
+ if with_container_superv:
+ CMD=CMD+['SUPERV']
+ if with_gui:
+ CMD=CMD+['GUI']
class SessionServer(Server):
- CMD=['SALOME_Session_Server']
+ CMD=['SALOME_Session_Server']
class NotifyServer(Server):
- CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
+ CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
# -----------------------------------------------------------------------------
#
#
def test(clt):
- """
- Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
- usage : hello=test(clt)
- """
- # create an LifeCycleCORBA instance
- import LifeCycleCORBA
- lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
- import HXX2SALOME_GENERIC_CLASS_NAME_ORB
- hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
- return hello
+ """
+ Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
+ usage : hello=test(clt)
+ """
+ # create an LifeCycleCORBA instance
+ import LifeCycleCORBA
+ lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
+ import HXX2SALOME_GENERIC_CLASS_NAME_ORB
+ hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
+ return hello
# -----------------------------------------------------------------------------
#
#
def add_path(directory):
- os.environ["PATH"]=directory + ":" + os.environ["PATH"]
+ os.environ["PATH"]=directory + ":" + os.environ["PATH"]
def add_ld_library_path(directory):
- os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
+ os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
def add_python_path(directory):
- os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
- sys.path[:0]=[directory]
+ os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
+ sys.path[:0]=[directory]
# -----------------------------------------------------------------------------
#
#
def startGUI():
- import SALOME
- session=clt.waitNS("/Kernel/Session",SALOME.Session)
+ import SALOME
+ session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+ #
+ # Activation du GUI de Session Server
+ #
+
+ session.GetInterface()
- #
- # Activation du GUI de Session Server
- #
-
- session.GetInterface()
-
#
# -----------------------------------------------------------------------------
#
def startSalome():
- #
- # Lancement Session Loader
- #
- SessionLoader().run()
-
- #
- # Initialisation ORB et Naming Service
- #
- clt=orbmodule.client()
-
- # (non obligatoire) Lancement Logger Server et attente de sa
- # disponibilite dans le naming service
- #
- if with_logger:
- LoggerServer().run()
- clt.waitLogger("Logger")
-
- #
- # Lancement Registry Server
- #
- RegistryServer().run()
-
- #
- # Attente de la disponibilité du Registry dans le Naming Service
- #
- clt.waitNS("/Registry")
-
- #
- # Lancement Catalog Server
- #
- cataServer=CatalogServer()
- cataServer.setpath(liste_modules)
- cataServer.run()
-
- #
- # Attente de la disponibilité du Catalog Server dans le Naming Service
- #
- import SALOME_ModuleCatalog
- clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
-
- #
- # Lancement SalomeDS Server
- #
- os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
- os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
- SalomeDSServer().run()
-
- if "GEOM" in liste_modules:
- print "GEOM OCAF Resources"
- os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
-
-
- #
- # Attente de la disponibilité du SalomeDS dans le Naming Service
- #
- clt.waitNS("/myStudyManager")
-
- #
- # Lancement Session Server
- #
- SessionServer().run()
-
- #
- # Attente de la disponibilité du Session Server dans le Naming Service
- #
- import SALOME
- session=clt.waitNS("/Kernel/Session",SALOME.Session)
-
- #
- # Lancement containers
- #
- theComputer = os.getenv("HOSTNAME")
- theComputer = theComputer.split('.')[0]
-
- #
- # Lancement Container C++ local
- #
- if with_container_cpp:
- ContainerCPPServer().run()
- #
- # Attente de la disponibilité du Container C++ local
- # dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
- #
- # Lancement Container Python local
- #
- if with_container_python:
- ContainerPYServer().run()
- #
- # Attente de la disponibilité du Container Python local
- # dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
-
- if with_container_superv:
- #
- # Lancement Container Supervision local
- #
- ContainerSUPERVServer().run()
- #
- # Attente de la disponibilité du Container Supervision local
+ #
+ # Lancement Session Loader
+ #
+ SessionLoader().run()
+
+ #
+ # Initialisation ORB et Naming Service
+ #
+ clt=orbmodule.client()
+
+ # (non obligatoire) Lancement Logger Server et attente de sa
+ # disponibilite dans le naming service
+ #
+ if with_logger:
+ LoggerServer().run()
+ clt.waitLogger("Logger")
+
+ #
+ # Lancement Registry Server
+ #
+ RegistryServer().run()
+
+ #
+ # Attente de la disponibilit?? du Registry dans le Naming Service
+ #
+ clt.waitNS("/Registry")
+
+ #
+ # Lancement Catalog Server
+ #
+ cataServer=CatalogServer()
+ cataServer.setpath(liste_modules)
+ cataServer.run()
+
+ #
+ # Attente de la disponibilit?? du Catalog Server dans le Naming Service
+ #
+ import SALOME_ModuleCatalog
+ clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
+
+ #
+ # Lancement SalomeDS Server
+ #
+ os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
+ os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
+ SalomeDSServer().run()
+
+ if "GEOM" in liste_modules:
+ print("GEOM OCAF Resources")
+ os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
+
+
+ #
+ # Attente de la disponibilit?? du SalomeDS dans le Naming Service
+ #
+ clt.waitNS("/myStudyManager")
+
+ #
+ # Lancement Session Server
+ #
+ SessionServer().run()
+
+ #
+ # Attente de la disponibilit?? du Session Server dans le Naming Service
+ #
+ import SALOME
+ session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+ #
+ # Lancement containers
+ #
+ theComputer = os.getenv("HOSTNAME")
+ theComputer = theComputer.split('.')[0]
+
+ #
+ # Lancement Container C++ local
+ #
+ if with_container_cpp:
+ ContainerCPPServer().run()
+ #
+ # Attente de la disponibilit?? du Container C++ local
# dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
- #
- # Activation du GUI de Session Server
- #
- #session.GetInterface()
+ #
+ clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
+ #
+ # Lancement Container Python local
+ #
+ if with_container_python:
+ ContainerPYServer().run()
+ #
+ # Attente de la disponibilit?? du Container Python local
+ # dans le Naming Service
+ #
+ clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
+
+ if with_container_superv:
+ #
+ # Lancement Container Supervision local
+ #
+ ContainerSUPERVServer().run()
+ #
+ # Attente de la disponibilit?? du Container Supervision local
+ # dans le Naming Service
+ #
+ clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
+ #
+ # Activation du GUI de Session Server
+ #
+ #session.GetInterface()
- end_time = os.times()
- print
- print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4])
+ end_time = os.times()
+ print()
+ print("Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4]))
- return clt
+ return clt
#
# -----------------------------------------------------------------------------
#
if __name__ == "__main__":
- clt=None
- try:
- clt = startSalome()
- except:
- print
- print
- print "--- erreur au lancement Salome ---"
-
- #print process_id
-
-
- filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
- #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
-
- fpid=open(filedict, 'w')
- pickle.dump(process_id,fpid)
- fpid.close()
-
- print """
-
-Sauvegarde du dictionnaire des process dans , %s
-Pour tuer les process SALOME, executer : python killSalome.py depuis
-une console, ou bien killSalome() depuis le present interpreteur,
-s'il n'est pas fermé.
-
-runSalome, avec l'option --killall, commence par tuer les process restants
-d'une execution précédente.
-
-Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
-s'il n'est pas fermé.
-
-""" % filedict
-
- #
- # Impression arborescence Naming Service
- #
-
- if clt != None:
- print
- print " --- registered objects tree in Naming Service ---"
- clt.showNS()
- session=clt.waitNS("/Kernel/Session")
- catalog=clt.waitNS("/Kernel/ModulCatalog")
- import socket
- container = clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
-
- if os.path.isfile("~/.salome/pystartup"):
- f=open(os.path.expanduser("~/.salome/pystartup"),'w')
- PYTHONSTARTUP=f.read()
- f.close()
- else:
- PYTHONSTARTUP="""
-# Add auto-completion and a stored history file of commands to your Python
-# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
-# bound to the TAB key by default (you can change it - see readline docs).
-#
-# Store the history in ~/.salome/pyhistory,
-#
-import atexit
-import os
-import readline
-import rlcompleter
-readline.parse_and_bind('tab: complete')
+ clt=None
+ try:
+ clt = startSalome()
+ except:
+ print()
+ print()
+ print("--- erreur au lancement Salome ---")
+
+ #print process_id
+
+
+ filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
+ #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
+
+ fpid=open(filedict, 'w')
+ pickle.dump(process_id,fpid)
+ fpid.close()
+
+ print("""
+
+ Sauvegarde du dictionnaire des process dans , %s
+ Pour tuer les process SALOME, executer : python killSalome.py depuis
+ une console, ou bien killSalome() depuis le present interpreteur,
+ s'il n'est pas ferm??.
+
+ runSalome, avec l'option --killall, commence par tuer les process restants
+ d'une execution pr??c??dente.
+
+ Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
+ s'il n'est pas ferm??.
+
+ """ % filedict)
+
+ #
+ # Impression arborescence Naming Service
+ #
+
+ if clt != None:
+ print()
+ print(" --- registered objects tree in Naming Service ---")
+ clt.showNS()
+ session=clt.waitNS("/Kernel/Session")
+ catalog=clt.waitNS("/Kernel/ModulCatalog")
+ import socket
+ container = clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
+
+ if os.path.isfile("~/.salome/pystartup"):
+ f=open(os.path.expanduser("~/.salome/pystartup"),'w')
+ PYTHONSTARTUP=f.read()
+ f.close()
+ else:
+ PYTHONSTARTUP="""
+ # Add auto-completion and a stored history file of commands to your Python
+ # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
+ # bound to the TAB key by default (you can change it - see readline docs).
+ #
+ # Store the history in ~/.salome/pyhistory,
+ #
+ import atexit
+ import os
+ import readline
+ import rlcompleter
+ readline.parse_and_bind('tab: complete')
-historyPath = os.path.expanduser("~/.salome/pyhistory")
+ historyPath = os.path.expanduser("~/.salome/pyhistory")
-def save_history(historyPath=historyPath):
- import readline
- readline.write_history_file(historyPath)
+ def save_history(historyPath=historyPath):
+ import readline
+ readline.write_history_file(historyPath)
-if os.path.exists(historyPath):
- readline.read_history_file(historyPath)
+ if os.path.exists(historyPath):
+ readline.read_history_file(historyPath)
-atexit.register(save_history)
-del os, atexit, readline, rlcompleter, save_history, historyPath
-"""
- f=open(os.path.expanduser("~/.salome/pystartup"),'w')
- f.write(PYTHONSTARTUP)
- f.close()
+ atexit.register(save_history)
+ del os, atexit, readline, rlcompleter, save_history, historyPath
+ """
+ f=open(os.path.expanduser("~/.salome/pystartup"),'w')
+ f.write(PYTHONSTARTUP)
+ f.close()
- exec PYTHONSTARTUP in {}
-
+ exec(PYTHONSTARTUP, {})
files = '''$files'''
-print 'Byte-compiling python modules...'
+print('Byte-compiling python modules...')
for file in string.split(files):
$pathtrans
$filetrans
if not os.path.exists(filepath) or not (len(filepath) >= 3
and filepath[-3:] == '.py'):
- continue
- print file,
+ continue
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(filepath, filepath + 'c', path)
-print" || exit $?
+print()" || exit $?
# this will fail for python < 1.5, but that doesn't matter ...
$PYTHON -O -c "
import sys, os, string, py_compile
files = '''$files'''
-print 'Byte-compiling python modules (optimized versions) ...'
+print('Byte-compiling python modules (optimized versions) ...')
for file in string.split(files):
$pathtrans
$filetrans
if not os.path.exists(filepath) or not (len(filepath) >= 3
and filepath[-3:] == '.py'):
- continue
- print file,
+ continue
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(filepath, filepath + 'o', path)
-print" 2>/dev/null || :
-
-# Local Variables:
-# mode: shell-script
-# sh-indentation: 2
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-end: "$"
-# End:
+print()" 2>/dev/null || :
+
msgstr "Ceci est un simple test"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::INF_HXX2SALOME_GENERIC_CLASS_NAME_CHECK"
-msgstr "Cochée"
+msgstr "Cochée"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::INF_HXX2SALOME_GENERIC_CLASS_NAME_UNCHECK"
-msgstr "Décochée"
+msgstr "Décochée"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::RES_HXX2SALOME_GENERIC_CLASS_NAME_TITLE"
msgstr "Dialogue example de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::RES_HXX2SALOME_GENERIC_CLASS_NAME_TEXT"
-msgstr "Les préférences sont : \n\tCase à cocher : %1\n\tEntier : %2\n\tEntier2 : %3\n\tDouble : %4\n\tTexte : %5"
+msgstr "Les préférences sont : \n\tCase à cocher : %1\n\tEntier : %2\n\tEntier2 : %3\n\tDouble : %4\n\tTexte : %5"
msgid "TLT_MY_NEW_ITEM"
-msgstr "Un article de menu propre à HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Un article de menu propre à HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_MY_NEW_ITEM"
msgstr "Mon menu"
msgid "STS_MY_NEW_ITEM"
-msgstr "Affiche une boîte de dialogue simple"
+msgstr "Affiche une boîte de dialogue simple"
msgid "TLT_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "STS_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_FILE"
msgstr "&File"
#-------------------------------------------------------------------------
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_TAB_GENERAL"
-msgstr "Général"
+msgstr "Général"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_GROUP_DEFAULTS"
-msgstr "Valeurs par défaut"
+msgstr "Valeurs par défaut"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_BOOL"
msgstr "Cochez-moi"
msgstr "Entrez un entier :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SPININT"
-msgstr "Cliquez sur les flèches (entier) :"
+msgstr "Cliquez sur les flèches (entier) :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SPINDBL"
-msgstr "Cliquez sur les flèches (double) :"
+msgstr "Cliquez sur les flèches (double) :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SELECTOR"
msgstr "Choisissez une option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_0"
-msgstr "Première option"
+msgstr "Première option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_1"
msgstr "Seconde option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_2"
-msgstr "Troisième option"
+msgstr "Troisième option"
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-mport salome
+import salome
import HXX2SALOME_GENERIC_CLASS_NAME_ORB
myHXX2SALOME_GENERIC_CLASS_NAME = salome.lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
#
#
-print "Hello HXX2SALOME_GENERIC_CLASS_NAME"
+print("Hello HXX2SALOME_GENERIC_CLASS_NAME")
# Test here some of HXX2SALOME_GENERIC_CLASS_NAME methods ...
#
#
END {
-# CNC peut être mis dans le template directement printf "\nprivate:\n std::auto_ptr<%s> cppImpl_;\n",class_name >> hxx_file
+# CNC peut être mis dans le template directement printf "\nprivate:\n std::auto_ptr<%s> cppImpl_;\n",class_name >> hxx_file
}
" <component-author>""</component-author>\n"\
" <component-version>1.0</component-version>\n"\
" <component-comment></component-comment>\n"\
- " <component-multistudy>1</component-multistudy>\n"\
" <component-icone>"class_name".png</component-icone>\n"\
" <component-impltype>1</component-impltype>\n"\
" <component-interface-list>" >> catalog_file
echo ""
echo " to run IDLparser:"
echo ""
- echo " $0 -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,multistudy=<component_multistudy>][,remove=component_name] <file.idl> "
+ echo " $0 -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,remove=component_name] <file.idl> "
echo ""
echo " to have omniidl help:"
echo ""
# additional include directories
INCLUDE_DIRECTORIES(
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIR}
${PROJECT_SOURCE_DIR}/src/bases
${PROJECT_SOURCE_DIR}/src/engine
${CPPUNIT_INCLUDE_DIRS}
${PYTHON_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${KERNEL_INCLUDE_DIRS}
${CMAKE_CURRENT_SOURCE_DIR}/..
${CMAKE_CURRENT_SOURCE_DIR}/../../bases
YACSLoader loader;
Executor executor;
-
try
{
p=loader.load(schema);
+
+ std::cerr << __FILE__ << std::endl;
DEBTRACE("Proc *p = " << p);
std::ofstream f("toto");
p->writeDot(f);
f.close();
DEBTRACE("+++++++++++++++++++ BEGIN execution " << schema);
+ std::cerr << __FILE__ << std::endl;
executor.RunW(p,0);
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE("+++++++++++++++++++ END execution " << schema);
std::ofstream g("titi");
p->writeDot(g);
catch (YACS::Exception& e)
{
DEBTRACE("YACS exception caught: ");
+ std::cerr << __FILE__ << std::endl;
DEBTRACE(e.what());
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE("+++++++++++++++++++ END test in error " << schema);
return 1;
}
catch (const std::ios_base::failure&)
{
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE("io failure");
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE("+++++++++++++++++++ END test in error " << schema);
return 1;
}
const char *p = tc->name();
if ( *p != '\0' )
{
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE(p);
}
else
{
+ std::cerr << __FILE__ << std::endl;
DEBTRACE(tc->id());
}
DEBTRACE("+++++++++++++++++++ END test in error " << schema);
if (p)
{
PyObject *data = ((OutputPyPort*)p->nodeMap["node2"]->getOutputPort("p1"))->get();
- char *text = PyString_AsString(data);
+ char *text = PyUnicode_AsUTF8(data);
CPPUNIT_ASSERT_EQUAL(string("coucoucoucoucoucoucoucou"), string(text));
delete p;
}
if (p)
{
PyObject *data = ((OutputPyPort*)p->nodeMap["node2"]->getOutputPort("p1"))->get();
- char *text = PyString_AsString(data);;
+ char *text = PyUnicode_AsUTF8(data);
CPPUNIT_ASSERT_EQUAL(string("coucoucoucoucoucoucoucou"), string(text) );
delete p;
}
"""Optional method called on initialization.
The type of "input" is returned by "getTCForAlgoInit"
"""
- print "Algo initialize, input = ", input.getIntValue()
+ print("Algo initialize, input = ", input.getIntValue())
def startToTakeDecision(self):
"""This method is called only once to launch the algorithm. It must
pool, do nothing (wait for more samples), or empty the pool and
return to finish the evaluation.
"""
- print "startToTakeDecision"
+ print("startToTakeDecision")
# fill the pool with samples
iter=0
self.pool.pushInSample(0, 0.5)
currentId=self.pool.getCurrentId()
valIn = self.pool.getCurrentInSample().getDoubleValue()
valOut = self.pool.getCurrentOutSample().getIntValue()
- print "Compute currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut)
+ print("Compute currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut))
iter=iter+1
if iter < 3:
def finish(self):
"""Optional method called when the algorithm has finished, successfully
or not, to perform any necessary clean up."""
- print "Algo finish"
+ print("Algo finish")
self.pool.destroyAll()
def getAlgoResult(self):
"""Optional method called on initialization.
The type of "input" is returned by "getTCForAlgoInit"
"""
- print "Algo initialize, input = ", input.getIntValue()
+ print("Algo initialize, input = ", input.getIntValue())
def start(self):
"""Start to fill the pool with samples to evaluate."""
- print "Algo start "
+ print("Algo start ")
self.iter=0
# pushInSample(id, value)
self.pool.pushInSample(self.iter, 0.5)
currentId=self.pool.getCurrentId()
valIn = self.pool.getCurrentInSample().getDoubleValue()
valOut = self.pool.getCurrentOutSample().getIntValue()
- print "Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut)
+ print("Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut))
self.iter=self.iter+1
if self.iter < 3:
def finish(self):
"""Optional method called when the algorithm has finished, successfully
or not, to perform any necessary clean up."""
- print "Algo finish"
+ print("Algo finish")
self.pool.destroyAll()
def getAlgoResult(self):
rootContext = obj._narrow(CosNaming.NamingContext)
if rootContext is None:
- print "Failed to narrow the root naming context"
+ print("Failed to narrow the root naming context")
sys.exit(1)
# Resolve the name "test.my_context/Echo.Object"
try:
obj = rootContext.resolve(name)
-except CosNaming.NamingContext.NotFound, ex:
- print "Name not found"
+except CosNaming.NamingContext.NotFound as ex:
+ print("Name not found")
sys.exit(1)
# Narrow the object to an eo::Echo
echo = obj._narrow(eo.Echo)
if echo is None:
- print "Object reference is not an eo::Echo"
+ print("Object reference is not an eo::Echo")
sys.exit(1)
# Invoke the echoString operation
message = "Hello from Python"
result = echo.echoString(message)
-print "I said '%s'. The object said '%s'." % (message,result)
+print("I said '%s'. The object said '%s'." % (message,result))
"""
struct S1
s2=eo.S2(s1)
r=echo.echoStruct(s2)
-print r
+print(r)
s3=eo.S3(x=1,y=2,s="aa",b=True,ob=None)
r=echo.echoStruct2(s3)
-print r
+print(r)
ob=echo.createObj(3)
-print ob
+print(ob)
oc=echo.createC()
-print oc
+print(oc)
s3=eo.S3(x=1,y=2,s="aa",b=True,ob=ob)
r=echo.echoStruct2(s3)
-print r
+print(r)
s3=eo.S3(x=1,y=2,s="aa",b=True,ob=oc)
r=echo.echoStruct2(s3)
-print r
+print(r)
r=echo.echoObjectVec([ob,ob])
-print r
+print(r)
r=echo.echoObjectVec([oc,oc])
-print r
+print(r)
r=echo.echoObjectVec([ob,oc])
-print r
+print(r)
#echo.shutdown()
The last node gives the sum of rank n (=2**n) and also a direct calculation of 2**n.
"""
- print """
+ print("""
<proc>
<!-- types -->
<!-- inline -->
<inline name="node_0_0" >
<script><code>
import time
-from decimal import *"""
- print "getcontext().prec = " + str(1+n/3)
- print """
+from decimal import *""")
+ print("getcontext().prec = " + str(1+n/3))
+ print("""
aa=Decimal(a)
bb=Decimal(b)
cc=aa+bb
c=str(cc)
-print "cc=",cc
+print("cc=",cc)
time.sleep(1)
</code></script>
<inport name="a" type="string"/>
<inport name="b" type="string"/>
<outport name="c" type="string"/>
-</inline>"""
+</inline>""")
- print """
+ print("""
<inline name="collect" >
-<script><code>"""
- print "import time"
- print "from decimal import *"
- print "getcontext().prec = " + str(1+n/3)
- print "tot = Decimal(0)"
- print "for i in range (" + str(n+1) + "):"
- print " v='a' + str(i)"
- print " tot+=Decimal(eval(v))"
- print "print tot"
- print "result=str(tot)"
- print "ref=Decimal(2)**" + str(n)
- print "reference=str(ref)"
- print "time.sleep(1)"
- print "</code></script>"
+<script><code>""")
+ print("import time")
+ print("from decimal import *")
+ print("getcontext().prec = " + str(1+n/3))
+ print("tot = Decimal(0)")
+ print("for i in range (" + str(n+1) + "):")
+ print(" v='a' + str(i)")
+ print(" tot+=Decimal(eval(v))")
+ print("print(tot)")
+ print("result=str(tot)")
+ print("ref=Decimal(2)**" + str(n))
+ print("reference=str(ref)")
+ print("time.sleep(1)")
+ print("</code></script>")
for i in range (n+1):
inport='<inport name="a' + str(i) + '" type="string"/>'
- print inport
+ print(inport)
pass
- print '<outport name="result" type="string"/>'
- print '<outport name="reference" type="string"/>'
- print "</inline>"
- print
+ print('<outport name="result" type="string"/>')
+ print('<outport name="reference" type="string"/>')
+ print("</inline>")
+ print()
for i in range (1,n+1):
for j in range (i+1):
node="node_" + str(i) +"_" + str(j)
nodetxt='<node name="'+node+'" type="node_0_0"></node>'
- print nodetxt
+ print(nodetxt)
pass
pass
- print """
+ print("""
<!-- service -->
<!-- control -->
- """
+ """)
for i in range (n):
for j in range (i+1):
tonode2="node_" + str(i+1) +"_" + str(j+1)
control1='<control> <fromnode>'+fromnode+'</fromnode> <tonode>'+tonode1+'</tonode> </control>'
control2='<control> <fromnode>'+fromnode+'</fromnode> <tonode>'+tonode2+'</tonode> </control>'
- print control1
- print control2
+ print(control1)
+ print(control2)
pass
pass
for i in range (n+1):
fromnode="node_" + str(n) +"_" + str(i)
control='<control> <fromnode>'+fromnode+'</fromnode> <tonode>collect</tonode> </control>'
- print control
+ print(control)
pass
- print """
+ print("""
<!-- datalinks -->
- """
+ """)
for i in range (n):
for j in range (i+1):
datafrom='<fromnode>' + fromnode + '</fromnode> <fromport>c</fromport>'
datato1 ='<tonode>' + tonode1 + '</tonode> <toport>b</toport>'
datato2 ='<tonode>' + tonode2 + '</tonode> <toport>a</toport>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato1
- print '</datalink>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato2
- print '</datalink>'
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato1)
+ print('</datalink>')
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato2)
+ print('</datalink>')
pass
pass
for i in range (n+1):
datafrom='<fromnode>' + fromnode + '</fromnode> <fromport>c</fromport>'
toport='a' + str(i)
datato ='<tonode>collect</tonode> <toport>' + toport + '</toport>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato
- print '</datalink>'
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato)
+ print('</datalink>')
- print """
+ print("""
<!--parameters -->
- """
+ """)
- print """
+ print("""
<parameter>
<tonode>node_0_0</tonode> <toport>a</toport>
<value><string>0</string></value>
<tonode>node_0_0</tonode> <toport>b</toport>
<value><string>1</string></value>
</parameter>
- """
+ """)
for i in range (1,n+1):
node1="node_" + str(i) +"_" + str(0)
node2="node_" + str(i) +"_" + str(i)
tonode1 =' <tonode>' + node1 + '</tonode> <toport>a</toport>'
tonode2 =' <tonode>' + node2 + '</tonode> <toport>b</toport>'
- print '<parameter>'
- print tonode1
- print ' <value><string>0</string></value>'
- print '</parameter>'
+ print('<parameter>')
+ print(tonode1)
+ print(' <value><string>0</string></value>')
+ print('</parameter>')
- print '<parameter>'
- print tonode2
- print ' <value><string>0</string></value>'
- print '</parameter>'
+ print('<parameter>')
+ print(tonode2)
+ print(' <value><string>0</string></value>')
+ print('</parameter>')
- print """
+ print("""
</proc>
- """
+ """)
if __name__ == "__main__":
import sys
if rank <2:
raise ValueError("rank must be >1")
except (IndexError, ValueError):
- print usage%(sys.argv[0])
+ print(usage%(sys.argv[0]))
sys.exit(1)
pass
triangle(rank)
<inline name="node_0_0" >
<script><code>
c=a+b
-print c
+print(c)
</code></script>
<inport name="a" type="int"/>
<inport name="b" type="int"/>
The last node gives the sum of rank n (=2**n) and also a direct calculation of 2**n.
"""
- print debut
+ print(debut)
- print """
+ print("""
<inline name="collect" >
-<script><code>"""
- print "tot = 0"
- print "for i in range (" + str(n+1) + "):"
- print " v='a' + str(i)"
- print " tot+=eval(v)"
- print "result=tot"
- print "print result"
- print "reference=2**" + str(n)
- print "print reference"
- print "</code></script>"
+<script><code>""")
+ print("tot = 0")
+ print("for i in range (" + str(n+1) + "):")
+ print(" v='a' + str(i)")
+ print(" tot+=eval(v)")
+ print("result=tot")
+ print("print result")
+ print("reference=2**" + str(n))
+ print("print reference")
+ print("</code></script>")
for i in range (n+1):
inport='<inport name="a' + str(i) + '" type="int"/>'
- print inport
+ print(inport)
pass
- print '<outport name="result" type="int"/>'
- print '<outport name="reference" type="int"/>'
- print "</inline>"
- print
+ print('<outport name="result" type="int"/>')
+ print('<outport name="reference" type="int"/>')
+ print("</inline>")
+ print()
for i in range (1,n+1):
for j in range (i+1):
node="node_" + str(i) +"_" + str(j)
nodetxt='<node name="'+node+'" type="node_0_0"></node>'
- print nodetxt
+ print(nodetxt)
pass
pass
- print """
+ print("""
<!-- service -->
<!-- control -->
- """
+ """)
for i in range (n):
for j in range (i+1):
tonode2="node_" + str(i+1) +"_" + str(j+1)
control1='<control> <fromnode>'+fromnode+'</fromnode> <tonode>'+tonode1+'</tonode> </control>'
control2='<control> <fromnode>'+fromnode+'</fromnode> <tonode>'+tonode2+'</tonode> </control>'
- print control1
- print control2
+ print(control1)
+ print(control2)
pass
pass
- print """
+ print("""
<!-- datalinks -->
- """
+ """)
for i in range (n):
for j in range (i+1):
datafrom='<fromnode>' + fromnode + '</fromnode> <fromport>c</fromport>'
datato1 ='<tonode>' + tonode1 + '</tonode> <toport>b</toport>'
datato2 ='<tonode>' + tonode2 + '</tonode> <toport>a</toport>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato1
- print '</datalink>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato2
- print '</datalink>'
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato1)
+ print('</datalink>')
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato2)
+ print('</datalink>')
pass
pass
datafrom='<fromnode>' + fromnode + '</fromnode> <fromport>c</fromport>'
toport='a' + str(i)
datato ='<tonode>collect</tonode> <toport>' + toport + '</toport>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato
- print '</datalink>'
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato)
+ print('</datalink>')
- print """
+ print("""
<!--parameters -->
- """
+ """)
- print """
+ print("""
<parameter>
<tonode>node_0_0</tonode> <toport>a</toport>
<value><int>0</int></value>
<tonode>node_0_0</tonode> <toport>b</toport>
<value><int>1</int></value>
</parameter>
- """
+ """)
for i in range (1,n+1):
node1="node_" + str(i) +"_" + str(0)
node2="node_" + str(i) +"_" + str(i)
tonode1 =' <tonode>' + node1 + '</tonode> <toport>a</toport>'
tonode2 =' <tonode>' + node2 + '</tonode> <toport>b</toport>'
- print '<parameter>'
- print tonode1
- print ' <value><int>0</int></value>'
- print '</parameter>'
+ print('<parameter>')
+ print(tonode1)
+ print(' <value><int>0</int></value>')
+ print('</parameter>')
- print '<parameter>'
- print tonode2
- print ' <value><int>0</int></value>'
- print '</parameter>'
+ print('<parameter>')
+ print(tonode2)
+ print(' <value><int>0</int></value>')
+ print('</parameter>')
- print """
+ print("""
</proc>
- """
+ """)
if __name__ == "__main__":
import sys
if rank >31:
raise ValueError("rank must be <32")
except (IndexError, ValueError):
- print usage%(sys.argv[0])
+ print(usage%(sys.argv[0]))
sys.exit(1)
pass
triangle(rank)
"""Optional method called on initialization.
The type of "input" is returned by "getTCForAlgoInit"
"""
- print "Algo initialize, input = ", input.getIntValue()
+ print("Algo initialize, input = ", input.getIntValue())
def start(self):
"""Start to fill the pool with samples to evaluate."""
- print "Algo start "
+ print("Algo start ")
self.iter=0
# pushInSample(id, value)
self.pool.pushInSample(self.iter, 1)
currentId=self.pool.getCurrentId()
valIn = self.pool.getCurrentInSample().getIntValue()
valOut = self.pool.getCurrentOutSample().getIntValue()
- print "Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut)
+ print("Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut))
self.iter=self.iter+1
if self.iter < 3:
def finish(self):
"""Optional method called when the algorithm has finished, successfully
or not, to perform any necessary clean up."""
- print "Algo finish"
+ print("Algo finish")
self.pool.destroyAll()
def getAlgoResult(self):
import os
import orbmodule
-import salome_utils
+import salome_utils
clt = orbmodule.client()
FactoryContainer = "/Containers/" + salome_utils.getShortHostName() + "/FactoryServer"
clt.waitNS(FactoryContainer)
-
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import xmlrpclib,sys
+import xmlrpc.client,sys
#example
data="""
</methodCall>
"""
def echo(args):
- print "args=",args
+ print("args=",args)
if not args:
return None
elif len(args) == 1:
else:
return args
-f=open("input")
-data=f.read()
-f.close()
-print data
+with open("input",'r') as f:
+ data=f.read()
+print(data)
class Objref:
"""Wrapper for objrefs """
self.data=data
def __str__(self):
return self.data or ""
- def __cmp__(self, other):
+
+# __cmp__ is not defined in Python 3 : strict ordering
+ def __le__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data <= other
+ def __lt__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data < other
+ def __ge__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data >= other
+ def __gt__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data > other
+ def __eq__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data == other
+ def __ne__(self, other):
if isinstance(other, Binary):
other = other.data
- return cmp(self.data, other)
+ return self.data != other
def decode(self, data):
self.data = data
out.write(self.data or "")
out.write("</objref></value>\n")
-xmlrpclib.WRAPPERS=xmlrpclib.WRAPPERS+(Objref,)
+xmlrpc.client.WRAPPERS=xmlrpc.client.WRAPPERS+(Objref,)
def end_objref(self,data):
self.append(Objref(data))
self._value=0
-xmlrpclib.Unmarshaller.end_objref=end_objref
-xmlrpclib.Unmarshaller.dispatch["objref"]=end_objref
+xmlrpc.client.Unmarshaller.end_objref=end_objref
+xmlrpc.client.Unmarshaller.dispatch["objref"]=end_objref
-params, method = xmlrpclib.loads(data)
+params, method = xmlrpc.client.loads(data)
try:
- call=eval(method)
- response=call(params)
- response = (response,)
+ call=eval(method)
+ response=call(params)
+ response = (response,)
except:
- # report exception back to server
- response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2]))
+ # report exception back to server
+ response = xmlrpc.client.dumps( xmlrpc.client.Fault(1, "%s:%s" % sys.exc_info()[:2]))
else:
- response = xmlrpclib.dumps( response, methodresponse=1)
+ response = xmlrpc.client.dumps( response, methodresponse=1)
-print response
-f=open("output",'w')
-f.write(response)
-f.close()
+print(response)
+with open("output",'w') as f:
+ f.write(response)
{
XML_SetUserData(saxContext,pp);
_stackParser.push(pp);
- DEBTRACE("parser::SetUserDataAndPush, stack size: " << sp.size());
+ DEBTRACE("parser::SetUserDataAndPush, stack size: " << pp->_level);
}
void parser::onEnd(const XML_Char *el, parser* child)
INCLUDE_DIRECTORIES(
${CPPUNIT_INCLUDE_DIRS}
${PTHREADS_INCLUDE_DIRS}
+ ${OMNIORBPY_INCLUDE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/
${CMAKE_CURRENT_SOURCE_DIR}/..
${CMAKE_CURRENT_SOURCE_DIR}/../../bases
-->
<proc name="proc">
- <property name="DefaultStudyID" value="1"/>
<type name="bool" kind="bool"/>
<type name="double" kind="double"/>
<type name="string" kind="string"/>
<property name="workingdir" value=""/>
</container>
<datanode name="StudyInNode0" kind="study">
- <property name="StudyID" value="1"/>
<parameter name="a" type="GEOM_Object" ref="/Geometry/Box_1"/>
<parameter name="b" type="GEOM_Object" ref="/Geometry/Sphere_1"/>
</datanode>
<outport name="return" type="GEOM_Object"/>
</service>
<outnode name="StudyOutNode0" kind="study">
- <property name="StudyID" value="1"/>
<parameter name="a" type="GEOM_Object" ref="/Geometry/YacsFuse"/>
</outnode>
- <service name="SalomeNode1">
- <node>SalomeNode0</node>
- <method>SetStudyID</method>
- <inport name="theStudyID" type="Int"/>
- </service>
<control> <fromnode>StudyInNode0</fromnode> <tonode>PyScript0</tonode> </control>
- <control> <fromnode>StudyInNode0</fromnode> <tonode>SalomeNode1</tonode> </control>
<control> <fromnode>PyScript0</fromnode> <tonode>SalomeNode0</tonode> </control>
<control> <fromnode>SalomeNode0</fromnode> <tonode>StudyOutNode0</tonode> </control>
- <control> <fromnode>SalomeNode1</fromnode> <tonode>SalomeNode0</tonode> </control>
<datalink control="false">
<fromnode>StudyInNode0</fromnode> <fromport>a</fromport>
<tonode>PyScript0</tonode> <toport>a</toport>
<fromnode>SalomeNode0</fromnode> <fromport>return</fromport>
<tonode>StudyOutNode0</tonode> <toport>a</toport>
</datalink>
- <parameter>
- <tonode>SalomeNode1</tonode><toport>theStudyID</toport>
- <value><int>1</int></value>
- </parameter>
</proc>
<inline name="node98" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="objvec"/>
</inline>
<inline name="node1" state="disabled">
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="int"/>
</inline>
<inline name="node11" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="string"/>
</inline>
<inline name="node12" >
<script>
- <code>print p1</code>
- <code>print "coucou"</code>
+ <code>print(p1)</code>
+ <code>print("coucou")</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<inline name="node13" >
<script>
- <code><![CDATA[print p1]]></code>
- <code><![CDATA[print "coucou"]]> </code>
+ <code><![CDATA[print(p1)]]></code>
+ <code><![CDATA[print("coucou")]]> </code>
<code><![CDATA[a=1/0]]> </code>
</script>
<inport name="p1" type="dblevecvec"/>
<script>
<code>import eo</code>
<code>obj=obj._narrow(eo.Echo)</code>
- <code>print p1</code>
- <code>print obj</code>
+ <code>print(p1)</code>
+ <code>print(obj)</code>
<code>p2=obj.echoC(p1)</code>
- <code>print p2</code>
+ <code>print(p2)</code>
</script>
<inport name="p1" type="eo/C"/>
<inport name="obj" type="Echo"/>
</inline>
<inline name="node34" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="eo/C"/>
<outport name="p2" type="eo/C"/>
</inline>
<inline name="node35" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="eo/C"/>
<outport name="p2" type="eo/C"/>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
- <code> print "coucou b1.b2.node1" </code>
+ <code> print(p1);p1=2*p1 </code>
+ <code> print("coucou b1.b2.node1") </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="node1" >
<function name="f">
<code> def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="node2" >
<function name="f">
<code>def f(s1):</code>
- <code> print s1 </code>
+ <code> print(s1) </code>
<code> return s1 </code>
</function>
<inport name="s1" type="dblevec"/>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="boolvec"/>
<outport name="p1" type="boolvec"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="boolvec"/>
<outport name="p1" type="boolvec"/>
-->
<proc name="proc">
- <property name="DefaultStudyID" value="1"/>
<objref name="CALCIUM_integer" id="IDL:CALCIUM_integer:1.0"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<inline name="pyth1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<inline name="pyth2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<inline name="pyth3" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<inline name="pyth4" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</foreach>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
<outport name="p1" type="dblevec"/>
</datanode>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<bloc name="b">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
<outport name="p1" type="dblevec"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
<outport name="p1" type="dblevec"/>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>#a=1/0</code>
</script>
<outport name="p1" type="string"/>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>#a=1/0</code>
</script>
<inport name="p1" type="string"/>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>a=1/0</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<!-- service -->
<inline name="node1" >
- <script><code>print p1;p1=2*p1</code></script>
+ <script><code>print(p1);p1=2*p1</code></script>
<inport name="p1" type="string"/>
<outport name="p1" type="string"/>
</inline>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="node3" >
<script>
- <code>print "node3:",p1</code>
+ <code>print("node3:",p1)</code>
</script>
<inport name="p1" type="file"/>
</inline>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
</bloc>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
</inline>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
</foreach>
<inline name="node3" >
<script>
- <code>print "coucou"</code>
+ <code>print("coucou")</code>
</script>
</inline>
<service name="node4" >
</bloc>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="intvecvec"/>
<outport name="p1" type="intvecvec"/>
</inline>
<inline name="node3" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="intvecvec"/>
</inline>
-->
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
runs[run].append(medFile)
runs[run].append(meshName)
pass
-print "There is(are) ",numberOfRun," runs of Fake Compo on process ",os.getpid()
+print("There is(are) ",numberOfRun," runs of Fake Compo on process ",os.getpid())
]]></code></script>
<outport name="numberOfRun" type="int"/>
<outport name="runs" type="seqpyobj"/>
<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="schema">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<function name="f">
<code>import time</code>
<code>def f(p1):</code>
- <code> print "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ start ", p1</code>
+ <code> print("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ start ", p1)</code>
<code> time.sleep(0.1)</code>
- <code> print "----------------------------------------- stop ", p1</code>
+ <code> print("----------------------------------------- stop ", p1)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="Schema">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<foreach name="ForEachLoop" nbranch="4" type="int">
<initnode>
<inline name="initScript">
- <script><code><![CDATA[print "initnode"
+ <script><code><![CDATA[print("initnode")
o1=7
]]></code></script>
<outport name="o1" type="int"/>
</inline>
<finalizenode>
<inline name="finalizeScript">
- <script><code><![CDATA[print "finalizenode"
+ <script><code><![CDATA[print("finalizenode")
]]></code></script>
<inport name="i2" type="int"/>
</inline>
</datalink>
</foreach>
<inline name="PostProc">
- <script><code><![CDATA[print "Post-traitement"
+ <script><code><![CDATA[print("Post-traitement")
for x in i5:
- print x
+ print(x)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i5" type="seqint"/>
<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="Schema">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print "a=",a</code>
+ <code> print("a=",a)</code>
<code> a=a+p1</code>
- <code> print "a=",a</code>
+ <code> print("a=",a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print "a:",a</code>
+ <code> print("a:",a)</code>
<code> a=a+p1</code>
- <code> print "p1:",p1</code>
+ <code> print("p1:",p1)</code>
<code><![CDATA[ condition=(p1 < 40.)]]> </code>
<code> return p1,condition</code>
</function>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<!--nodes -->
<datanode name="s" kind="study" >
- <property name="StudyID" value="1" />
<parameter name="b" type="FIELDDOUBLE" ref="0:1:1:3:2:1"/>
</datanode>
<datanode name="d" >
<script>
<code>import SALOME_MED</code>
<code>p1=p1._narrow(SALOME_MED.FIELD)</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="FIELDDOUBLE"/>
<outport name="p1" type="FIELDDOUBLE"/>
<inline name="pyth0" >
<script>
- <code>print "MEDFIELD:",p1</code>
+ <code>print (MEDFIELD:",p1)</code>
<code>p1.Register()</code>
</script>
<inport name="p1" type="FIELDDOUBLE"/>
<inline name="pyth1" >
<script>
- <code>print "MEDFIELD:",p1</code>
+ <code>print("MEDFIELD:",p1)</code>
</script>
<inport name="p1" type="FIELDDOUBLE"/>
</inline>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="intvec"/>
<outport name="p1" type="intvec"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="intvec"/>
<outport name="p1" type="intvec"/>
<inline name="poly_7" >
<script>
<code>Pn=(429*x**7 -693*x**5+315*x**3 -35*x)/16</code>
- <code>print "reference P7=",Pn</code>
+ <code>print("reference P7=",Pn)</code>
</script>
<inport name="x" type="double"/>
<outport name="Pn" type="double"/>
<inline name="iter1" >
<script>
<code>Pn = ((2*n-1)*x*Pnm1 -(n-1)*Pnm2)/n</code>
- <code>print "n=",n," Pn=",Pn</code>
+ <code>print("n=",n," Pn=",Pn)</code>
<code>n=n+1</code>
</script>
<inport name="Pnm1" type="double"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="objvec"/>
<outport name="p1" type="objvec"/>
<foreach name="foreach4" nbranch="3" type="Obj" >
<inline name="pyth" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="Obj"/>
<outport name="p1" type="Obj"/>
<inline name="pyth7" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="objvec"/>
<outport name="p1" type="objvec"/>
<inline name="pyth0" >
<script>
- <code>print "p1",p1</code>
- <code>print "p2",p2</code>
+ <code>print("p1",p1)</code>
+ <code>print("p2",p2)</code>
<code>p1=[p1,p2,p2,p1]</code>
</script>
<inport name="p1" type="Obj"/>
<inline name="node2" >
<script >
<code>p1= p1+10.</code>
- <code>print "node2:",p1</code>
+ <code>print("node2:",p1)</code>
<code>#a=p1/0</code>
<code>p1=5</code>
</script>
<inline name="node2" >
<script >
<code>p1= p1+10.</code>
- <code>print "node2:",p1</code>
+ <code>print("node2:",p1)</code>
<code>#a=p1/0</code>
<code>p1=5</code>
</script>
-->
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<optimizer name="OptimizerLoop1" nbranch="1" lib="libTestOptLoop" entry="createOptimizerAlgASyncExample">
<inline name="PyScript7">
<script><code><![CDATA[o9 = int(i8)
-print "traitement:", i8
+print("traitement:", i8)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i8" type="double"/>
-->
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<optimizer name="OptimizerLoop1" nbranch="1" lib="algoasyncexample.py" entry="myalgoasync">
<inline name="PyScript7">
<script><code><![CDATA[o9 = int(i8)
-print "traitement:", i8
+print("traitement:", i8)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i8" type="double"/>
<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="optim">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
-->
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<optimizer name="OptimizerLoop1" nbranch="1" lib="libTestOptLoop" entry="createOptimizerAlgSyncExample">
<inline name="PyScript7">
<script><code><![CDATA[o9 = int(i8)
-print "traitement:", i8
+print("traitement:", i8)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i8" type="double"/>
-->
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<optimizer name="OptimizerLoop1" nbranch="1" lib="algosyncexample.py" entry="myalgosync">
<inline name="PyScript7">
<script><code><![CDATA[o9 = int(i8)
-print "traitement:", i8
+print("traitement:", i8)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i8" type="double"/>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="int"/>
</inline>
<inline name="node11" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="string"/>
</inline>
<inline name="node12" >
<script>
- <code>print p1</code>
- <code>print "coucou"</code>
+ <code>print(p1)</code>
+ <code>print("coucou")</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<inline name="node13" >
<script>
- <code><![CDATA[print p1]]></code>
- <code><![CDATA[print "coucou"]]> </code>
+ <code><![CDATA[print(p1)]]></code>
+ <code><![CDATA[print("coucou")]]> </code>
</script>
<inport name="p1" type="dblevecvec"/>
<outport name="p1" type="dblevecvec"/>
<script>
<code>import eo</code>
<code>obj=obj._narrow(eo.Echo)</code>
- <code>print p1</code>
- <code>print obj</code>
+ <code>print(p1)</code>
+ <code>print(obj)</code>
<code>p2=obj.echoC(p1)</code>
- <code>print p2</code>
+ <code>print(p2)</code>
</script>
<inport name="p1" type="C"/>
<inport name="obj" type="Echo"/>
</inline>
<inline name="node34" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="C"/>
<outport name="p2" type="C"/>
</inline>
<inline name="node35" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="C"/>
<outport name="p2" type="C"/>
-->
<proc name="TestDistPython2">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<function name="ff2">
<code><![CDATA[
def ff2(x,a):
- print "coucou, x=",x
- print "coucou, a=",a
- print my_container
+ print("coucou, x=",x)
+ print("coucou, a=",a)
+ print(my_container)
return x+" OK ca marche"+str(a),2*a+4.7
]]></code>
</function>
</remote>
<inline name="node2">
<script><code><![CDATA[
-print "dans node2 p1=",p1
-print "dans node2 p2=",p2
+print("dans node2 p1=",p1)
+print("dans node2 p2=",p2)
]]></code></script>
<inport name="p1" type="string"/>
<inport name="p2" type="double"/>
-->
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<code><![CDATA[import time
def f():
- print my_container
- for n in xrange(15):
- print time.time()
+ print(my_container)
+ for n in range(15):
+ print(time.time())
time.sleep(1)
]]></code>
<function name="f">
<code><![CDATA[import time
def f():
- print my_container
- for n in xrange(15):
- print time.time()
+ print(my_container)
+ for n in range(15):
+ print(time.time())
time.sleep(1)
]]></code>
</function>
-->
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<code><![CDATA[import time
def f(i5):
- print my_container
- print "nouvelle branche avec ", i5
- for n in xrange(15):
- print time.time()
+ print(my_container)
+ print("nouvelle branche avec ", i5)
+ for n in range(15):
+ print(time.time())
time.sleep(1)
]]></code>
-->
<proc name="TestDistPython2">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<remote name="Node6">
<script>
<code><![CDATA[
-print "coucou, x=",x
-print "coucou, a=",a
-print "my_container=",my_container
+print("coucou, x=",x)
+print("coucou, a=",a)
+print("my_container=",my_container)
y= x+" OK ca marche"+str(a)
z=2*a+4.7
-print y,z
+print(y,z)
]]></code>
</script>
<load container="cont1"/>
</remote>
<inline name="node2">
<script><code><![CDATA[
-print "dans node2 p1=",p1
-print "dans node2 p2=",p2
+print("dans node2 p1=",p1)
+print("dans node2 p2=",p2)
]]></code></script>
<inport name="p1" type="string"/>
<inport name="p2" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> a=a+1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="int"/>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="int"/>
</inline>
<inline name="node11" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="string"/>
</inline>
<inline name="node12" >
<script>
- <code>print p1</code>
- <code>print "coucou"</code>
+ <code>print(p1)</code>
+ <code>print("coucou")</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<inline name="node13" >
<script>
- <code><![CDATA[print p1]]></code>
- <code><![CDATA[print "coucou"]]> </code>
+ <code><![CDATA[print(p1)]]></code>
+ <code><![CDATA[print("coucou")]]> </code>
</script>
<inport name="p1" type="dblevecvec"/>
<outport name="p1" type="dblevecvec"/>
<script>
<code>import eo</code>
<code>obj=obj._narrow(eo.Echo)</code>
- <code>print p1</code>
- <code>print obj</code>
+ <code>print(p1)</code>
+ <code>print(obj)</code>
<code>p2=obj.echoC(p1)</code>
- <code>print p2</code>
+ <code>print(p2)</code>
</script>
<inport name="p1" type="C"/>
<inport name="obj" type="Echo"/>
</inline>
<inline name="node34" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="C"/>
<outport name="p2" type="C"/>
</inline>
<inline name="node35" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="C"/>
<outport name="p2" type="C"/>
<code>orb = CORBA.ORB_init([], CORBA.ORB_ID)</code>
<code>lcc = LifeCycleCORBA(orb)</code>
<code>naming_service = SALOME_NamingServicePy_i(orb)</code>
- <code>StudyManager = naming_service.Resolve('myStudyManager')</code>
<code>aVisu = lcc.FindOrLoadComponent("FactoryServer","VISU")</code>
- <code>aStudy = StudyManager.GetStudyByID(1)</code>
- <code>aVisu.SetCurrentStudy(aStudy)</code>
<code>aViewManager=aVisu.GetViewManager()</code>
<code>aView=aViewManager.Create3DView()</code>
<code>medFile = os.getenv('DATA_DIR') + '/MedFiles/' + "TimeStamps.med" </code>
<inport name="box" type="GEOM_Object"/>
<outport name="box" type="GEOM_Object"/>
</service>
- <service name="node51" >
- <component>GEOM_Superv</component>
- <method>SetStudyID</method>
- <inport name="id" type="int"/>
- </service>
<service name="node52" >
<component>PYHELLO</component>
<method>makeBanner</method>
<control> <fromnode>node5</fromnode> <tonode>node62</tonode> </control>
<control> <fromnode>node5</fromnode> <tonode>node63</tonode> </control>
<control> <fromnode>node13</fromnode> <tonode>node14</tonode> </control>
- <control> <fromnode>node44</fromnode> <tonode>node51</tonode> </control>
- <control> <fromnode>node51</fromnode> <tonode>node49</tonode> </control>
<control> <fromnode>node49</fromnode> <tonode>node50</tonode> </control>
<control> <fromnode>node36</fromnode> <tonode>node37</tonode> </control>
<!-- datalinks -->
<parameter><tonode>node37</tonode><toport>p4</toport><value><string>vitesse</string></value></parameter>
<parameter><tonode>node37</tonode><toport>p5</toport><value><double>0.</double></value></parameter>
<parameter><tonode>node52</tonode><toport>nom</toport><value><string>toto</string></value></parameter>
-<parameter><tonode>node51</tonode><toport>id</toport><value><int>1</int></value></parameter>
<parameter><tonode>node49</tonode> <toport>x1</toport><value><double>0</double></value></parameter>
<parameter><tonode>node49</tonode> <toport>y1</toport><value><double>0</double></value></parameter>
<parameter><tonode>node49</tonode> <toport>z1</toport><value><double>0</double></value></parameter>
<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
msg += "refOutput - output : %f - %f \n"%(refOutput, output);
msg += "Got abs relative diff %f .\n"%err
ret = False;
- print msg;
+ print(msg)
pass
-#print "+++ OK " , i , " +++", ret
+#print("+++ OK " , i , " +++", ret)
]]></code></script>
<inport name="i" type="int"/>
<inport name="refOutputs" type="pyobj"/>
<inline name="PyBuildLoopIndex">
<function name="make_indexes">
<code><![CDATA[def make_indexes(inVal, outVal) :
- print "In make_indexes" ;
+ print("In make_indexes")
if ( len(inVal) != len(outVal) ) :
msg = "len(inVal) (%i) != len(outVal) (%i). "%( len(inVal), len(outVal) ) ;
raise ValueError(msg)
myFunc = "pyFunc";
myHeader = "Function processed in YACCS";
myCode = pmmlObj.ExportPyStr(myFunc, myHeader);
-exec myCode;
+exec(myCode);
]]></code></script>
<inport name="filename" type="string"/>
<inport name="modelname" type="string"/>
<outport name="filepath" type="string"/>
</inline>
<inline name="PyGetRes">
- <script><code><![CDATA[print "retVec ";
-print retVec;
+ <script><code><![CDATA[print("retVec ");
+print(retVec);
res = "True";
for ret in retVec:
if not ret:
<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
if errLR > epsilon or errANN > epsilon:
msg += "KO valid with eps %f at pattern #%i: \n"%(epsilon, i) ;
ret = False;
- print msg;
+ print(msg);
pass
-print "+++ OK " , i , " +++", ret
+print("+++ OK " , i , " +++", ret)
]]></code></script>
<inport name="i" type="int"/>
<inport name="refOutputsLR" type="pyobj"/>
myFunc = "pyFunc";
myHeader = "Function processed in YACCS";
myCode = pmmlObj.ExportPyStr(myFunc, myHeader);
-exec myCode;
+exec(myCode);
]]></code></script>
<inport name="filename" type="string"/>
<inport name="modelname" type="string"/>
myFunc = "pyFunc";
myHeader = "Function processed in YACCS";
myCode = pmmlObj.ExportPyStr(myFunc, myHeader);
-exec myCode;
+exec(myCode);
]]></code></script>
<inport name="filename" type="string"/>
<inport name="modelname" type="string"/>
<inline name="PyBuildLoopIndex0">
<function name="make_indexes">
<code><![CDATA[def make_indexes(inVal, outVal_LR, outVal_ANN) :
- print "In make_indexes" ;
+ print("In make_indexes") ;
if ( len(inVal) != len(outVal_LR) ) :
msg = "len(inVal) (%i) != len(outVal_LR) (%i). "%( len(inVal), len(outVal_LR) ) ;
<outport name="filepath" type="string"/>
</inline>
<inline name="PyGetRes">
- <script><code><![CDATA[print "retVec ";
-print retVec;
+ <script><code><![CDATA[print("retVec ");
+print(retVec);
res = "True";
for ret in retVec:
if not ret:
<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
msg += "refOutput - output : %f - %f \n"%(refOutput, output);
msg += "Got abs relative diff %f .\n"%err
ret = False;
- print msg;
+ print(msg);
pass
-#print "+++ OK " , i , " +++", ret
+#print("+++ OK " , i , " +++", ret)
]]></code></script>
<inport name="i" type="int"/>
<inport name="refOutputs" type="pyobj"/>
<inline name="PyBuildLoopIndex">
<function name="make_indexes">
<code><![CDATA[def make_indexes(inVal, outVal) :
- print "In make_indexes" ;
+ print("In make_indexes") ;
if ( len(inVal) != len(outVal) ) :
msg = "len(inVal) (%i) != len(outVal) (%i). "%( len(inVal), len(outVal) ) ;
raise ValueError(msg)
myFunc = "pyFunc";
myHeader = "Function processed in YACCS";
myCode = pmmlObj.ExportPyStr(myFunc, myHeader);
-exec myCode;
+exec(myCode);
]]></code></script>
<inport name="filename" type="string"/>
<inport name="modelname" type="string"/>
<outport name="filepath" type="string"/>
</inline>
<inline name="PyGetRes">
- <script><code><![CDATA[print "retVec ";
-print retVec;
+ <script><code><![CDATA[print("retVec ");
+print(retVec);
res = "True";
for ret in retVec:
if not ret:
<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
msg += "refOutput - output : %f - %f \n"%(refOutput, output);
msg += "Got abs relative diff %f .\n"%err
ret = False;
- print msg;
+ print(msg);
pass
-print "+++ OK " , i , " +++", ret
+print("+++ OK " , i , " +++", ret)
]]></code></script>
<inport name="i" type="int"/>
<inport name="refOutputs" type="pyobj"/>
<inline name="PyBuildLoopIndex">
<function name="make_indexes">
<code><![CDATA[def make_indexes(inVal, outVal) :
- print "In make_indexes" ;
+ print("In make_indexes") ;
if ( len(inVal) != len(outVal) ) :
msg = "len(inVal) (%i) != len(outVal) (%i). "%( len(inVal), len(outVal) ) ;
raise ValueError(msg)
myFunc = "pyFunc";
myHeader = "Function processed in YACCS";
myCode = pmmlObj.ExportPyStr(myFunc, myHeader);
-exec myCode;
+exec(myCode);
]]></code></script>
<inport name="filename" type="string"/>
<inport name="modelname" type="string"/>
<outport name="filepath" type="string"/>
</inline>
<inline name="PyGetRes">
- <script><code><![CDATA[print "retVec ";
-print retVec;
+ <script><code><![CDATA[print("retVec ");
+print(retVec);
res = "True";
for ret in retVec:
if not ret:
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import HELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "HELLO")</code>
- <code> print compo.hello(salome.myStudy, p1)</code>
- <code> print p1</code>
+ <code> print(compo.hello(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<inport name="p1" type="string"/>
</sinline>
<code>salome.salome_init()</code>
<code>import HELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "HELLO")</code>
- <code> print compo.hello(salome.myStudy, p1)</code>
- <code> print p1</code>
+ <code> print(compo.hello(p1))</code>
+ <code> print(p1)</code>
</function>
<inport name="p1" type="string"/>
</sinline>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>import salome</code>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
- <code>print __container__from__YACS__</code>
+ <code>print(__container__from__YACS__)</code>
<code>machine,container=__container__from__YACS__.split('/')</code>
<code>param={}</code>
<code>param['hostname']=machine</code>
<code>param['container_name']=container</code>
<code>compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
<code>def f(p1):</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import HELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "HELLO")</code>
- <code> print compo.hello(salome.myStudy, p1)</code>
- <code> print p1</code>
+ <code> print(compo.hello(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<inport name="p1" type="string"/>
</sinline>
<code>salome.salome_init()</code>
<code>import HELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "HELLO")</code>
- <code> print compo.hello(salome.myStudy, p1)</code>
- <code> print p1</code>
+ <code> print(compo.hello(p1))</code>
+ <code> print(p1)</code>
</function>
<inport name="p1" type="string"/>
</sinline>
<code>import salome</code>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
- <code>print __container__from__YACS__</code>
+ <code>print(__container__from__YACS__)</code>
<code>machine,container=__container__from__YACS__.split('/')</code>
<code>param={}</code>
<code>param['hostname']=machine</code>
<code>param['container_name']=container</code>
<code>compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
<code>def f(p1):</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
<code> return p1</code>
</function>
<load container="A"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="strvec"/>
</inline>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="strvec"/>
<outport name="p1" type="strvec"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="strvec"/>
<outport name="p1" type="strvec"/>
<inline name="pyth3" >
<script>
- <code>print s1</code>
+ <code>print(s1)</code>
</script>
<inport name="s1" type="eo/S2"/>
</inline>
<inline name="pyth9" >
<script>
- <code>print s1</code>
+ <code>print(s1)</code>
</script>
<inport name="s1" type="eo/S2"/>
</inline>
<inline name="pyth2" >
<script>
- <code>print s1</code>
+ <code>print(s1)</code>
</script>
<inport name="s1" type="eo/S2"/>
</inline>
<inline name="pyth0" >
<script>
- <code>print s1</code>
- <code>print t1</code>
+ <code>print(s1)</code>
+ <code>print(t1)</code>
</script>
<inport name="p1" type="double"/>
<inport name="s1" type="eo/S2"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
<outport name="p1" type="dblevec"/>
<!--nodes -->
<datanode name="s" kind="study" >
- <property name="StudyID" value="1" />
<parameter name="b" type="GEOM/GEOM_Object" ref="0:1:2:2"/>
<parameter name="c" type="bool" ref="/Geometry/Box_1"/>
</datanode>
<script>
<code>import GEOM</code>
<code>p1=p1._narrow(GEOM.GEOM_Object)</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="GEOM/GEOM_Object"/>
<outport name="p1" type="GEOM/GEOM_Object"/>
</inline>
<outnode name="os" kind="study" ref="stud1.hdf" >
- <property name="StudyID" value="3" />
<parameter name="b" type="GEOM/GEOM_Object" ref="/Save/x"/>
<!-- <parameter name="c" type="GEOM/GEOM_Object" ref="/Geometry/Box_2"/>
<parameter name="b" type="GEOM/GEOM_Object" ref="0:1:1:6"/>
<switch name="b1" select="3" >
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
-->
<proc name="proc">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<struct name="Engines/dataref">
<member name="ref" type="string"/>
<outport name="select" type="int"/>
</inline>
<inline name="n2">
- <script><code><![CDATA[print p1]]></code></script>
+ <script><code><![CDATA[print(p1)]]></code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<switch name="b1">
<default>
<inline name="n2">
- <script><code><![CDATA[print p1]]></code></script>
+ <script><code><![CDATA[print(p1)]]></code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</default>
<case id="1">
<inline name="n2">
- <script><code><![CDATA[print p1]]></code></script>
+ <script><code><![CDATA[print(p1)]]></code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</default>
<case id="1">
<inline name="n2">
- <script><code><![CDATA[print p1
+ <script><code><![CDATA[print(p1)
p1=p1+20
condition=p1 < 40. ]]></code></script>
<inport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<case id="3">
<bloc name="b">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<case id="3">
<forloop name="b" nsteps="2">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<while name="b" >
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>p1=p1+20</code>
<code><![CDATA[condition=p1 < 90.]]> </code>
</script>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<case id="1">
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>p1=p1+20</code>
<code><![CDATA[condition=p1 < 40.]]> </code>
</script>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<inline name="node_0_0" >
<script><code>
c=a+b
-print c
+print(c)
</code></script>
<inport name="a" type="int"/>
<inport name="b" type="int"/>
<inline name="node_3_0" >
<script><code>
c=a+b/0
-print c
+print(c)
</code></script>
<inport name="a" type="int"/>
<inport name="b" type="int"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print "p1:",p1</code>
+ <code> print("p1:",p1)</code>
<code><![CDATA[ condition=p1 < 40.]]> </code>
<code> return p1,condition</code>
</function>
<code><![CDATA[def f(p1):]]> </code>
<code><![CDATA[ global a]]> </code>
<code><![CDATA[ p1= p1+10.]]> </code>
- <code><![CDATA[ print a]]> </code>
+ <code><![CDATA[ print(a)]]> </code>
<code><![CDATA[ a=a+p1]]> </code>
- <code><![CDATA[ print "a:",a]]> </code>
+ <code><![CDATA[ print("a:",a)]]> </code>
<code><![CDATA[ condition=p1 < 50.]]> </code>
<code><![CDATA[ return p1,condition]]> </code>
</function>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print "p1:",p1</code>
+ <code> print("p1:",p1)</code>
<code><![CDATA[ condition=p1 < 40.]]> </code>
<code> return p1,condition</code>
</function>
${PROJECT_SOURCE_DIR}/src/yacsloader
${PROJECT_BINARY_DIR}/src/engine_swig
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIRS}
)
"""Optional method called on initialization.
The type of "input" is returned by "getTCForAlgoInit"
"""
- print "Algo initialize, input = ", input.getIntValue()
+ print("Algo initialize, input = ", input.getIntValue())
def start(self):
"""Start to fill the pool with samples to evaluate."""
- print "Algo start "
+ print("Algo start ")
self.iter=0
# pushInSample(id, value)
self.pool.pushInSample(self.iter, 1)
currentId=self.pool.getCurrentId()
valIn = self.pool.getCurrentInSample().getIntValue()
valOut = self.pool.getCurrentOutSample().getIntValue()
- print "Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut)
+ print("Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut))
self.iter=self.iter+1
if self.iter < 3:
def finish(self):
"""Optional method called when the algorithm has finished, successfully
or not, to perform any necessary clean up."""
- print "Algo finish"
+ print("Algo finish")
self.pool.destroyAll()
def getAlgoResult(self):
def test1_edit(self):
p = self.r.createProc("pr")
- print p.typeMap
+ print(p.typeMap)
t=p.getTypeCode("double")
- print t.kind()
+ print(t.kind())
t=p.typeMap["double"]
td=p.createType("double","double")
ti=p.createType("int","int")
tc1=p.createInterfaceTc("","Obj",[])
- print tc1.name(),tc1.id()
+ print(tc1.name(),tc1.id())
tc2=p.createInterfaceTc("","Obj2",[tc1])
- print tc2.name(),tc2.id()
+ print(tc2.name(),tc2.id())
tc3=p.createSequenceTc("","seqdbl",td)
- print tc3.name(),tc3.id(),tc3.contentType()
+ print(tc3.name(),tc3.id(),tc3.contentType())
tc4=p.createSequenceTc("","seqObj2",tc2)
tc5=p.createSequenceTc("","seqint",ti)
- print tc4.name(),tc4.id()
- print tc4.isA(tc1),0
- print tc2.isA(tc1),1
- print tc1.isA(tc2),0
- print td.isA(ti),0
- print td.isAdaptable(ti),1
- print ti.isAdaptable(td),0
- print tc5.isAdaptable(tc3),0
- print tc3.isAdaptable(tc5),1
+ print(tc4.name(),tc4.id())
+ print(tc4.isA(tc1),0)
+ print(tc2.isA(tc1),1)
+ print(tc1.isA(tc2),0)
+ print(td.isA(ti),0)
+ print(td.isAdaptable(ti),1)
+ print(ti.isAdaptable(td),0)
+ print(tc5.isAdaptable(tc3),0)
+ print(tc3.isAdaptable(tc5),1)
n=self.r.createScriptNode("","node1")
- n.setScript("print 'coucou1'")
+ n.setScript("print('coucou1')")
n.edAddInputPort("p1",ti)
n.edAddOutputPort("p1",ti)
p.edAddChild(n)
retex=None
try:
inport.edInitXML("<value><intt>5</int></value>")
- except ValueError, ex:
- print "Value Error: ", ex
+ except ValueError as ex:
+ print("Value Error: ", ex)
retex=ex
- except pilot.Exception,ex:
- print "YACS exception:",ex.what()
+ except pilot.Exception as ex:
+ print("YACS exception:",ex.what())
retex=ex.what()
- self.assert_(retex is not None, "exception not raised, or wrong type")
+ self.assertTrue(retex is not None, "exception not raised, or wrong type")
inport.edInitXML("<value><int>5</int></value>")
# --- create script node node2
n2=self.r.createScriptNode("","node2")
- n2.setScript("print 'coucou2'")
+ n2.setScript("print('coucou2')")
n2.edAddInputPort("p1",ti)
p.edAddChild(n2)
# --- end of node
n=self.r.createFuncNode("","node3")
n.setScript("""
def f():
- print 'coucou3'
+ print('coucou3')
""")
n.setFname("f")
p.edAddChild(n)
p.edAddChild(b)
n=self.r.createScriptNode("","b1.node2")
- n.setScript("print 'coucou2'")
+ n.setScript("print('coucou2')")
b.edAddChild(n)
# --- end bloc
ip.edInitInt(3)
n=self.r.createScriptNode("","l1.node2")
- n.setScript("print 'coucou2'")
+ n.setScript("print('coucou2')")
lo.edSetNode(n)
# --- end loop
n=self.r.createFuncNode("","w1.node3")
n.setScript("""
def f():
- print 'coucou3'
+ print('coucou3')
return 0
""")
n.setFname("f")
n=self.r.createFuncNode("","sw1.node3")
n.setScript("""
def f():
- print 'case1'
+ print('case1')
return 0
""")
n.setFname("f")
n=self.r.createFuncNode("","sw1.node4")
n.setScript("""
def f():
- print 'default'
+ print('default')
return 0
""")
n.setFname("f")
try:
self.e.RunW(p,0)
- except pilot.Exception,ex:
- print ex.what()
+ except pilot.Exception as ex:
+ print(ex.what())
self.fail(ex)
#self.e.displayDot(p)
if __name__ == '__main__':
import os
U = os.getenv('USER')
- f=open("/tmp/" + U + "/UnitTestsResult", 'a')
- f.write(" --- TEST src/yacsloader: testEdit.py\n")
- suite = unittest.makeSuite(TestEdit)
- result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
- f.close()
+ with open("/tmp/" + U + "/UnitTestsResult", 'a') as f:
+ f.write(" --- TEST src/yacsloader: testEdit.py\n")
+ suite = unittest.makeSuite(TestEdit)
+ result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
sys.exit(not result.wasSuccessful())
def test1_StepByStep(self):
# --- execution step by step
- print "================= Start of STEPBYSTEP ==================="
+ print("================= Start of STEPBYSTEP ===================")
self.e.setExecMode(1) # YACS::STEPBYSTEP
run1 = threading.Thread(None, self.e.RunPy, "stepbystep", (self.p,0))
self.e.waitPause()
#e.displayDot(p)
bp = self.e.getTasksToLoad()
- print "nexts possible steps = ", bp
+ print("nexts possible steps = ", bp)
if len(bp) > 0:
tte= bp[-1:] # only one node at each step, the last one in the list
r = self.e.setStepsToExecute(tte)
else:
tocont = False
pass
- print "toContinue = ", tocont
+ print("toContinue = ", tocont)
pass
self.e.resumeCurrentBreakPoint()
self.assertEqual(106, self.p.getChildByName('c0.c1.n1').getEffectiveState())
self.assertEqual(999, self.p.getChildByName('c0.n2').getEffectiveState())
self.assertEqual(888, self.p.getChildByName('node62').getEffectiveState())
- print "================= End of STEPBYSTEP ====================="
+ print("================= End of STEPBYSTEP =====================")
pass
def test2_StopToBreakpoint(self):
# --- start execution, set a breakpoint before node48, then continue
time.sleep(1)
- print "================= Start of BREAKPOINT ==================="
+ print("================= Start of BREAKPOINT ===================")
brp=['node48']
self.e.setListOfBreakPoints(brp)
self.e.setExecMode(2) # YACS::STOPBEFORENODES
time.sleep(0.1)
self.e.waitPause()
#self.e.displayDot(p)
- print "================= reach BREAKPOINT ======================"
+ print("================= reach BREAKPOINT ======================")
# --- resume from breakpoint
- print "=========== BREAKPOINT, start RESUME ===================="
+ print("=========== BREAKPOINT, start RESUME ====================")
time.sleep(1)
self.e.setExecMode(0) # YACS::CONTINUE
self.e.resumeCurrentBreakPoint()
self.assertEqual(106, self.p.getChildByName('c0.c1.n1').getEffectiveState())
self.assertEqual(999, self.p.getChildByName('c0.n2').getEffectiveState())
self.assertEqual(888, self.p.getChildByName('node62').getEffectiveState())
- print "================= End of RESUME ========================="
+ print("================= End of RESUME =========================")
pass
def test3_RunWithoutBreakpoints(self):
# --- start execution, run without breakpoints
time.sleep(1)
- print "================= Start of CONTINUE ====================="
+ print("================= Start of CONTINUE =====================")
self.e.setExecMode(0) # YACS::CONTINUE
run3 = threading.Thread(None, self.e.RunPy, "continue", (self.p,0))
run3.start()
self.assertEqual(106, self.p.getChildByName('c0.c1.n1').getEffectiveState())
self.assertEqual(999, self.p.getChildByName('c0.n2').getEffectiveState())
self.assertEqual(888, self.p.getChildByName('node62').getEffectiveState())
- print "================= End of CONTINUE ======================="
+ print("================= End of CONTINUE =======================")
pass
def test4_StopOnError(self):
# --- stop execution on first error and save state
time.sleep(1)
- print "================= Start of STOPONERROR =================="
+ print("================= Start of STOPONERROR ==================")
self.e.setStopOnError()
run4 = threading.Thread(None, self.e.RunPy, "continue", (self.p,0))
run4.start()
#self.e.displayDot(self.p)
s13 = self.p.getChildByName('node13').getEffectiveState()
s43 = self.p.getChildByName('node43').getEffectiveState()
- self.assert_((s13==999) or (s43==999))
- print "================= End of STOPONERROR ====================="
+ self.assertTrue((s13==999) or (s43==999))
+ print("================= End of STOPONERROR =====================")
pass
def test5_PartialExec(self):
# --- stop execution after breakpoint
time.sleep(1)
- print "================= Start of PARTIALEXEC ==================="
+ print("================= Start of PARTIALEXEC ===================")
brp=['node35']
self.e.setListOfBreakPoints(brp)
self.e.setExecMode(2) # YACS::STOPBEFORENODES
#self.e.displayDot(self.p)
self.assertEqual(106, self.p.getChildByName('node34').getEffectiveState())
self.assertEqual(101, self.p.getChildByName('node35').getEffectiveState())
- print "================= reach BREAKPOINT PARTIAL EXEC =========="
+ print("================= reach BREAKPOINT PARTIAL EXEC ==========")
pass
-
+
pass
if __name__ == '__main__':
- import os
- U = os.getenv('USER')
- f=open("/tmp/" + U + "/UnitTestsResult", 'a')
- f.write(" --- TEST src/yacsloader: testExec.py\n")
- suite = unittest.makeSuite(TestExec)
- result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
- f.close()
- sys.exit(not result.wasSuccessful())
\ No newline at end of file
+ import os
+ import sys
+ U = os.getenv('USER')
+ with open(os.path.join("/tmp", U, "UnitTestsResult"), 'a') as f:
+ f.write(" --- TEST src/yacsloader: testExec.py\n")
+ suite = unittest.makeSuite(TestExec)
+ result = unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
+
+ sys.exit(not result.wasSuccessful())
retex=None
try:
p = self.l.load("nonexisting")
- except IOError, ex:
- print "IO Error: ", ex
+ except IOError as ex:
+ print("IO Error: ", ex)
retex=ex
- #except pilot.invalid_argument,ex:
- # print "invalid_argument:",ex.what()
+ # except pilot.invalid_argument as ex:
+ # print("invalid_argument:",str(ex))
# retex=ex.what()
- self.assert_(retex is not None, "exception not raised, or wrong type")
+ self.assertTrue(retex is not None, "exception not raised, or wrong type")
pass
def test2_parseError(self):
retex=None
try:
p = self.l.load("samples/bid.xml")
- except ValueError,ex:
- print "Caught ValueError Exception:",ex
+ except ValueError as ex:
+ print("Caught ValueError Exception:",ex)
retex = ex
expected="LogRecord: parser:ERROR:from node node5 does not exist in control link: node5->b2 context: b1. (samples/bid.xml:53)\n"
- self.assert_(p.getLogger("parser").getStr() == expected, "error not found: "+p.getLogger("parser").getStr())
+ self.assertTrue(p.getLogger("parser").getStr() == expected, "error not found: "+p.getLogger("parser").getStr())
pass
def test3_normal(self):
# --- File exists and no parsing problem
try:
p = self.l.load("samples/aschema.xml")
- print p.getLogger("parser").getStr()
- print p
- print p.getName()
- for k in p.typeMap: print k
- for k in p.nodeMap: print k
- for k in p.inlineMap: print k
- for k in p.serviceMap: print k
- print self.e.getTasksToLoad()
+ print(p.getLogger("parser").getStr())
+ print(p)
+ print(p.getName())
+ for k in p.typeMap: print(k)
+ for k in p.nodeMap: print(k)
+ for k in p.inlineMap: print(k)
+ for k in p.serviceMap: print(k)
+ print(self.e.getTasksToLoad())
self.e.RunW(p,0)
self.assertEqual(106, p.getChildByName('node48').getEffectiveState())
- except pilot.Exception,ex:
- print "YACS exception:",ex
+ except pilot.Exception as ex:
+ print("YACS exception:",ex)
self.fail(ex)
pass
pass
if __name__ == '__main__':
import os
U = os.getenv('USER')
- f=open("/tmp/" + U + "/UnitTestsResult", 'a')
- f.write(" --- TEST src/yacsloader: testLoader.py\n")
- suite = unittest.makeSuite(TestLoader)
- result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
- f.close()
- sys.exit(not result.wasSuccessful())
\ No newline at end of file
+ with open("/tmp/" + U + "/UnitTestsResult", 'a') as f:
+ f.write(" --- TEST src/yacsloader: testLoader.py\n")
+ suite = unittest.makeSuite(TestLoader)
+ result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
+ sys.exit(not result.wasSuccessful())
if __name__ == '__main__':
import os
U = os.getenv('USER')
- f=open("/tmp/" + U + "/UnitTestsResult", 'a')
- f.write(" --- TEST src/yacsloader: testProgress.py\n")
- suite = unittest.makeSuite(TestEdit)
- result=unittest.TextTestRunner(f, descriptions=1, verbosity=3).run(suite)
- f.close()
+ with open("/tmp/" + U + "/UnitTestsResult", 'a') as f:
+ f.write(" --- TEST src/yacsloader: testProgress.py\n")
+ suite = unittest.makeSuite(TestEdit)
+ result=unittest.TextTestRunner(f, descriptions=1, verbosity=3).run(suite)
sys.exit(not result.wasSuccessful())
"""test delete following creation from class"""
co=self.r.createContainer()
self.assertEqual(co.getRefCnt(), 1)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
def test1(self):
"""test delete following creation from createContainer and delitem from containerMap"""
co=self.p.createContainer("c2")
del self.p.containerMap["c2"]
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 1)
del co
co=self.p.createContainer("c2")
self.p.containerMap["c2"]=co
del self.p.containerMap["c2"]
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 1)
del co
del self.p.containerMap["c9"]
self.assertEqual(co.getName(), "c9")
self.assertEqual(co.getRefCnt(), 1)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
def test4(self):
del self.p.containerMap["c10"]
self.assertEqual(co.getName(), "c10")
self.assertEqual(co.getRefCnt(), 1)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
def test5(self):
del self.p
self.assertEqual(co.getName(), "c10")
self.assertEqual(co.getRefCnt(), 1)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
def test6(self):
"""test ownership of container on getitem from containerMap"""
co=self.p.createContainer("c8")
self.assertEqual(co.getRefCnt(), 2)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
self.assertEqual(self.p.containerMap["c8"].getRefCnt(), 2) # +1 for getitem
co=self.p.containerMap["c8"]
self.assertEqual(co.getRefCnt(), 2)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
self.assertEqual(self.p.containerMap["c8"].getRefCnt(), 2) # +1 for getitem
del self.p.containerMap["c8"]
def test9(self):
"""test method values"""
self.p.createContainer("c8")
- for co in self.p.containerMap.values():
- self.assert_(co.thisown)
+ for co in list(self.p.containerMap.values()):
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 2)
def test10(self):
"""test method items"""
self.p.createContainer("c8")
- for k,co in self.p.containerMap.items():
- self.assert_(co.thisown)
+ for k,co in list(self.p.containerMap.items()):
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 2)
def test11(self):
"""test method clear"""
co=self.p.createContainer("c8")
self.p.containerMap.clear()
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 1)
def test12(self):
co=self.p.createContainer("c8")
d={"c1":co}
self.p.containerMap.update(d)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 3)
class TestTypeCodeRef(unittest.TestCase):
"""test delete following creation from createSequenceTc"""
tc=pilot.TypeCode(pilot.Double)
self.assertEqual(tc.getRefCnt(), 1)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
def test1(self):
"""test delete following creation from createInterfaceTc and delitem from typeMap"""
tc=self.p.createInterfaceTc("","obj",[])
del self.p.typeMap["obj"]
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 1)
def test2(self):
tc=self.p.createInterfaceTc("","obj",[])
self.p.typeMap["obj"]=tc
del self.p.typeMap["obj"]
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 1)
def test3(self):
self.assertEqual(tc.getRefCnt(), 2)
del self.p.typeMap["obj"]
self.assertEqual(tc.getRefCnt(), 1)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
def test4(self):
"""test delete from typeMap following creation from createInterfaceTc"""
tc=self.p.createInterfaceTc("","obj",[])
del self.p.typeMap["obj"]
self.assertEqual(tc.getRefCnt(), 1)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
def test5(self):
"""test existence TypeCode following delete proc"""
tc=self.p.createInterfaceTc("","obj",[])
del self.p
self.assertEqual(tc.getRefCnt(), 1)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
def test6(self):
"""test ownership of TypeCode on getitem from typeMap"""
tc=self.p.createInterfaceTc("","obj",[])
self.assertEqual(tc.getRefCnt(), 2)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
del tc
self.assertEqual(self.p.typeMap["obj"].getRefCnt(), 2) # +1 for getitem
tc=self.p.typeMap["obj"]
self.assertEqual(tc.getRefCnt(), 2)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
del tc
self.assertEqual(self.p.typeMap["obj"].getRefCnt(), 2) # +1 for getitem
del self.p.typeMap["obj"]
def test9(self):
"""test method values"""
self.p.createInterfaceTc("","obj",[])
- for tc in self.p.typeMap.values():
+ for tc in list(self.p.typeMap.values()):
if tc.name()!="obj":continue
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 2)
def test10(self):
"""test method items"""
self.p.createInterfaceTc("","obj",[])
- for k,tc in self.p.typeMap.items():
+ for k,tc in list(self.p.typeMap.items()):
if tc.name()!="obj":continue
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 2)
def test11(self):
"""test method clear"""
tc=self.p.createInterfaceTc("","obj",[])
self.p.typeMap.clear()
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 1)
def test12(self):
tc=self.p.createInterfaceTc("","obj",[])
d={"c1":tc}
self.p.typeMap.update(d)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 3)
if __name__ == '__main__':
import os
U = os.getenv('USER')
- f=open("/tmp/" + U + "/UnitTestsResult", 'a')
- f.write(" --- TEST src/yacsloader: testRefcount.py\n")
- suite1 = unittest.makeSuite(TestContainerRef)
- suite2 = unittest.makeSuite(TestTypeCodeRef)
- suite = unittest.TestSuite((suite1, suite2))
- result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
- f.close()
- sys.exit(not result.wasSuccessful())
\ No newline at end of file
+ with open("/tmp/" + U + "/UnitTestsResult", 'a') as f:
+ f.write(" --- TEST src/yacsloader: testRefcount.py\n")
+ suite1 = unittest.makeSuite(TestContainerRef)
+ suite2 = unittest.makeSuite(TestTypeCodeRef)
+ suite = unittest.TestSuite((suite1, suite2))
+ result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
+ sys.exit(not result.wasSuccessful())
# --- stop execution after breakpoint
time.sleep(1)
- print "================= Start of PARTIALEXEC ==================="
+ print("================= Start of PARTIALEXEC ===================")
brp=['b1.b2.node1']
self.e.setListOfBreakPoints(brp)
self.e.setExecMode(2) # YACS::STOPBEFORENODES
#self.e.displayDot(self.p)
self.assertEqual(101, self.p.getChildByName('b1.b2.node1').getEffectiveState())
self.assertEqual(106, self.p.getChildByName('b1.node1').getEffectiveState())
- print "================= reach BREAKPOINT PARTIAL EXEC =========="
+ print("================= reach BREAKPOINT PARTIAL EXEC ==========")
pass
def test2_ExecFromLoadState(self):
# --- reload state from previous partial execution then exec
time.sleep(1)
- print "================= Start of EXECLOADEDSTATE ==============="
+ print("================= Start of EXECLOADEDSTATE ===============")
sp = loader.stateParser()
sl = loader.stateLoader(sp,self.p)
sl.parse('dumpPartialBloc2.xml')
self.assertEqual(106, self.p.getChildByName('b1.b2.node1').getEffectiveState())
self.assertEqual(106, self.p.getChildByName('b1.b2.node2').getEffectiveState())
self.assertEqual(106, self.p.getChildByName('b1.b2.loop1.node1').getEffectiveState())
- print "================= End of EXECLOADEDSTATE ================="
+ print("================= End of EXECLOADEDSTATE =================")
pass
if __name__ == '__main__':
import os
U = os.getenv('USER')
- f=open("/tmp/" + U + "/UnitTestsResult", 'a')
- f.write(" --- TEST src/yacsloader: testResume.py\n")
- suite = unittest.makeSuite(TestResume)
- result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
- f.close()
+ with open("/tmp/" + U + "/UnitTestsResult", 'a') as f:
+ f.write(" --- TEST src/yacsloader: testResume.py\n")
+ suite = unittest.makeSuite(TestResume)
+ result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
sys.exit(not result.wasSuccessful())
s.save(saveSchema2)
e.RunW(p,0)
e.saveState(dumpSchema2)
- except ValueError, ex:
- print "Value Error: ", ex
+ except ValueError as ex:
+ print("Value Error: ", ex)
pb = "problem on " + fileOrig + " : ValueError"
self.fail(pb)
- except pilot.Exception,ex:
- print ex.what()
+ except pilot.Exception as ex:
+ print(ex.what())
pb = "problem on " + fileOrig + " : " + ex.what()
self.fail(pb)
except:
pb = "unknown problem on " + fileOrig
self.fail(pb)
- s1=open(saveSchema1,'r')
- s2=open(saveSchema2,'r')
- d1=open(dumpSchema1,'r')
- d2=open(dumpSchema2,'r')
- ls1 = s1.readlines().sort()
- ls2 = s2.readlines().sort()
- ld1 = d1.readlines().sort()
- ld2 = d2.readlines().sort()
+
+ with open(saveSchema1,'r') as s1:
+ ls1 = s1.readlines().sort()
+ with open(saveSchema2,'r') as s2:
+ ls2 = s2.readlines().sort()
+ with open(dumpSchema1,'r') as d1:
+ ld1 = d1.readlines().sort()
+ with open(dumpSchema2,'r') as d2:
+ ld2 = d2.readlines().sort()
pb1 = "file schemes produced by successive executions are not identical: " + fileOrig
pb2 = "final dump states produced by successive executions are not identical: " + fileOrig
self.assertEqual(ls1,ls2,pb1)
if __name__ == '__main__':
import os
U = os.getenv('USER')
- f=open("/tmp/" + U + "/UnitTestsResult", 'a')
- f.write(" --- TEST src/yacsloader: testSave.py\n")
- suite = unittest.makeSuite(TestSave)
- result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
- f.close()
- sys.exit(not result.wasSuccessful())
\ No newline at end of file
+ with open("/tmp/" + U + "/UnitTestsResult", 'a') as f:
+ f.write(" --- TEST src/yacsloader: testSave.py\n")
+ suite = unittest.makeSuite(TestSave)
+ result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
+ sys.exit(not result.wasSuccessful())
ref=datetime.datetime.now()
t=0. ; pas=1./float(nb)
- for i in xrange(nb):
- for j in xrange(nb):
+ for i in range(nb):
+ for j in range(nb):
x=j*pas
t+=1.+cos(1.*(x*3.14159))
pass
pass
- print "coucou from script0-%i -> %s"%(dbg,str(datetime.datetime.now()-ref))
+ print("coucou from script0-%i -> %s"%(dbg,str(datetime.datetime.now()-ref)))
return t
"""
script1="""
import datetime
ref=datetime.datetime.now()
o2=0. ; pas=1./float(i1)
-for i in xrange(i1):
- for j in xrange(i1):
+for i in range(i1):
+ for j in range(i1):
x=j*pas
o2+=1.+cos(1.*(x*3.14159))
pass
-print "coucou from script1-%i -> %s"%(dbg,str(datetime.datetime.now()-ref))
+print("coucou from script1-%i -> %s"%(dbg,str(datetime.datetime.now()-ref)))
"""
- for i in xrange(nbOfNodes):
+ for i in range(nbOfNodes):
node0=self.r.createFuncNode("DistPython","node%i"%(i))
p.edAddChild(node0)
node0.setFname("ff")
st=datetime.datetime.now()
# 1st exec
ex.RunW(p,0)
- print "Time spend of test0 to run 1st %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test0 to run 1st %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
# 2nd exec using the same already launched remote python interpreters
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test0 to run 2nd %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test0 to run 2nd %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
# 3rd exec using the same already launched remote python interpreters
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test0 to run 3rd %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test0 to run 3rd %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
pass
ref=datetime.datetime.now()
t=0. ; pas=1./float(nb)
- for i in xrange(nb):
- for j in xrange(nb):
+ for i in range(nb):
+ for j in range(nb):
x=j*pas
t+=1.+cos(1.*(x*3.14159))
pass
pass
- print "coucou from script0-%i -> %s"%(dbg,str(datetime.datetime.now()-ref))
+ print("coucou from script0-%i -> %s"%(dbg,str(datetime.datetime.now()-ref)))
return t
"""
# here in script1 aa is refered ! aa will exist thanks to HPCont Init Script
import datetime
ref=datetime.datetime.now()
o2=0. ; pas=1./float(i1)
-for i in xrange(i1):
- for j in xrange(i1):
+for i in range(i1):
+ for j in range(i1):
x=j*pas
o2+=1.+cos(1.*(x*3.14159))
pass
-print "coucou %lf from script1-%i -> %s"%(aa,dbg,str(datetime.datetime.now()-ref))
+print("coucou %lf from script1-%i -> %s"%(aa,dbg,str(datetime.datetime.now()-ref)))
aa+=1.
"""
#
- for i in xrange(nbOfNodes):
+ for i in range(nbOfNodes):
nodeMiddle=self.r.createFuncNode("Salome","node%i_1"%(i)) # PyFuncNode remote
p.edAddChild(nodeMiddle)
nodeMiddle.setFname("ff")
self.assertEqual(p.getState(),pilot.READY)
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test1 to 1st run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test1 to 1st run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
# 2nd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test1 to 2nd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test1 to 2nd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
# 3rd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test1 to 3rd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test1 to 3rd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
pass
""" Test on HP Containers in foreach context."""
script0="""def ff():
global aa
- print "%%lf - %%s"%%(aa,str(my_container))
+ print("%%lf - %%s"%%(aa,str(my_container)))
return 16*[%i],0
"""
script1="""from math import cos
import datetime
ref=datetime.datetime.now()
o2=0. ; pas=1./float(i1)
-for i in xrange(i1):
- for j in xrange(i1):
+for i in range(i1):
+ for j in range(i1):
x=j*pas
o2+=1.+cos(1.*(x*3.14159))
pass
-print "coucou %lf from script -> %s"%(aa,str(datetime.datetime.now()-ref))
+print("coucou %lf from script -> %s"%(aa,str(datetime.datetime.now()-ref)))
aa+=1.
o3=0
"""
self.assertEqual(p.getState(),pilot.READY)
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test2 to 1st run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test2 to 1st run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
# 2nd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test2 to 2nd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test2 to 2nd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
# 3rd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test2 to 3rd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test2 to 3rd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
pass
""" Test that focuses on parallel load of containers."""
script0="""def ff():
global aa
- print "%%lf - %%s"%%(aa,str(my_container))
+ print("%%lf - %%s"%%(aa,str(my_container)))
return 100*[%i],0
"""
script1="""from math import cos
import datetime
ref=datetime.datetime.now()
o2=0. ; pas=1./float(i1)
-for i in xrange(i1):
- for j in xrange(i1):
+for i in range(i1):
+ for j in range(i1):
x=j*pas
o2+=1.+cos(1.*(x*3.14159))
pass
-print "coucou %lf from script -> %s"%(aa,str(datetime.datetime.now()-ref))
+print("coucou %lf from script -> %s"%(aa,str(datetime.datetime.now()-ref)))
aa+=1.
o3=0
"""
self.assertEqual(p.getState(),pilot.READY)
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test3 to 1st run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test3 to 1st run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
# 2nd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test3 to 2nd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test3 to 2nd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
# 3rd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test3 to 3rd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test3 to 3rd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
pass
script1="""nb=7
ii=0
o1=nb*[None]
-for i in xrange(nb):
+for i in range(nb):
tmp=(i+10)*[None]
- for j in xrange(i+10):
+ for j in range(i+10):
tmp[j]=ii
ii+=1
pass
script1="""nb=7
ii=0
o1=nb*[None]
-for i in xrange(nb):
+for i in range(nb):
tmp=(i+10)*[None]
- for j in xrange(i+10):
+ for j in range(i+10):
tmp[j]=ii
ii+=1
pass
self.assertEqual(n1.getState(),pilot.DONE)
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
- self.assertEqual(a,range(6))
- self.assertEqual([elt.getPyObj() for elt in b],[[6L, 12L, 16L, 18L, -4L, 10L]])
+ self.assertEqual(a,list(range(6)))
+ self.assertEqual([elt.getPyObj() for elt in b],[[6, 12, 16, 18, -4, 10]])
self.assertEqual(c,['n10_o2_interceptor'])
pass
self.assertEqual(n1.getState(),pilot.FAILED)
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
- self.assertEqual(a,range(3))
- self.assertEqual([elt.getPyObj() for elt in b],[[6L,12L,16L]])
+ self.assertEqual(a,list(range(3)))
+ self.assertEqual([elt.getPyObj() for elt in b],[[6,12,16]])
self.assertEqual(c,['n10_o2_interceptor'])
pass
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[0,1,2,4,5])
- self.assertEqual([elt.getPyObj() for elt in b],[[6L,12L,16L,-4L,10L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[6,12,16,-4,10]])
self.assertEqual(c,['n10_o2_interceptor'])
p.getChildByName("n1").getChildByName("n10").setScript("""
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[1,2,3,4,5])
- self.assertEqual([elt.getPyObj() for elt in b],[[12L,16L,18L,-4L,10L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[12,16,18,-4,10]])
self.assertEqual(c,['n10_o2_interceptor'])
pass
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[0,1,2,4,5])
- self.assertEqual([elt.getPyObj() for elt in b],[[6L,12L,16L,-4L,10L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[6,12,16,-4,10]])
self.assertEqual(c,['n10_o2_interceptor'])
p.getChildByName("n1").getChildByName("n10").setScript("""
#
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(p.getState(),pilot.DONE)
- self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[6L,12L,16L,63L,-4L,10L])
+ self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[6,12,16,63,-4,10])
pass
def test10(self):
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[1,3,5,7,9,11])
- self.assertEqual([elt.getPyObj() for elt in b],[[12L,36L,60L,84L,108L,132L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[12,36,60,84,108,132]])
self.assertEqual(c,['n10_o2_interceptor'])
p.getChildByName("n1").getChildByName("n10").setScript("""
#
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(p.getState(),pilot.DONE)
- self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0L,12L,30L,36L,60L,60L,90L,84L,120L,108L,150L,132L])
+ self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0,12,30,36,60,60,90,84,120,108,150,132])
pass
pass
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[0,2,4,6,8,10])
- self.assertEqual([elt.getPyObj() for elt in b],[[0L,4L,8L,12L,16L,20L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[0,4,8,12,16,20]])
p.getChildByName("n0").setScript("o0=[ 3*elt for elt in range(12) ]")
p.getChildByName("n1").getChildByName("n10").setScript("""
#
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(p.getState(),pilot.DONE)
- self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0L,5L,4L,15L,8L,25L,12L,35L,16L,45L,20L,55L])
+ self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0,5,4,15,8,25,12,35,16,45,20,55])
pass
def test12(self):
#
node0=self.r.createForEachLoop("ForEachLoop_int0",ti)
p.edAddChild(node0)
- node0.edGetSeqOfSamplesPort().edInitPy(range(4))
+ node0.edGetSeqOfSamplesPort().edInitPy(list(range(4)))
node0.edGetNbOfBranchesPort().edInitInt(2)
#
node00=self.r.createBloc("Bloc0")
node0.edAddChild(node00)
node000_0=self.r.createForEachLoop("ForEachLoop_int1",ti)
node00.edAddChild(node000_0)
- node000_0.edGetSeqOfSamplesPort().edInitPy(range(4))
+ node000_0.edGetSeqOfSamplesPort().edInitPy(list(range(4)))
node000_0.edGetNbOfBranchesPort().edInitInt(3)
#
node0000=self.r.createBloc("Bloc1")
node00.edAddChild(node000_1)
i7=node000_1.edAddInputPort("i7",ti2)
i5=node000_1.edAddInputPort("i5",ti2)
- node000_1.setScript("for i in i7:\n print i\nprint \"separation\"\nfor i in i5:\n print i")
+ node000_1.setScript("for i in i7:\n print(i)\nprint(\"separation\")\nfor i in i5:\n print(i)")
node000_1.setContainer(cont)
node000_1.setExecutionMode("remote")
p.edAddLink(o5,i7)
#
n00.edAddLink(n000.edGetSamplePort(),i0)
#
- n000.edGetSeqOfSamplesPort().edInitPy(range(10))
+ n000.edGetSeqOfSamplesPort().edInitPy(list(range(10)))
n000.edGetNbOfBranchesPort().edInitInt(2)
#
n01=r.createScriptNode("Salome","test23/check") ; n0bis.edAddChild(n01)
#
nb=4
outs=[]
- for i in xrange(nb):
+ for i in range(nb):
node=self.r.createScriptNode("Salome","node%d"%i)
node.setExecutionMode("remote")
node.setContainer(cont)
res=node.edAddOutputPort("res",ti)
p.edAddChild(node)
l=[]
- for i in xrange(nb):
+ for i in range(nb):
elt="i%d"%i
inp=node.edAddInputPort(elt,ti) ; l.append(elt)
p.edAddChild(node)
node.setScript("res="+"+".join(l))
p.edAddCFLink(b,node)
#
- for i in xrange(10):
+ for i in range(10):
p.init()
ex = pilot.ExecutorSwig()
self.assertEqual(p.getState(),pilot.READY)
n00=self.r.createScriptNode("Salome","n00") ; n0.edAddChild(n00)
o0=n00.edAddOutputPort("o0",tp2)
- n00.setScript("o0=[[i+1] for i in xrange(8)]")
+ n00.setScript("o0=[[i+1] for i in range(8)]")
n01=self.r.createScriptNode("Salome","n01") ; n0.edAddChild(n01)
i1=n01.edAddInputPort("i1",tp)
n01.setScript("assert(i1==[[1], [2], [3], [4], [5], [6], [7], [8]])")
n00=self.r.createScriptNode("Salome","n00") ; n0.edAddChild(n00)
o0=n00.edAddOutputPort("o0",tp2)
- n00.setScript("o0=[[i+1] for i in xrange(8)]")
+ n00.setScript("o0=[[i+1] for i in range(8)]")
n01=self.r.createScriptNode("Salome","n01") ; n0.edAddChild(n01)
i1=n01.edAddInputPort("i1",tp)
n01.setScript("assert(i1==[[1], [2], [3], [4], [5], [6], [7], [8]])")
self.assertEqual(p.getState(),pilot.DONE)
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(a,[0,1])
- self.assertEqual([elt.getPyObj() for elt in b],[[0L,2L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[0,2]])
#
p.getChildByName("n0").setScript("o0=[ 3*elt for elt in range(6) ]")
p.getChildByName("n1").getChildByName("n10").setScript("""
#
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(p.getState(),pilot.DONE)
- self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0L,2L,10L,15L,20L,25L])
+ self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0,2,10,15,20,25])
pass
pass
q.getChildByName("n1").getChildByName("n10").setScript("""
import time
time.sleep(0.1)
-print "execution n10:", i1
+print("execution n10:", i1)
o2=5*i1
""")
q.getChildByName("n2").setScript("""
-print "execution n2:", i3
+print("execution n2:", i3)
o4=i3
""")
loader.loadState(q, xmlStateFileName)
if __name__ == '__main__':
import os,sys
U = os.getenv('USER')
- f=open("/tmp/" + U + "/UnitTestsResult", 'a')
- f.write(" --- TEST src/yacsloader: testSaveLoadRun.py\n")
- suite = unittest.makeSuite(TestSaveLoadRun)
- result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
- f.close()
+ with open("/tmp/" + U + "/UnitTestsResult", 'a') as f:
+ f.write(" --- TEST src/yacsloader: testSaveLoadRun.py\n")
+ suite = unittest.makeSuite(TestSaveLoadRun)
+ result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
sys.exit(not result.wasSuccessful())
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
procEx.saveState("res.xml")
i+=1
pass
-print procEx.getOutPortValue(dico["poly_7"],"Pn")
-print procEx.getInPortValue(dico["poly_7"],"x")
-print procEx.getInPortValue(dico["poly_7"],"notAPort")
-print procEx.getInPortValue(dico["Legendre.loopIter"],"nsteps")
+print(procEx.getOutPortValue(dico["poly_7"],"Pn"))
+print(procEx.getInPortValue(dico["poly_7"],"x"))
+print(procEx.getInPortValue(dico["poly_7"],"notAPort"))
+print(procEx.getInPortValue(dico["Legendre.loopIter"],"nsteps"))
# -----------------------------------------------------------------------------
# --- schema with errors (echoSrv must be launched)
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
procEx.saveState("res2.xml")
i+=1
pass
-print procEx.getErrorDetails(dico["c1"])
-print procEx.getErrorDetails(dico["node13"])
+print(procEx.getErrorDetails(dico["c1"]))
+print(procEx.getErrorDetails(dico["node13"]))
# -----------------------------------------------------------------------------
# --- schema with errors
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
#procEx.resumeCurrentBreakPoint()
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
procEx.saveState("partialExec.xml")
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
procEx.saveState("finishExec.xml")
return self.p.getIds()
def runProc(self,debug, isPyThread, fromscratch):
- print "**************************Begin schema execution %s**************************" % self.xmlFile
+ print("**************************Begin schema execution %s**************************" % self.xmlFile)
self.e.RunPy(self.p,debug, isPyThread, fromscratch)
- print "**************************End schema execution %s****************************" % self.xmlFile
+ print("**************************End schema execution %s****************************" % self.xmlFile)
def Run(self):
if self.run1 is not None:
sp = loader.stateParser()
sl = loader.stateLoader(sp,self.p)
sl.parse(xmlFile)
- except IOError, ex:
- print "IO Error: ", ex
+ except IOError as ex:
+ print("IO Error: ", ex)
return
- except ValueError,ex:
- print "Caught ValueError Exception:",ex
+ except ValueError as ex:
+ print("Caught ValueError Exception:",ex)
return
- except pilot.Exception,ex:
- print ex.what()
+ except pilot.Exception as ex:
+ print(ex.what())
return
except:
- print "Unknown exception!"
+ print("Unknown exception!")
return
if self.run1 is None:
"""
def __init__ ( self, orb, poa, contID, containerName, instanceName,
interfaceName ):
- print "YACS.__init__: ", containerName, ';', instanceName
+ print("YACS.__init__: ", containerName, ';', instanceName)
SALOME_ComponentPy.SALOME_ComponentPy_i.__init__(self, orb, poa, contID,
containerName, instanceName,
interfaceName, False)
procExec_i = proc_i(xmlFile)
logger=procExec_i.p.getLogger("parser")
if not logger.isEmpty():
- print "The imported file has errors :"
- print logger.getStr()
+ print("The imported file has errors :")
+ print(logger.getStr())
sys.stdout.flush()
return None
- except IOError, ex:
- print >> sys.stderr ,"IO Error: ", ex
+ except IOError as ex:
+ print("IO Error: ", ex, file=sys.stderr)
return None
- except ValueError,ex:
- print >> sys.stderr ,"Caught ValueError Exception:",ex
+ except ValueError as ex:
+ print("Caught ValueError Exception:",ex, file=sys.stderr)
return None
- except pilot.Exception,ex:
- print >> sys.stderr ,ex.what()
+ except pilot.Exception as ex:
+ print(ex.what(), file=sys.stderr)
return None
except:
traceback.print_exc()
${PROJECT_SOURCE_DIR}/src/runtime
${PROJECT_SOURCE_DIR}/src/yacsloader
${PROJECT_SOURCE_DIR}/src/evalyfx
+ ${OMNIORB_INCLUDE_DIR}
+ ${OMNIORB_ROOT_DIR}/include/omniORB4/internal
+ ${OMNIORBPY_INCLUDE_DIR}
)
# additional preprocessor / compiler flags
ADD_DEFINITIONS(
${QT_DEFINITIONS}
+ ${OMNIORB_DEFINITIONS}
${PYTHON_DEFINITIONS})
IF(SALOME_YACS_USE_KERNEL)
YACSEvalParamsForCluster& ps(res->getAddParamsForCluster());
_clusterAdvInfo->applyToParams(ps);
}
- emit readyForRunSignal(true);
+ Q_EMIT readyForRunSignal(true);
}
QString YDFXGUIHostParametrizer::getNameOfHost()
ok->setDisabled(!isInterac && !_clusterAdvInfo->isOK());
if(_wasInteractive!=isInterac)
{
- emit interactivityChanged(isInterac);
+ Q_EMIT interactivityChanged(isInterac);
_wasInteractive=isInterac;
}
}
}
bool newOK(isOK());
_wasOK=newOK;
- emit statusOfEntryChanged(newOK);
+ Q_EMIT statusOfEntryChanged(newOK);
}
void YDFXGUIBatchInfo::learnSettings(QSettings& settings) const
void YDFXGUIBatchInfo::somethingChanged()
{
- emit statusOfEntryChanged(isOK());
+ Q_EMIT statusOfEntryChanged(isOK());
}
QString YDFXGUIBatchInfo::NormalizeDuration(const QString& txt)
#include <QThread>
#include <QMutex>
-#include "Python.h"
-
class YACSEvalSession;
class YACSEvalYFXWrap;
class YDFXGUIAllPorts;
{
if(wasKO)
{
- emit statusChanged();
+ Q_EMIT statusChanged();
disconnect(this,SIGNAL(changeLook()),this,SLOT(applyModificationOfLook()));
}
}
bool oldOK(isOK());
bool oldStatus(_inp->isRandomVar());
_inp->declareRandomnessStatus(!oldStatus);
- emit statusChanged(); // always emit because this even if newOK and oldOK are the same the upon status can changed !
+ Q_EMIT statusChanged(); // always Q_EMIT because this even if newOK and oldOK are the same the upon status can changed !
updateGeometry();
update();
return _inp->isRandomVar();
void InputLabel::pressOccured()
{
- emit randomnessStatusChanged();
+ Q_EMIT randomnessStatusChanged();
}
std::vector<ColoredString> InputLabel::textForEmulatedPushButton() const
{
bool oldStatus(_outp->isQOfInterest());
_outp->setQOfInterestStatus(!oldStatus);
- emit clicked();
+ Q_EMIT clicked();
}
std::vector<ColoredString> OutputLabel::textForEmulatedPushButton() const
update();
setWasOKStatus(newStatus);
}
- emit theGlobalStatusChanged(newStatus);// emit signal always because of input ports and sequences definitions.
+ Q_EMIT theGlobalStatusChanged(newStatus);// Q_EMIT signal always because of input ports and sequences definitions.
}
//////////////////
YDFXGUIInputPortValueEditor *childc(qobject_cast<YDFXGUIInputPortValueEditor *>(child));
if(childc)
{
- emit childc->changeLook();
+ Q_EMIT childc->changeLook();
}
}
}
bool step1(_in->isOK() && _out->isOK());
if(!step1)
{
- emit sequencesCanBeDefinedSignal(false);
- emit canBeExecutedSignal(false);
+ Q_EMIT sequencesCanBeDefinedSignal(false);
+ Q_EMIT canBeExecutedSignal(false);
return ;
}
- emit sequencesCanBeDefinedSignal(true);
- emit canBeExecutedSignal(_in->areSeqWellDefined());
+ Q_EMIT sequencesCanBeDefinedSignal(true);
+ Q_EMIT canBeExecutedSignal(_in->areSeqWellDefined());
}
//
// Author : Anthony Geay (EDF R&D)
+#include "YDFXGUIPyThreadSaver.hxx"
#include "YDFXGUIPushButtons.hxx"
#include "YDFXGUIWrap.hxx"
#include "YDFXGUISeqInit.hxx"
-#include "YDFXGUIPyThreadSaver.hxx"
#include "YDFXGUIHostParametrizer.hxx"
#include "YACSEvalSession.hxx"
if(dial.exec())
{
_state=zeWidget->saveState();
- emit sequenceWellDefined(true);
+ Q_EMIT sequenceWellDefined(true);
}
}
std::fill(_items.begin(),_items.end(),0);
_computationInProgress=true;
_mut.unlock();
- emit somethingChanged();
+ Q_EMIT somethingChanged();
}
void YDFXGUIRunInfo::endComputation()
_mut.lock();
_computationInProgress=false;
_mut.unlock();
- emit somethingChanged();
+ Q_EMIT somethingChanged();
}
void YDFXGUIRunInfo::sampleOK(int pos)
_mut.lock();
_items[pos]=1;
_mut.unlock();
- emit somethingChanged();
+ Q_EMIT somethingChanged();
}
void YDFXGUIRunInfo::sampleKO(int pos)
_mut.lock();
_items[pos]=2;
_mut.unlock();
- emit somethingChanged();
+ Q_EMIT somethingChanged();
}
std::vector<char> YDFXGUIRunInfo::getItems() const
#ifndef __YDFXGUIPYTHREADSAVER_HXX__
#define __YDFXGUIPYTHREADSAVER_HXX__
+#include "Python.h"
+
#include "ydfxwidgetsExport.hxx"
-#include "Python.h"
class QThread;
//
// Author : Anthony Geay (EDF R&D)
+#include "Python.h"
#include "YDFXGUISeqInit.hxx"
#include <QFile>
#include <QFileDialog>
#include <QApplication>
-#include "Python.h"
#include "AutoGIL.hxx"
//
if(_fileName.isEmpty())
{
- emit problemDetected(QString("For \"%1\" : no file defined !").arg(zeBossc->getName()));
+ Q_EMIT problemDetected(QString("For \"%1\" : no file defined !").arg(zeBossc->getName()));
return false;
}
QFile file(_fileName);
double v(line2.toDouble(&isOK));
if(!isOK)
{
- emit problemDetected(QString("For \"%1\" : At line %2 it is not a float !").arg(zeBossc->getName()).arg(i));
+ Q_EMIT problemDetected(QString("For \"%1\" : At line %2 it is not a float !").arg(zeBossc->getName()).arg(i));
return false;
}
_vect.push_back(v);
AutoPyRef code(Py_CompileString(txt.c_str(),TMP_FILENAME, Py_file_input));
if(code.get() == NULL)
{
- emit problemDetected(QString("For \"%1\" : python code is invalid !").arg(zeBossc->getName()));
+ Q_EMIT problemDetected(QString("For \"%1\" : python code is invalid !").arg(zeBossc->getName()));
return false;
}
AutoPyRef context(PyDict_New());
PyDict_SetItemString( context, "__builtins__", PyEval_GetBuiltins() );
- AutoPyRef res(PyEval_EvalCode((PyCodeObject *)code.get(), context, context));
+ AutoPyRef res(PyEval_EvalCode(code.get(), context, context));
PyObject *item(PyDict_GetItemString(context,name.c_str()));
//
if(!item)
{
- emit problemDetected(QString("For \"%1\" : Py var %1 is not defined !").arg(zeBossc->getName()));
+ Q_EMIT problemDetected(QString("For \"%1\" : Py var %1 is not defined !").arg(zeBossc->getName()));
return false;
}
if(!PyList_Check(item))
{
- emit problemDetected(QString("For \"%1\" : Py var %1 must be a list !").arg(zeBossc->getName()));
+ Q_EMIT problemDetected(QString("For \"%1\" : Py var %1 must be a list !").arg(zeBossc->getName()));
return false;
}
sz=PyList_Size(item);
PyObject *val(PyList_GetItem(item,i));
if(!PyFloat_Check(val))
{
- emit problemDetected(QString("For \"%1\" : At pos %2 of python list, it is not a float !").arg(zeBossc->getName()).arg(i));
+ Q_EMIT problemDetected(QString("For \"%1\" : At pos %2 of python list, it is not a float !").arg(zeBossc->getName()).arg(i));
return false;
}
_vect[i]=PyFloat_AS_DOUBLE(val);
QVBoxLayout *verticalLayout(new QVBoxLayout(this));
_textEdit=new YDFXGUISeqSetterT(this); verticalLayout->addWidget(_textEdit);
_push=new YDFXGUISeqSetterP(this); verticalLayout->addWidget(_push);
- _textEdit->setText(QString("import math\n%1=[math.sqrt(float(elt)+0.) for elt in xrange(4)]").arg(name));
+ _textEdit->setText(QString("import math\n%1=[math.sqrt(float(elt)+0.) for elt in range(4)]").arg(name));
_textEdit->hide();
_push->hide();
}
connect(_combo,SIGNAL(currentIndexChanged(int)),this,SLOT(typeOfAssignmentChanged(int)));
horizontalLayout->addWidget(_setter);
_combo->setCurrentIndex(0);
- emit _combo->currentIndexChanged(0);//to be sure to sync widgets
+ Q_EMIT _combo->currentIndexChanged(0);//to be sure to sync widgets
}
void YDFXGUISeqLine::loadState(const QMap<QString,QString>& state)
{
int sz;
bool verdict(checkConsistency(sz));
- emit configurationIsOK(verdict);
+ Q_EMIT configurationIsOK(verdict);
}
void YDFXGUISeqInitEff::applyOnEFX()
refSz=locSz;
if(locSz!=refSz)
{
- emit line->setter()->problemDetected(QString("Var %1 does not have the same number of elts than others !").arg(line->getName()));
+ Q_EMIT line->setter()->problemDetected(QString("Var %1 does not have the same number of elts than others !").arg(line->getName()));
return false;
}
}
void YACSEvalYFXWrap::unlockAll()
{
_efx->unlockAll();
- emit lockSignal(false);
+ Q_EMIT lockSignal(false);
}
void YACSEvalYFXWrap::lockPortsForEvaluation()
_efx->lockPortsForEvaluation(inps2,outps2);
_efx->giveResources();//do not remove this line to generate resource info
if(!lockedOrNot)
- emit lockSignal(true);
+ Q_EMIT lockSignal(true);
}
int YACSEvalYFXWrap::getNbOfItems() const
void YACSEvalYFXWrap::setRunningStatus(bool status)
{
if(_isRunning!=status)
- emit runSignal(status);
+ Q_EMIT runSignal(status);
_isRunning=status;
}
if(_isSeqOfValsSet!=newStatus)
{
_isSeqOfValsSet=newStatus;
- emit sequencesAreSetSignal(_isSeqOfValsSet);
+ Q_EMIT sequencesAreSetSignal(_isSeqOfValsSet);
}
}