--- a/Beremiz_service.py Fri Nov 23 11:01:20 2018 +0100
+++ b/Beremiz_service.py Fri Nov 23 12:13:24 2018 +0100
@@ -32,11 +32,15 @@
from threading import Thread, Semaphore, Lock
+from builtins import str as text +from past.builtins import execfile +from six.moves import builtins from runtime.PyroServer import Server
from runtime.xenomai import TryPreloadXenomai
from runtime import LogMessageAndException
+from runtime import PlcStatus import util.paths as paths
@@ -142,7 +146,7 @@
-__builtin__.__dict__['_'] = lambda x: x
+builtins.__dict__['_'] = lambda x: x # TODO: add a cmdline parameter if Trying Preloading Xenomai makes problem
@@ -161,12 +165,12 @@
- loc = __builtin__.__dict__.get('loc', None)
+ loc = builtins.__dict__.get('loc', None) wx.LogGui.EnableLogging(False)
wx.LogGui.EnableLogging(True)
- __builtin__.__dict__['loc'] = loc
+ builtins.__dict__['loc'] = loc # Define location for searching translation files
loc.AddCatalogLookupPathPrefix(localedir)
@@ -184,8 +188,8 @@
def unicode_translation(message):
return wx.GetTranslation(message).encode(default_locale)
- __builtin__.__dict__['_'] = unicode_translation
- # __builtin__.__dict__['_'] = wx.GetTranslation
+ builtins.__dict__['_'] = unicode_translation + # builtins.__dict__['_'] = wx.GetTranslation # Life is hard... have a candy.
@@ -200,7 +204,6 @@
if wx.VERSION >= (3, 0, 0):
app = wx.App(redirect=False)
@@ -315,7 +318,7 @@
ip_addr = self.pyroserver.ip_addr
ip_addr = '' if ip_addr is None else ip_addr
dlg = ParamsEntryDialog(None, _("Enter the IP of the interface to bind"), defaultValue=ip_addr)
- dlg.SetTests([(re.compile('\d{1,3}(?:\.\d{1,3}){3}$').match, _("IP is not valid!")),
+ dlg.SetTests([(re.compile(r'\d{1,3}(?:\.\d{1,3}){3}$').match, _("IP is not valid!")), (lambda x:len([x for x in x.split(".") if 0 <= int(x) <= 255]) == 4,
if dlg.ShowModal() == wx.ID_OK:
@@ -324,7 +327,7 @@
def OnTaskBarChangePort(self, evt):
dlg = ParamsEntryDialog(None, _("Enter a port number "), defaultValue=str(self.pyroserver.port))
- dlg.SetTests([(UnicodeType.isdigit, _("Port number must be an integer!")), (lambda port: 0 <= int(port) <= 65535, _("Port number must be 0 <= port <= 65535!"))])
+ dlg.SetTests([(text.isdigit, _("Port number must be an integer!")), (lambda port: 0 <= int(port) <= 65535, _("Port number must be 0 <= port <= 65535!"))]) if dlg.ShowModal() == wx.ID_OK:
self.pyroserver.port = int(dlg.GetValue())
self.pyroserver.Restart()
@@ -368,9 +371,9 @@
wx.CallAfter(wx.GetApp().ExitMainLoop)
def UpdateIcon(self, plcstatus):
- if plcstatus is "Started":
+ if plcstatus is PlcStatus.Started: currenticon = self.MakeIcon(starticon)
- elif plcstatus is "Stopped":
+ elif plcstatus is PlcStatus.Stopped: currenticon = self.MakeIcon(stopicon)
currenticon = self.MakeIcon(defaulticon)
--- a/IDEFrame.py Fri Nov 23 11:01:20 2018 +0100
+++ b/IDEFrame.py Fri Nov 23 12:13:24 2018 +0100
@@ -23,14 +23,17 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from __future__ import absolute_import
+from __future__ import division
-from types import TupleType
+from future.builtins import \ +from six.moves import cPickle, xrange from editors.EditorPanel import EditorPanel
from editors.SFCViewer import SFC_Viewer
@@ -108,7 +111,7 @@
def DecodeFileSystemPath(path, is_base64=True):
path = base64.decodestring(path)
- return unicode(path, sys.getfilesystemencoding())
+ return text(path, sys.getfilesystemencoding()) def AppendMenu(parent, help, id, kind, text):
@@ -200,22 +203,22 @@
raise ValueError("Not possible")
if tab["size"][0] == rect.width:
if tab["pos"][1] == rect.y:
- split = (wx.TOP, float(tab["size"][1]) / float(rect.height))
+ split = (wx.TOP, tab["size"][1] / rect.height) split_rect = wx.Rect(rect.x, rect.y + tab["size"][1] + TAB_BORDER,
rect.width, rect.height - tab["size"][1] - TAB_BORDER)
elif tab["pos"][1] == rect.height + 1 - tab["size"][1]:
- split = (wx.BOTTOM, 1.0 - float(tab["size"][1]) / float(rect.height))
+ split = (wx.BOTTOM, 1.0 - tab["size"][1] / rect.height) split_rect = wx.Rect(rect.x, rect.y,
rect.width, rect.height - tab["size"][1] - TAB_BORDER)
elif tab["size"][1] == rect.height:
if tab["pos"][0] == rect.x:
- split = (wx.LEFT, float(tab["size"][0]) / float(rect.width))
+ split = (wx.LEFT, tab["size"][0] / rect.width) split_rect = wx.Rect(rect.x + tab["size"][0] + TAB_BORDER, rect.y,
rect.width - tab["size"][0] - TAB_BORDER, rect.height)
elif tab["pos"][0] == rect.width + 1 - tab["size"][0]:
- split = (wx.RIGHT, 1.0 - float(tab["size"][0]) / float(rect.width))
+ split = (wx.RIGHT, 1.0 - tab["size"][0] / rect.width) split_rect = wx.Rect(rect.x, rect.y,
rect.width - tab["size"][0] - TAB_BORDER, rect.height)
@@ -833,7 +836,7 @@
def LoadTabLayout(self, notebook, tabs, mode="all", first_index=None):
- if isinstance(tabs, ListType):
+ if isinstance(tabs, list): raise ValueError("Not supported")
@@ -2435,7 +2438,7 @@
result = self.Controler.PastePou(pou_type, pou_xml)
- if not isinstance(result, TupleType):
+ if not isinstance(result, tuple): self.ShowErrorMessage(result)
self._Refresh(TITLE, EDITORTOOLBAR, FILEMENU, EDITMENU, PROJECTTREE, LIBRARYTREE)
@@ -2591,7 +2594,7 @@
- return (x / y) + {True: 0, False: 1}[(x % y) == 0]
+ return (x // y) + {True: 0, False: 1}[(x % y) == 0] class GraphicPrintout(wx.Printout):
@@ -2638,8 +2641,8 @@
ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()
pw, ph = self.GetPageSizePixels()
dw, dh = dc.GetSizeTuple()
- Xscale = (float(dw) * float(ppiPrinterX)) / (float(pw) * 25.4)
- Yscale = (float(dh) * float(ppiPrinterY)) / (float(ph) * 25.4)
+ Xscale = (dw * ppiPrinterX) / (pw * 25.4) + Yscale = (dh * ppiPrinterY) / (ph * 25.4) fontsize = self.FontSize * Yscale
@@ -2661,10 +2664,10 @@
# Calculate the position on the DC for centering the graphic
posX = area_width * ((page - 1) % self.PageGrid[0])
- posY = area_height * ((page - 1) / self.PageGrid[0])
+ posY = area_height * ((page - 1) // self.PageGrid[0]) - scaleX = float(area_width) / float(self.PageSize[0])
- scaleY = float(area_height) / float(self.PageSize[1])
+ scaleX = area_width / self.PageSize[0] + scaleY = area_height / self.PageSize[1] scale = min(scaleX, scaleY)
# Set the scale and origin
--- a/PLCControler.py Fri Nov 23 11:01:20 2018 +0100
+++ b/PLCControler.py Fri Nov 23 12:13:24 2018 +0100
@@ -25,12 +25,14 @@
from __future__ import absolute_import
-from types import TupleType
+from __future__ import division from copy import deepcopy
from time import localtime
+from functools import reduce +from future.builtins import round import util.paths as paths
@@ -43,8 +45,8 @@
from graphics.GraphicCommons import *
from PLCGenerator import *
-duration_model = re.compile("(?:([0-9]{1,2})h)?(?:([0-9]{1,2})m(?!s))?(?:([0-9]{1,2})s)?(?:([0-9]{1,3}(?:\.[0-9]*)?)ms)?")
-VARIABLE_NAME_SUFFIX_MODEL = re.compile('(\d+)$')
+duration_model = re.compile(r"(?:([0-9]{1,2})h)?(?:([0-9]{1,2})m(?!s))?(?:([0-9]{1,2})s)?(?:([0-9]{1,3}(?:\.[0-9]*)?)ms)?") +VARIABLE_NAME_SUFFIX_MODEL = re.compile(r'(\d+)$') ScriptDirectory = paths.AbsDir(__file__)
@@ -461,7 +463,7 @@
self.ProgramFilePath = filepath
return program_text, errors, warnings
except PLCGenException as ex:
- errors.append(ex.message)
errors.append("No project opened")
return "", errors, warnings
@@ -873,7 +875,7 @@
tempvar.setname(var.Name)
var_type = PLCOpenParser.CreateElement("type", "variable")
- if isinstance(var.Type, TupleType):
+ if isinstance(var.Type, tuple): if var.Type[0] == "array":
_array_type, base_type_name, dimensions = var.Type
array = PLCOpenParser.CreateElement("array", "dataType")
@@ -1366,7 +1368,7 @@
def IsLocatableType(self, typename, debug=False):
- if isinstance(typename, TupleType) or self.GetBlockType(typename) is not None:
+ if isinstance(typename, tuple) or self.GetBlockType(typename) is not None: # the size of these types is implementation dependend
@@ -1379,7 +1381,7 @@
def IsEnumeratedType(self, typename, debug=False):
- if isinstance(typename, TupleType):
+ if isinstance(typename, tuple): datatype = self.GetDataType(typename, debug)
@@ -1393,7 +1395,7 @@
def IsSubrangeType(self, typename, exclude=None, debug=False):
- if isinstance(typename, TupleType):
+ if isinstance(typename, tuple): datatype = self.GetDataType(typename, debug)
@@ -1612,7 +1614,7 @@
element = PLCOpenParser.CreateElement("variable", "struct")
element.setname(element_infos["Name"])
element_type = PLCOpenParser.CreateElement("type", "variable")
- if isinstance(element_infos["Type"], TupleType):
+ if isinstance(element_infos["Type"], tuple): if element_infos["Type"][0] == "array":
_array_type, base_type_name, dimensions = element_infos["Type"]
array = PLCOpenParser.CreateElement("array", "dataType")
@@ -1939,8 +1941,8 @@
x, y, width, height = bbox.bounding_box()
- new_pos[0] -= width / 2
- new_pos[1] -= height / 2
+ new_pos[0] -= width // 2 + new_pos[1] -= height // 2 new_pos = map(lambda x: x + 30, new_pos)
if scaling[0] != 0 and scaling[1] != 0:
--- a/PLCGenerator.py Fri Nov 23 11:01:20 2018 +0100
+++ b/PLCGenerator.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,8 +24,10 @@
from __future__ import absolute_import
+from functools import reduce +from six.moves import xrange from plcopen import PLCOpenParser
from plcopen.structures import *
from plcopen.types_enums import *
@@ -708,7 +710,7 @@
def ComputeConnectionTypes(self, pou):
- if isinstance(body, ListType):
+ if isinstance(body, list): body_content = body.getcontent()
body_type = body_content.getLocalTag()
@@ -941,7 +943,7 @@
def ComputeProgram(self, pou):
- if isinstance(body, ListType):
+ if isinstance(body, list): body_content = body.getcontent()
body_type = body_content.getLocalTag()
@@ -1025,7 +1027,7 @@
self.GenerateBlock(instance, block_infos, body, None)
- raise PLCGenException(e.message)
+ raise PLCGenException(str(e)) elif isinstance(instance, ConnectorClass):
connector = instance.getname()
if self.ComputedConnectors.get(connector, None):
@@ -1049,7 +1051,7 @@
uncomputed_index = range(len(paths))
for num, path in enumerate(paths):
- if isinstance(path, ListType):
+ if isinstance(path, list): str_path = str(path[-1:])
same_paths.setdefault(str_path, [])
@@ -1303,7 +1305,7 @@
paths.append(str(self.GenerateBlock(next, block_infos, body, connection, order, to_inout)))
- raise PLCGenException(e.message)
+ raise PLCGenException(str(e)) elif isinstance(next, ContinuationClass):
computed_value = self.ComputedConnectors.get(name, None)
@@ -1339,7 +1341,7 @@
paths.append([variable, tuple(factorized_paths)])
paths.append([variable] + factorized_paths)
- elif isinstance(result[0], ListType):
+ elif isinstance(result[0], list): paths.append([variable] + result[0])
elif result[0] is not None:
paths.append([variable, result[0]])
@@ -1350,7 +1352,7 @@
def ComputePaths(self, paths, first=False):
- if isinstance(paths, TupleType):
+ if isinstance(paths, tuple): @@ -1359,7 +1361,7 @@
return JoinList([(" OR ", ())], vars)
return [("(", ())] + JoinList([(" OR ", ())], vars) + [(")", ())]
- elif isinstance(paths, ListType):
+ elif isinstance(paths, list): vars = [self.ComputePaths(path) for path in paths]
return JoinList([(" AND ", ())], vars)
@@ -1421,7 +1423,7 @@
if connections is not None and len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- if isinstance(body, ListType):
+ if isinstance(body, list): return body.getcontentInstance(instanceLocalId)
@@ -1433,7 +1435,7 @@
if connections is not None and len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- if isinstance(body, ListType):
+ if isinstance(body, list): instances.append(body.getcontentInstance(instanceLocalId))
@@ -1454,7 +1456,7 @@
if connections is not None and len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- if isinstance(body, ListType):
+ if isinstance(body, list): instance = body.getcontentInstance(instanceLocalId)
if isinstance(instance, TransitionClass):
@@ -1488,7 +1490,7 @@
if connections is not None and len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- if isinstance(body, ListType):
+ if isinstance(body, list): instance = body.getcontentInstance(instanceLocalId)
if isinstance(instance, TransitionClass):
@@ -1513,7 +1515,7 @@
if connections is not None and len(connections) == 1:
stepLocalId = connections[0].getrefLocalId()
- if isinstance(body, ListType):
+ if isinstance(body, list): step = body.getcontentInstance(stepLocalId)
self.GenerateSFCStep(step, pou)
@@ -1560,7 +1562,7 @@
if connections is not None and len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- if isinstance(body, ListType):
+ if isinstance(body, list): instance = body.getcontentInstance(instanceLocalId)
if isinstance(instance, StepClass):
@@ -1615,7 +1617,7 @@
self.TagName = previous_tagname
elif transitionValues["type"] == "connection":
- if isinstance(body, ListType):
+ if isinstance(body, list): connections = transitionValues["value"].getconnections()
if connections is not None:
--- a/ProjectController.py Fri Nov 23 11:01:20 2018 +0100
+++ b/ProjectController.py Fri Nov 23 12:13:24 2018 +0100
@@ -36,11 +36,11 @@
-from types import ListType
from threading import Timer
from datetime import datetime
from weakref import WeakKeyDictionary
-from itertools import izip
+from functools import reduce +from six.moves import xrange @@ -67,13 +67,13 @@
base_folder = paths.AbsParentDir(__file__)
MATIEC_ERROR_MODEL = re.compile(
- ".*\.st:(\d+)-(\d+)\.\.(\d+)-(\d+): (?:error)|(?:warning) : (.*)$")
+ r".*\.st:(\d+)-(\d+)\.\.(\d+)-(\d+): (?:error)|(?:warning) : (.*)$") def ExtractChildrenTypesFromCatalog(catalog):
for n, d, _h, c in catalog:
- if isinstance(c, ListType):
+ if isinstance(c, list): children_types.extend(ExtractChildrenTypesFromCatalog(c))
children_types.append((n, GetClassImporter(c), d))
@@ -83,7 +83,7 @@
def ExtractMenuItemsFromCatalog(catalog):
for n, d, h, c in catalog:
- if isinstance(c, ListType):
+ if isinstance(c, list): children = ExtractMenuItemsFromCatalog(c)
@@ -712,7 +712,7 @@
lines = [line.strip() for line in location_file.readlines()]
# This regular expression parses the lines genereated by IEC2C
LOCATED_MODEL = re.compile(
- "__LOCATED_VAR\((?P<IEC_TYPE>[A-Z]*),(?P<NAME>[_A-Za-z0-9]*),(?P<DIR>[QMI])(?:,(?P<SIZE>[XBWDL]))?,(?P<LOC>[,0-9]*)\)")
+ r"__LOCATED_VAR\((?P<IEC_TYPE>[A-Z]*),(?P<NAME>[_A-Za-z0-9]*),(?P<DIR>[QMI])(?:,(?P<SIZE>[XBWDL]))?,(?P<LOC>[,0-9]*)\)") result = LOCATED_MODEL.match(line)
@@ -770,7 +770,7 @@
plc_file = open(self._getIECcodepath(), "r")
- for dummy in plc_file.xreadlines():
+ for dummy in plc_file.readlines(): plc_file = open(self._getIECcodepath(), "a")
@@ -858,9 +858,9 @@
lambda filename: os.path.join(buildpath, filename), H_files)
- with file(H_file, 'r') as original:
+ with open(H_file, 'r') as original: - with file(H_file, 'w') as modified:
+ with open(H_file, 'w') as modified: modified.write('#include "beremiz.h"\n' + data)
self.logger.write(_("Extracting Located Variables...\n"))
@@ -952,7 +952,7 @@
- for line in open(csvfile, 'r').xreadlines():
+ for line in open(csvfile, 'r').readlines(): strippedline = line.strip()
if strippedline.startswith("//"):
@@ -1293,7 +1293,7 @@
self._IECCodeView.SetTextSyntax("ALL")
self._IECCodeView.SetKeywords(IEC_KEYWORDS)
- text = file(plc_file).read()
+ text = open(plc_file).read() text = '(* No IEC code have been generated at that time ! *)'
self._IECCodeView.SetText(text=text)
@@ -1503,7 +1503,7 @@
debug_vars = UnpackDebugBuffer(
debug_buff, self.TracedIECTypes)
if debug_vars is not None and len(debug_vars) == len(self.TracedIECPath):
- for IECPath, values_buffer, value in izip(
+ for IECPath, values_buffer, value in zip( @@ -1682,7 +1682,7 @@
debug_ticks, buffers = self.SnapshotAndResetDebugValuesBuffers()
if len(self.TracedIECPath) == len(buffers):
- for IECPath, values in izip(self.TracedIECPath, buffers):
+ for IECPath, values in zip(self.TracedIECPath, buffers): IECPath, "NewValues", debug_ticks, values)
--- a/controls/DebugVariablePanel/DebugVariableGraphicViewer.py Fri Nov 23 11:01:20 2018 +0100
+++ b/controls/DebugVariablePanel/DebugVariableGraphicViewer.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,7 +24,7 @@
from __future__ import absolute_import
-from types import TupleType
+from __future__ import division from time import time as gettime
from cycler import cycler
@@ -36,6 +36,7 @@
from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap
from matplotlib.backends.backend_agg import FigureCanvasAgg
from mpl_toolkits.mplot3d import Axes3D
+from six.moves import xrange from editors.DebugViewer import REFRESH_PERIOD
from controls.DebugVariablePanel.DebugVariableViewer import *
@@ -156,7 +157,7 @@
# Check that data is valid regarding DebugVariablePanel
- if not isinstance(values, TupleType):
+ if not isinstance(values, tuple): message = _("Invalid value \"%s\" for debug variable") % data
@@ -194,7 +195,7 @@
# Get Before which Viewer the variable has to be moved or added
# according to the position of mouse in Viewer.
# Drag'n Drop is an internal is an internal move inside Debug
@@ -442,10 +443,10 @@
x = rect.x + (- w - offset
else rect.width + offset)
- y = rect.y + (rect.height - h) / 2
+ y = rect.y + (rect.height - h) // 2 - x = rect.x + (rect.width - w) / 2
+ x = rect.x + (rect.width - w) // 2 y = rect.y + (- h - offset
else rect.height + offset)
@@ -800,7 +801,7 @@
self.ParentWindow.SetCanvasPosition(
(self.MouseStartPos.x - event.x) *
- (end_tick - start_tick) / rect.width)
+ (end_tick - start_tick) // rect.width) def OnCanvasScroll(self, event):
@@ -818,7 +819,7 @@
tick = (start_tick + end_tick) / 2.
- self.ParentWindow.ChangeRange(int(-event.step) / 3, tick)
+ self.ParentWindow.ChangeRange(int(-event.step) // 3, tick) # Vetoing event to prevent parent panel to be scrolled
self.ParentWindow.VetoScrollEvent = True
@@ -926,7 +927,7 @@
# Mouse is over Viewer figure and graph is not 3D
bbox = self.GetAxesBoundingBox()
if bbox.InsideXY(x, y) and not self.Is3DCanvas():
- rect = wx.Rect(bbox.x, bbox.y, bbox.width / 2, bbox.height)
+ rect = wx.Rect(bbox.x, bbox.y, bbox.width // 2, bbox.height) # Mouse is over Viewer left part of figure
self.SetHighlight(HIGHLIGHT_LEFT)
@@ -936,7 +937,7 @@
self.SetHighlight(HIGHLIGHT_RIGHT)
# Mouse is over upper part of Viewer
# Viewer is upper one in Debug Variable Panel, show highlight
if self.ParentWindow.IsViewerFirst(self):
self.SetHighlight(HIGHLIGHT_BEFORE)
@@ -1324,11 +1325,11 @@
# Get value and forced flag for each variable displayed in graph
# If cursor tick is not defined get value and flag of last received
# or get value and flag of variable at cursor tick
- values, forced = apply(zip, [(
item.GetValue(self.CursorTick)
if self.CursorTick is not None
- else (item.GetValue(), item.IsForced())
- ) for item in self.Items])
+ else (item.GetValue(), item.IsForced())) for item in self.Items] + values, forced = zip(*args) # Get path of each variable displayed simplified using panel variable
@@ -1399,11 +1400,11 @@
destGC.SetPen(HIGHLIGHT['DROP_PEN'])
destGC.SetBrush(HIGHLIGHT['DROP_BRUSH'])
- x_offset = (bbox.width / 2
+ x_offset = (bbox.width // 2 if self.Highlight == HIGHLIGHT_RIGHT
destGC.DrawRectangle(bbox.x + x_offset, bbox.y,
- bbox.width / 2, bbox.height)
+ bbox.width // 2, bbox.height) # Draw other Viewer common elements
self.DrawCommonElements(destGC, self.GetButtons())
--- a/controls/DebugVariablePanel/DebugVariablePanel.py Fri Nov 23 11:01:20 2018 +0100
+++ b/controls/DebugVariablePanel/DebugVariablePanel.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,7 +24,8 @@
from __future__ import absolute_import
-from types import TupleType
+from __future__ import division +from functools import reduce @@ -123,7 +124,7 @@
# Check that data is valid regarding DebugVariablePanel
- if not isinstance(values, TupleType):
+ if not isinstance(values, tuple): message = _("Invalid value \"%s\" for debug variable") % data
@@ -307,7 +308,7 @@
# Calculate range to apply to data
self.CurrentRange = self.RANGE_VALUES[
- self.CanvasRange.GetSelection()][1] / self.Ticktime
+ self.CanvasRange.GetSelection()][1] // self.Ticktime def SetDataProducer(self, producer):
@@ -390,7 +391,7 @@
cursor_tick_idx = numpy.argmin(numpy.abs(self.Ticks - cursor_tick))
if self.Ticks[cursor_tick_idx] == self.CursorTick:
- min(cursor_tick_idx + abs(move) / move,
+ min(cursor_tick_idx + abs(move) // move, self.CursorTick = self.Ticks[cursor_tick_idx]
@@ -488,18 +489,18 @@
merge_type = GRAPH_PARALLEL
if isinstance(panel, DebugVariableTextViewer) or panel.Is3DCanvas():
- if y_mouse > yw + height / 2:
+ if y_mouse > yw + height // 2: wx.CallAfter(self.MoveValue, variable, idx, True)
rect = panel.GetAxesBoundingBox(True)
if rect.InsideXY(x_mouse, y_mouse):
- merge_rect = wx.Rect(rect.x, rect.y, rect.width / 2., rect.height)
+ merge_rect = wx.Rect(rect.x, rect.y, rect.width // 2, rect.height) if merge_rect.InsideXY(x_mouse, y_mouse):
merge_type = GRAPH_ORTHOGONAL
wx.CallAfter(self.MergeGraphs, variable, idx, merge_type, force=True)
- if y_mouse > yw + height / 2:
+ if y_mouse > yw + height // 2: wx.CallAfter(self.MoveValue, variable, idx, True)
@@ -547,16 +548,16 @@
tick_duration = int(tick * self.Ticktime)
- for value, format in [(tick_duration / DAY, _("%dd")),
- ((tick_duration % DAY) / HOUR, _("%dh")),
- ((tick_duration % HOUR) / MINUTE, _("%dm")),
- ((tick_duration % MINUTE) / SECOND, _("%ds"))]:
+ for value, format in [(tick_duration // DAY, _("%dd")), + ((tick_duration % DAY) // HOUR, _("%dh")), + ((tick_duration % HOUR) // MINUTE, _("%dm")), + ((tick_duration % MINUTE) // SECOND, _("%ds"))]: if value > 0 or not_null:
duration += format % value
- duration += _("%03gms") % (float(tick_duration % SECOND) / MILLISECOND)
+ duration += _("%03gms") % ((tick_duration % SECOND) / MILLISECOND) self.TickTimeLabel.SetLabel("t: %s" % duration)
self.TickLabel.SetLabel("")
@@ -638,7 +639,7 @@
def OnRangeChanged(self, event):
- self.CurrentRange = self.RANGE_VALUES[self.CanvasRange.GetSelection()][1] / self.Ticktime
+ self.CurrentRange = self.RANGE_VALUES[self.CanvasRange.GetSelection()][1] // self.Ticktime self.CanvasRange.SetValue(str(self.CurrentRange))
wx.CallAfter(self.RefreshRange)
@@ -909,11 +910,12 @@
xstart, ystart = self.GraphicsWindow.GetViewStart()
window_size = self.GraphicsWindow.GetClientSize()
vwidth, vheight = self.GraphicsSizer.GetMinSize()
- posx = max(0, min(xstart, (vwidth - window_size[0]) / SCROLLBAR_UNIT))
- posy = max(0, min(ystart, (vheight - window_size[1]) / SCROLLBAR_UNIT))
+ posx = max(0, min(xstart, (vwidth - window_size[0]) // SCROLLBAR_UNIT)) + posy = max(0, min(ystart, (vheight - window_size[1]) // SCROLLBAR_UNIT)) self.GraphicsWindow.Scroll(posx, posy)
self.GraphicsWindow.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT,
- vwidth / SCROLLBAR_UNIT, vheight / SCROLLBAR_UNIT,
+ vwidth // SCROLLBAR_UNIT, + vheight // SCROLLBAR_UNIT, def OnGraphicsWindowEraseBackground(self, event):
--- a/controls/EnhancedStatusBar.py Fri Nov 23 11:01:20 2018 +0100
+++ b/controls/EnhancedStatusBar.py Fri Nov 23 12:13:24 2018 +0100
@@ -56,6 +56,7 @@
from __future__ import absolute_import
+from __future__ import division # Horizontal Alignment Constants
@@ -145,7 +146,7 @@
widget.SetPosition((xpos, rect.y-1))
elif verticalalignment == ESB_ALIGN_CENTER_VERTICAL:
if widgetsize[1] < rect.height - 1:
- diffs = (rect.height - widgetsize[1])/2
+ diffs = (rect.height - widgetsize[1]) // 2 widget.SetPosition((xpos, rect.y+diffs))
widget.SetSize((widgetsize[0], rect.height-2))
@@ -163,7 +164,7 @@
widget.SetPosition((xpos, rect.y-1))
elif verticalalignment == ESB_ALIGN_CENTER_VERTICAL:
if widgetsize[1] < rect.height - 1:
- diffs = (rect.height - widgetsize[1])/2
+ diffs = (rect.height - widgetsize[1]) // 2 widget.SetPosition((xpos, rect.y+diffs))
widget.SetSize((widgetsize[0], rect.height-2))
@@ -175,13 +176,13 @@
elif horizontalalignment == ESB_ALIGN_CENTER_HORIZONTAL:
- xpos = rect.x + (rect.width - widgetsize[0])/2 - 1
+ xpos = rect.x + (rect.width - widgetsize[0]) // 2 - 1 if verticalalignment == ESB_EXACT_FIT:
widget.SetSize((widgetsize[0], rect.height))
widget.SetPosition((xpos, rect.y))
elif verticalalignment == ESB_ALIGN_CENTER_VERTICAL:
if widgetsize[1] < rect.height - 1:
- diffs = (rect.height - widgetsize[1])/2
+ diffs = (rect.height - widgetsize[1]) // 2 widget.SetPosition((xpos, rect.y+diffs))
widget.SetSize((widgetsize[0], rect.height-1))
@@ -221,19 +222,20 @@
if self.GetFieldsCount() <= pos:
- raise "\nERROR: EnhancedStatusBar has a max of %d items, you tried to set item #%d" % (self.GetFieldsCount(), pos)
+ raise ValueError("\nERROR: EnhancedStatusBar has a max of %d items, you tried to set item #%d" % + (self.GetFieldsCount(), pos)) if horizontalalignment not in [ESB_ALIGN_CENTER_HORIZONTAL, ESB_EXACT_FIT,
ESB_ALIGN_LEFT, ESB_ALIGN_RIGHT]:
- raise '\nERROR: Parameter "horizontalalignment" Should Be One Of '\
- '"ESB_ALIGN_CENTER_HORIZONTAL", "ESB_ALIGN_LEFT", "ESB_ALIGN_RIGHT"' \
+ raise ValueError('\nERROR: Parameter "horizontalalignment" Should Be One Of ' + '"ESB_ALIGN_CENTER_HORIZONTAL", "ESB_ALIGN_LEFT", "ESB_ALIGN_RIGHT"' if verticalalignment not in [ESB_ALIGN_CENTER_VERTICAL, ESB_EXACT_FIT,
ESB_ALIGN_TOP, ESB_ALIGN_BOTTOM]:
- raise '\nERROR: Parameter "verticalalignment" Should Be One Of '\
- '"ESB_ALIGN_CENTER_VERTICAL", "ESB_ALIGN_TOP", "ESB_ALIGN_BOTTOM"' \
+ raise ValueError('\nERROR: Parameter "verticalalignment" Should Be One Of ' + '"ESB_ALIGN_CENTER_VERTICAL", "ESB_ALIGN_TOP", "ESB_ALIGN_BOTTOM"' self.RemoveChild(self._items[pos].widget)
--- a/controls/LogViewer.py Fri Nov 23 11:01:20 2018 +0100
+++ b/controls/LogViewer.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,12 +24,14 @@
from __future__ import absolute_import
+from __future__ import division from datetime import datetime
from time import time as gettime
from weakref import proxy
+from six.moves import xrange from controls.CustomToolTip import CustomToolTip, TOOLTIP_WAIT_PERIOD
from editors.DebugViewer import DebugViewer, REFRESH_PERIOD
@@ -43,11 +45,11 @@
def ArrowPoints(direction, width, height, xoffset, yoffset):
return [wx.Point(xoffset + 1, yoffset + height - 2),
- wx.Point(xoffset + width / 2, yoffset + 1),
+ wx.Point(xoffset + width // 2, yoffset + 1), wx.Point(xoffset + width - 1, yoffset + height - 2)]
return [wx.Point(xoffset + 1, yoffset - height + 1),
- wx.Point(xoffset + width / 2, yoffset - 2),
+ wx.Point(xoffset + width // 2, yoffset - 2), wx.Point(xoffset + width - 1, yoffset - height + 1)]
@@ -124,7 +126,7 @@
thumb_size = range_rect.height * THUMB_SIZE_RATIO
thumb_range = range_rect.height - thumb_size
self.RefreshThumbPosition(
- max(-1., min((posy - self.ThumbScrollingStartPos.y) * 2. / thumb_range, 1.)))
+ max(-1., min((posy - self.ThumbScrollingStartPos.y) * 2. // thumb_range, 1.))) def OnResize(self, event):
@@ -146,11 +148,11 @@
gc.SetPen(wx.Pen(wx.NamedColour("GREY"), 3))
gc.SetBrush(wx.GREY_BRUSH)
- gc.DrawLines(ArrowPoints(wx.TOP, width * 0.75, width * 0.5, 2, (width + height) / 4 - 3))
- gc.DrawLines(ArrowPoints(wx.TOP, width * 0.75, width * 0.5, 2, (width + height) / 4 + 3))
+ gc.DrawLines(ArrowPoints(wx.TOP, width * 0.75, width * 0.5, 2, (width + height) // 4 - 3)) + gc.DrawLines(ArrowPoints(wx.TOP, width * 0.75, width * 0.5, 2, (width + height) // 4 + 3)) - gc.DrawLines(ArrowPoints(wx.BOTTOM, width * 0.75, width * 0.5, 2, (height * 3 - width) / 4 + 3))
- gc.DrawLines(ArrowPoints(wx.BOTTOM, width * 0.75, width * 0.5, 2, (height * 3 - width) / 4 - 3))
+ gc.DrawLines(ArrowPoints(wx.BOTTOM, width * 0.75, width * 0.5, 2, (height * 3 - width) // 4 + 3)) + gc.DrawLines(ArrowPoints(wx.BOTTOM, width * 0.75, width * 0.5, 2, (height * 3 - width) // 4 - 3)) thumb_rect = self.GetThumbRect()
exclusion_rect = wx.Rect(thumb_rect.x, thumb_rect.y,
@@ -222,8 +224,8 @@
w, h = dc.GetTextExtent(self.Label)
- self.Position.x + (self.Size.width - w) / 2,
- self.Position.y + (self.Size.height - h) / 2)
+ self.Position.x + (self.Size.width - w) // 2, + self.Position.y + (self.Size.height - h) // 2) @@ -259,19 +261,19 @@
datetime_text = self.Date.strftime("%d/%m/%y %H:%M")
dw, dh = dc.GetTextExtent(datetime_text)
- dc.DrawText(datetime_text, (width - dw) / 2, offset + (DATE_INFO_SIZE - dh) / 2)
+ dc.DrawText(datetime_text, (width - dw) // 2, offset + (DATE_INFO_SIZE - dh) // 2) seconds_text = "%12.9f" % self.Seconds
sw, sh = dc.GetTextExtent(seconds_text)
- dc.DrawText(seconds_text, 5, offset + (MESSAGE_INFO_SIZE - sh) / 2)
+ dc.DrawText(seconds_text, 5, offset + (MESSAGE_INFO_SIZE - sh) // 2) bw, bh = self.LevelBitmap.GetWidth(), self.LevelBitmap.GetHeight()
- dc.DrawBitmap(self.LevelBitmap, 10 + sw, offset + (MESSAGE_INFO_SIZE - bh) / 2)
+ dc.DrawBitmap(self.LevelBitmap, 10 + sw, offset + (MESSAGE_INFO_SIZE - bh) // 2) text = self.Message.replace("\n", " ")
_mw, mh = dc.GetTextExtent(text)
- dc.DrawText(text, 15 + sw + bw, offset + (MESSAGE_INFO_SIZE - mh) / 2)
+ dc.DrawText(text, 15 + sw + bw, offset + (MESSAGE_INFO_SIZE - mh) // 2) def GetHeight(self, draw_date):
@@ -611,7 +613,7 @@
def ScrollMessagePanelByPage(self, page):
if self.CurrentMessage is not None:
_width, height = self.MessagePanel.GetClientSize()
- message_per_page = max(1, (height - DATE_INFO_SIZE) / MESSAGE_INFO_SIZE - 1)
+ message_per_page = max(1, (height - DATE_INFO_SIZE) // MESSAGE_INFO_SIZE - 1) self.ScrollMessagePanel(page * message_per_page)
def ScrollMessagePanelByTimestamp(self, seconds):
@@ -756,7 +758,7 @@
def OnMessagePanelMouseWheel(self, event):
- self.ScrollMessagePanel(event.GetWheelRotation() / event.GetWheelDelta())
+ self.ScrollMessagePanel(event.GetWheelRotation() // event.GetWheelDelta()) def OnMessagePanelEraseBackground(self, event):
--- a/controls/VariablePanel.py Fri Nov 23 11:01:20 2018 +0100
+++ b/controls/VariablePanel.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,12 +24,15 @@
from __future__ import absolute_import
+from __future__ import division -from types import TupleType, StringType, UnicodeType
+from builtins import str as text +from six import string_types +from six.moves import xrange from plcopen.structures import LOCATIONDATATYPES, TestIdentifier, IEC_KEYWORDS, DefaultType
from plcopen.VariableInfoCollector import _VariableInfos
@@ -98,8 +101,8 @@
"External": lambda x: {"Constant": "Constant"}.get(x, "")
-LOCATION_MODEL = re.compile("((?:%[IQM](?:\*|(?:[XBWLD]?[0-9]+(?:\.[0-9]+)*)))?)$")
-LOCATION_MODEL_SET = re.compile("((?:%[IQM](?:[XBWLD]?[0-9]+(?:\.[0-9]+)*))?)$")
+LOCATION_MODEL = re.compile(r"((?:%[IQM](?:\*|(?:[XBWLD]?[0-9]+(?:\.[0-9]+)*)))?)$") +LOCATION_MODEL_SET = re.compile(r"((?:%[IQM](?:[XBWLD]?[0-9]+(?:\.[0-9]+)*))?)$") # -------------------------------------------------------------------------------
@@ -137,10 +140,10 @@
if colname == "Initial Value":
value = getattr(self.data[row], colname, "")
- if colname == "Type" and isinstance(value, TupleType):
+ if colname == "Type" and isinstance(value, tuple): return "ARRAY [%s] OF %s" % (",".join(map("..".join, value[2])), value[1])
- if not isinstance(value, (StringType, UnicodeType)):
+ if not isinstance(value, string_types): if colname in ["Class", "Option"]:
@@ -277,7 +280,7 @@
message = _("Invalid value \"%s\" for variable grid element") % data
- if not isinstance(values, TupleType):
+ if not isinstance(values, tuple): message = _("Invalid value \"%s\" for variable grid element") % data
@@ -603,10 +606,10 @@
# increment location address
if row_content.Location != "" and LOCATION_MODEL_SET.match(row_content.Location):
old_location = row_content.Location
- model = re.compile("%[IQM][XBWLD]?(.*\.|)")
+ model = re.compile(r"%[IQM][XBWLD]?(.*\.|)") prefix = model.match(old_location).group(0)
addr = int(re.split(model, old_location)[-1]) + 1
- row_content.Location = prefix + unicode(addr)
+ row_content.Location = prefix + text(addr) if not row_content.Class:
row_content.Class = self.DefaultTypes.get(self.Filter, self.Filter)
@@ -682,7 +685,7 @@
self.VariablesGrid.SetColAttr(col, attr)
self.VariablesGrid.SetColMinimalWidth(col, self.ColSettings["size"][col])
if (panel_width > self.PanelWidthMin) and not self.ColSettings["fixed_size"][col]:
- self.VariablesGrid.SetColSize(col, int((float(self.ColSettings["size"][col])/stretch_cols_sum)*stretch_cols_width))
+ self.VariablesGrid.SetColSize(col, int((self.ColSettings["size"][col]/stretch_cols_sum)*stretch_cols_width)) self.VariablesGrid.SetColSize(col, self.ColSettings["size"][col])
@@ -697,7 +700,7 @@
def IsFunctionBlockType(self, name):
- if isinstance(name, TupleType) or \
+ if isinstance(name, tuple) or \ self.ElementType != "function" and self.BodyType in ["ST", "IL"]:
@@ -985,7 +988,7 @@
def AddVariableHighlight(self, infos, highlight_type):
- if isinstance(infos[0], TupleType):
+ if isinstance(infos[0], tuple): for i in xrange(*infos[0]):
self.Table.AddHighlight((i,) + infos[1:], highlight_type)
cell_visible = infos[0][0]
@@ -997,7 +1000,7 @@
self.RefreshHighlightsTimer.Start(int(REFRESH_HIGHLIGHT_PERIOD * 1000), oneShot=True)
def RemoveVariableHighlight(self, infos, highlight_type):
- if isinstance(infos[0], TupleType):
+ if isinstance(infos[0], tuple): for i in xrange(*infos[0]):
self.Table.RemoveHighlight((i,) + infos[1:], highlight_type)
--- a/editors/Viewer.py Fri Nov 23 11:01:20 2018 +0100
+++ b/editors/Viewer.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,12 +24,14 @@
from __future__ import absolute_import
+from __future__ import division from time import time as gettime
-from types import TupleType
from threading import Lock
+from future.builtins import round +from six.moves import xrange from plcopen.structures import *
from plcopen.types_enums import ComputePouName
@@ -275,7 +277,7 @@
message = _("Invalid value \"%s\" for viewer block") % data
- if not isinstance(values, TupleType):
+ if not isinstance(values, tuple): message = _("Invalid value \"%s\" for viewer block") % data
@@ -307,10 +309,10 @@
block = FBD_Block(self.ParentWindow, values[0], blockname, id, inputs=blockinputs)
width, height = block.GetMinSize()
- x = round(float(x) / float(scaling[0])) * scaling[0]
- y = round(float(y) / float(scaling[1])) * scaling[1]
- width = round(float(width) / float(scaling[0]) + 0.5) * scaling[0]
- height = round(float(height) / float(scaling[1]) + 0.5) * scaling[1]
+ x = round(x / scaling[0]) * scaling[0] + y = round(y / scaling[1]) * scaling[1] + width = round(width / scaling[0] + 0.5) * scaling[0] + height = round(height / scaling[1] + 0.5) * scaling[1] block.SetSize(width, height)
self.ParentWindow.AddBlock(block)
@@ -859,7 +861,7 @@
client_size = self.Editor.GetClientSize()
- mouse_pos = wx.Point(client_size[0] / 2, client_size[1] / 2)
+ mouse_pos = wx.Point(client_size[0] // 2, client_size[1] // 2) mouse_event = wx.MouseEvent(wx.EVT_MOUSEWHEEL.typeId)
mouse_event.x = mouse_pos.x
mouse_event.y = mouse_pos.y
@@ -1338,7 +1340,8 @@
maxy = int(maxy * self.ViewScale[1])
self.Editor.SetScrollbars(
SCROLLBAR_UNIT, SCROLLBAR_UNIT,
- round(maxx / SCROLLBAR_UNIT) + width_incr, round(maxy / SCROLLBAR_UNIT) + height_incr,
+ round(maxx / SCROLLBAR_UNIT) + width_incr, + round(maxy / SCROLLBAR_UNIT) + height_incr, def EnsureVisible(self, block):
@@ -1355,13 +1358,13 @@
xpos, ypos = xstart, ystart
if block_minx < screen_minx and block_maxx < screen_maxx:
- xpos -= (screen_minx - block_minx) / SCROLLBAR_UNIT + 1
+ xpos -= (screen_minx - block_minx) // SCROLLBAR_UNIT + 1 elif block_maxx > screen_maxx and block_minx > screen_minx:
- xpos += (block_maxx - screen_maxx) / SCROLLBAR_UNIT + 1
+ xpos += (block_maxx - screen_maxx) // SCROLLBAR_UNIT + 1 if block_miny < screen_miny and block_maxy < screen_maxy:
- ypos -= (screen_miny - block_miny) / SCROLLBAR_UNIT + 1
+ ypos -= (screen_miny - block_miny) // SCROLLBAR_UNIT + 1 elif block_maxy > screen_maxy and block_miny > screen_miny:
- ypos += (block_maxy - screen_maxy) / SCROLLBAR_UNIT + 1
+ ypos += (block_maxy - screen_maxy) // SCROLLBAR_UNIT + 1 def SelectInGroup(self, element):
@@ -2316,8 +2319,8 @@
new_pos = event.GetPosition()
xmax = self.GetScrollRange(wx.HORIZONTAL) - self.GetScrollThumb(wx.HORIZONTAL)
ymax = self.GetScrollRange(wx.VERTICAL) - self.GetScrollThumb(wx.VERTICAL)
- scrollx = max(0, self.StartScreenPos[0] - (new_pos[0] - self.StartMousePos[0]) / SCROLLBAR_UNIT)
- scrolly = max(0, self.StartScreenPos[1] - (new_pos[1] - self.StartMousePos[1]) / SCROLLBAR_UNIT)
+ scrollx = max(0, self.StartScreenPos[0] - (new_pos[0] - self.StartMousePos[0]) // SCROLLBAR_UNIT) + scrolly = max(0, self.StartScreenPos[1] - (new_pos[1] - self.StartMousePos[1]) // SCROLLBAR_UNIT) if scrollx > xmax or scrolly > ymax:
self.RefreshScrollBars(max(0, scrollx - xmax), max(0, scrolly - ymax))
self.Scroll(scrollx, scrolly)
@@ -2545,10 +2548,10 @@
variable = FBD_Variable(self, var_class, var_name, var_type, id)
width, height = variable.GetMinSize()
- x = round(float(x) / float(scaling[0])) * scaling[0]
- y = round(float(y) / float(scaling[1])) * scaling[1]
- width = round(float(width) / float(scaling[0]) + 0.5) * scaling[0]
- height = round(float(height) / float(scaling[1]) + 0.5) * scaling[1]
+ x = round(x / scaling[0]) * scaling[0] + y = round(y / scaling[1]) * scaling[1] + width = round(width / scaling[0] + 0.5) * scaling[0] + height = round(height / scaling[1] + 0.5) * scaling[1] variable.SetPosition(x, y)
variable.SetSize(width, height)
@@ -2565,8 +2568,8 @@
def GetScaledSize(self, width, height):
if self.Scaling is not None:
- width = round(float(width) / float(self.Scaling[0]) + 0.4) * self.Scaling[0]
- height = round(float(height) / float(self.Scaling[1]) + 0.4) * self.Scaling[1]
+ width = round(width / self.Scaling[0] + 0.4) * self.Scaling[0] + height = round(height / self.Scaling[1] + 0.4) * self.Scaling[1] def AddNewElement(self, element, bbox, wire=None, connector=None):
@@ -3451,7 +3454,7 @@
result = self.Controler.PasteEditedElementInstances(self.TagName, element, new_pos, middle, self.Debug)
- if not isinstance(result, (StringType, UnicodeType)):
+ if not isinstance(result, string_types): self.RefreshView(selection=result)
self.RefreshVariablePanel()
--- a/etherlab/CommonEtherCATFunction.py Fri Nov 23 11:01:20 2018 +0100
+++ b/etherlab/CommonEtherCATFunction.py Fri Nov 23 12:13:24 2018 +0100
@@ -9,8 +9,12 @@
# See COPYING file for copyrights details.
from __future__ import absolute_import
+from __future__ import division +from builtins import str as text mailbox_protocols = ["AoE", "EoE", "CoE", "FoE", "SoE", "VoE"]
@@ -182,7 +186,7 @@
@param controler: _EthercatSlaveCTN class in EthercatSlave.py
self.Controler = controler
+ self.HexDecode = codecs.getdecoder("hex_codec") # -------------------------------------------------------------------------------
@@ -549,7 +553,7 @@
- hex_len = (value_len / 2) * 2 + 2
+ hex_len = (value_len // 2) * 2 + 2 hex_data = ("{:0>"+str(hex_len)+"x}").format(decnum)
@@ -589,7 +593,7 @@
# append zero-filled padding data up to EEPROM size
for dummy in range(self.SmartViewInfosFromXML["eeprom_size"] - len(self.BinaryCode)):
- self.BinaryCode = self.BinaryCode + 'ff'.decode('hex')
+ self.BinaryCode = self.BinaryCode + self.HexDecode('ff')[0] @@ -648,7 +652,7 @@
- for dummy in range(length/2):
+ for dummy in range(length//2): @@ -808,7 +812,7 @@
for eeprom_element in device.getEeprom().getcontent():
if eeprom_element["name"] == "ByteSize":
eeprom_size = int(str(eeprom_element))
- data = "{:0>4x}".format(int(eeprom_element)/1024*8-1)
+ data = "{:0>4x}".format(int(eeprom_element)//1024*8-1) @@ -857,7 +861,7 @@
for index in range(eeprom_size):
- eeprom_binary = eeprom_binary + eeprom[index].decode('hex')
+ eeprom_binary = eeprom_binary + self.HexDecode(eeprom[index])[0] @@ -894,7 +898,7 @@
for element in device.getType().getcontent():
- if data != "" and isinstance(data, unicode):
+ if data != "" and isinstance(data, text): for vendor_spec_string in vendor_spec_strings:
if data == vendor_spec_string:
self.OrderIdx = vendor_spec_strings.index(data)+1
@@ -913,7 +917,7 @@
# element2-1; <EtherCATInfo>-<Descriptions>-<Devices>-<Device>-<GroupType>
data = device.getGroupType()
- if data is not None and isinstance(data, unicode):
+ if data is not None and isinstance(data, text): for vendor_spec_string in vendor_spec_strings:
if data == vendor_spec_string:
self.GroupIdx = vendor_spec_strings.index(data)+1
@@ -937,7 +941,7 @@
for device_item in group_etc["devices"]:
if device == device_item[1]:
- if data is not None and isinstance(data, unicode):
+ if data is not None and isinstance(data, text): for vendor_spec_string in vendor_spec_strings:
if data == vendor_spec_string:
self.GroupIdx = vendor_spec_strings.index(data)+1
@@ -961,7 +965,7 @@
for device_item in group_etc["devices"]:
if device == device_item[1]:
- if data != "" and isinstance(data, unicode):
+ if data != "" and isinstance(data, text): for vendor_spec_string in vendor_spec_strings:
if data == vendor_spec_string:
@@ -980,7 +984,7 @@
for element in device.getName():
if element.getLcId() == 1 or element.getLcId() == 1033:
data = element.getcontent()
- if data != "" and isinstance(data, unicode):
+ if data != "" and isinstance(data, text): for vendor_spec_string in vendor_spec_strings:
if data == vendor_spec_string:
self.NameIdx = vendor_spec_strings.index(data)+1
@@ -1000,7 +1004,7 @@
# element5-1; <EtherCATInfo>-<Descriptions>-<Devices>-<Device>-<Image16x14>
if device.getcontent() is not None:
data = device.getcontent()
- if data is not None and isinstance(data, unicode):
+ if data is not None and isinstance(data, text): for vendor_spec_string in vendor_spec_strings:
if data == vendor_spec_string:
self.ImgIdx = vendor_spec_strings.index(data)+1
@@ -1024,7 +1028,7 @@
for device_item in group_etc["devices"]:
if device == device_item[1]:
- if data is not None and isinstance(data, unicode):
+ if data is not None and isinstance(data, text): for vendor_spec_string in vendor_spec_strings:
if data == vendor_spec_string:
self.ImgIdx = vendor_spec_strings.index(data)+1
@@ -1132,15 +1136,15 @@
- eeprom.append("{:0>4x}".format(length/4)[2:4])
- eeprom.append("{:0>4x}".format(length/4)[0:2])
+ eeprom.append("{:0>4x}".format(length//4)[2:4]) + eeprom.append("{:0>4x}".format(length//4)[0:2]) # total numbers of strings
eeprom.append("{:0>2x}".format(count))
for element in [vendor_specific_data,
- for dummy in range(len(element)/2):
+ for dummy in range(len(element)//2): @@ -1285,11 +1289,11 @@
- eeprom.append("{:0>4x}".format((count+1)/2)[2:4])
- eeprom.append("{:0>4x}".format((count+1)/2)[0:2])
+ eeprom.append("{:0>4x}".format((count+1)//2)[2:4]) + eeprom.append("{:0>4x}".format((count+1)//2)[0:2]) - eeprom.append("{:0>4x}".format((count)/2)[2:4])
- eeprom.append("{:0>4x}".format((count)/2)[0:2])
+ eeprom.append("{:0>4x}".format((count)//2)[2:4]) + eeprom.append("{:0>4x}".format((count)//2)[0:2]) for dummy in range(count):
@@ -1332,9 +1336,9 @@
- eeprom.append("{:0>4x}".format(len(data)/4)[2:4])
- eeprom.append("{:0>4x}".format(len(data)/4)[0:2])
- for dummy in range(len(data)/2):
+ eeprom.append("{:0>4x}".format(len(data)//4)[2:4]) + eeprom.append("{:0>4x}".format(len(data)//4)[0:2]) + for dummy in range(len(data)//2): @@ -1440,10 +1444,10 @@
- eeprom.append("{:0>4x}".format(len(data)/4)[2:4])
- eeprom.append("{:0>4x}".format(len(data)/4)[0:2])
+ eeprom.append("{:0>4x}".format(len(data)//4)[2:4]) + eeprom.append("{:0>4x}".format(len(data)//4)[0:2]) - for dummy in range(len(data)/2):
+ for dummy in range(len(data)//2): @@ -1514,10 +1518,10 @@
- eeprom.append("{:0>4x}".format(len(data)/4)[2:4])
- eeprom.append("{:0>4x}".format(len(data)/4)[0:2])
+ eeprom.append("{:0>4x}".format(len(data)//4)[2:4]) + eeprom.append("{:0>4x}".format(len(data)//4)[0:2]) - for dummy in range(len(data)/2):
+ for dummy in range(len(data)//2): --- a/etherlab/ConfigEditor.py Fri Nov 23 11:01:20 2018 +0100
+++ b/etherlab/ConfigEditor.py Fri Nov 23 12:13:24 2018 +0100
@@ -10,9 +10,9 @@
# See COPYING file for copyrights details.
from __future__ import absolute_import
+from __future__ import division -from types import TupleType
@@ -71,7 +71,7 @@
ETHERCAT_INDEX_MODEL = re.compile("#x([0-9a-fA-F]{0,4})$")
ETHERCAT_SUBINDEX_MODEL = re.compile("#x([0-9a-fA-F]{0,2})$")
-LOCATION_MODEL = re.compile("(?:%[IQM](?:[XBWLD]?([0-9]+(?:\.[0-9]+)*)))$")
+LOCATION_MODEL = re.compile(r"(?:%[IQM](?:[XBWLD]?([0-9]+(?:\.[0-9]+)*)))$") class NodeVariablesSizer(wx.FlexGridSizer):
@@ -324,12 +324,12 @@
xstart, ystart = self.EtherCATManagementEditor.GetViewStart()
window_size = self.EtherCATManagementEditor.GetClientSize()
maxx, maxy = self.EtherCATManagementEditor.GetMinSize()
- posx = max(0, min(xstart, (maxx - window_size[0]) / SCROLLBAR_UNIT))
- posy = max(0, min(ystart, (maxy - window_size[1]) / SCROLLBAR_UNIT))
+ posx = max(0, min(xstart, (maxx - window_size[0]) // SCROLLBAR_UNIT)) + posy = max(0, min(ystart, (maxy - window_size[1]) // SCROLLBAR_UNIT)) self.EtherCATManagementEditor.Scroll(posx, posy)
self.EtherCATManagementEditor.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT,
+ maxx // SCROLLBAR_UNIT, + maxy // SCROLLBAR_UNIT, # -------------------------------------------------------------------------------------------------------
@@ -417,7 +417,7 @@
message = _("Invalid value \"%s\" for process variable") % data
- if not isinstance(values, TupleType):
+ if not isinstance(values, tuple): message = _("Invalid value \"%s\" for process variable") % data
if values is not None and col != wx.NOT_FOUND and row != wx.NOT_FOUND and 2 <= col <= 3:
@@ -479,7 +479,7 @@
message = _("Invalid value \"%s\" for startup command") % data
- if not isinstance(values, TupleType):
+ if not isinstance(values, tuple): message = _("Invalid value \"%s\" for startup command") % data
@@ -1056,12 +1056,12 @@
xstart, ystart = self.EthercatMasterEditor.GetViewStart()
window_size = self.EthercatMasterEditor.GetClientSize()
maxx, maxy = self.EthercatMasterEditorSizer.GetMinSize()
- posx = max(0, min(xstart, (maxx - window_size[0]) / SCROLLBAR_UNIT))
- posy = max(0, min(ystart, (maxy - window_size[1]) / SCROLLBAR_UNIT))
+ posx = max(0, min(xstart, (maxx - window_size[0]) // SCROLLBAR_UNIT)) + posy = max(0, min(ystart, (maxy - window_size[1]) // SCROLLBAR_UNIT)) self.EthercatMasterEditor.Scroll(posx, posy)
self.EthercatMasterEditor.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT,
+ maxx // SCROLLBAR_UNIT, + maxy // SCROLLBAR_UNIT, @@ -1421,11 +1421,11 @@
xstart, ystart = self.ModuleLibraryEditor.GetViewStart()
window_size = self.ModuleLibraryEditor.GetClientSize()
maxx, maxy = self.ModuleLibraryEditor.GetMinSize()
- posx = max(0, min(xstart, (maxx - window_size[0]) / SCROLLBAR_UNIT))
- posy = max(0, min(ystart, (maxy - window_size[1]) / SCROLLBAR_UNIT))
+ posx = max(0, min(xstart, (maxx - window_size[0]) // SCROLLBAR_UNIT)) + posy = max(0, min(ystart, (maxy - window_size[1]) // SCROLLBAR_UNIT)) self.ModuleLibraryEditor.Scroll(posx, posy)
self.ModuleLibraryEditor.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT,
+ maxx // SCROLLBAR_UNIT, + maxy // SCROLLBAR_UNIT, --- a/graphics/FBD_Objects.py Fri Nov 23 11:01:20 2018 +0100
+++ b/graphics/FBD_Objects.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,7 +24,9 @@
from __future__ import absolute_import
+from __future__ import division +from six.moves import xrange from graphics.GraphicCommons import *
from plcopen.structures import *
@@ -130,7 +132,7 @@
def GetTextBoundingBox(self):
# Calculate the size of the name outside the block
text_width, text_height = self.NameSize
- return wx.Rect(self.Pos.x + (self.Size[0] - text_width) / 2,
+ return wx.Rect(self.Pos.x + (self.Size[0] - text_width) // 2, self.Pos.y - (text_height + 2),
@@ -160,9 +162,9 @@
# Calculate the size for the connector lines
lines = max(len(self.Inputs), len(self.Outputs))
- linesize = max((self.Size[1] - BLOCK_LINE_SIZE) / lines, BLOCK_LINE_SIZE)
+ linesize = max((self.Size[1] - BLOCK_LINE_SIZE) // lines, BLOCK_LINE_SIZE) # Update inputs and outputs positions
- position = BLOCK_LINE_SIZE + linesize / 2
+ position = BLOCK_LINE_SIZE + linesize // 2 ypos = round_scaling(self.Pos.y + position, scaling[1]) - self.Pos.y
@@ -478,9 +480,9 @@
# Draw a rectangle with the block size
dc.DrawRectangle(self.Pos.x, self.Pos.y, self.Size[0] + 1, self.Size[1] + 1)
# Draw block name and block type
- name_pos = (self.Pos.x + (self.Size[0] - name_size[0]) / 2,
+ name_pos = (self.Pos.x + (self.Size[0] - name_size[0]) // 2, self.Pos.y - (name_size[1] + 2))
- type_pos = (self.Pos.x + (self.Size[0] - type_size[0]) / 2,
+ type_pos = (self.Pos.x + (self.Size[0] - type_size[0]) // 2, dc.DrawText(self.Name, name_pos[0], name_pos[1])
dc.DrawText(self.Type, type_pos[0], type_pos[1])
@@ -591,7 +593,7 @@
bbx_width = self.Size[0] + 2 * CONNECTOR_SIZE
bbx_width = self.Size[0] + CONNECTOR_SIZE
- bbx_x = min(bbx_x, self.Pos.x + (self.Size[0] - self.NameSize[0]) / 2)
+ bbx_x = min(bbx_x, self.Pos.x + (self.Size[0] - self.NameSize[0]) // 2) bbx_width = max(bbx_width, self.NameSize[0])
bbx_height = self.Size[1]
if self.ExecutionOrder != 0:
@@ -604,9 +606,9 @@
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
- position = round_scaling(self.Pos.y + self.Size[1] / 2, scaling[1]) - self.Pos.y
+ position = round_scaling(self.Pos.y + self.Size[1] // 2, scaling[1]) - self.Pos.y - position = self.Size[1] / 2
+ position = self.Size[1] // 2 self.Input.SetPosition(wx.Point(0, position))
@@ -777,8 +779,8 @@
name_size = self.NameSize
executionorder_size = self.ExecutionOrderSize
- text_pos = (self.Pos.x + (self.Size[0] - name_size[0]) / 2,
- self.Pos.y + (self.Size[1] - name_size[1]) / 2)
+ text_pos = (self.Pos.x + (self.Size[0] - name_size[0]) // 2, + self.Pos.y + (self.Size[1] - name_size[1]) // 2) # Draw a rectangle with the variable size
dc.DrawRectangle(self.Pos.x, self.Pos.y, self.Size[0] + 1, self.Size[1] + 1)
@@ -876,9 +878,9 @@
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
- position = round_scaling(self.Pos.y + self.Size[1] / 2, scaling[1]) - self.Pos.y
+ position = round_scaling(self.Pos.y + self.Size[1] // 2, scaling[1]) - self.Pos.y - position = self.Size[1] / 2
+ position = self.Size[1] // 2 if self.Type == CONNECTOR:
self.Connector.SetPosition(wx.Point(0, position))
@@ -1017,18 +1019,18 @@
# Draw a rectangle with the connection size with arrows inside
dc.DrawRectangle(self.Pos.x, self.Pos.y, self.Size[0] + 1, self.Size[1] + 1)
- arrowsize = min(self.Size[1] / 2, (self.Size[0] - name_size[0] - 10) / 2)
+ arrowsize = min(self.Size[1] // 2, (self.Size[0] - name_size[0] - 10) // 2) dc.DrawLine(self.Pos.x, self.Pos.y, self.Pos.x + arrowsize,
- self.Pos.y + self.Size[1] / 2)
- dc.DrawLine(self.Pos.x + arrowsize, self.Pos.y + self.Size[1] / 2,
+ self.Pos.y + self.Size[1] // 2) + dc.DrawLine(self.Pos.x + arrowsize, self.Pos.y + self.Size[1] // 2, self.Pos.x, self.Pos.y + self.Size[1])
dc.DrawLine(self.Pos.x + self.Size[0] - arrowsize, self.Pos.y,
- self.Pos.x + self.Size[0], self.Pos.y + self.Size[1] / 2)
- dc.DrawLine(self.Pos.x + self.Size[0], self.Pos.y + self.Size[1] / 2,
+ self.Pos.x + self.Size[0], self.Pos.y + self.Size[1] // 2) + dc.DrawLine(self.Pos.x + self.Size[0], self.Pos.y + self.Size[1] // 2, self.Pos.x + self.Size[0] - arrowsize, self.Pos.y + self.Size[1])
- text_pos = (self.Pos.x + (self.Size[0] - name_size[0]) / 2,
- self.Pos.y + (self.Size[1] - name_size[1]) / 2)
+ text_pos = (self.Pos.x + (self.Size[0] - name_size[0]) // 2, + self.Pos.y + (self.Size[1] - name_size[1]) // 2) dc.DrawText(self.Name, text_pos[0], text_pos[1])
--- a/graphics/GraphicCommons.py Fri Nov 23 11:01:20 2018 +0100
+++ b/graphics/GraphicCommons.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,8 +24,11 @@
from __future__ import absolute_import
+from __future__ import division
+from future.builtins import round +from six import string_types +from six.moves import xrange from graphics.ToolTipProducer import ToolTipProducer
@@ -115,7 +118,7 @@
def round_scaling(x, n, constraint=0):
- fraction = float(x) / float(n)
@@ -185,8 +188,8 @@
pos = event.GetLogicalPosition(dc)
- pos.x = round(float(pos.x) / float(scaling[0])) * scaling[0]
- pos.y = round(float(pos.y) / float(scaling[1])) * scaling[1]
+ pos.x = round(pos.x / scaling[0]) * scaling[0] + pos.y = round(pos.y / scaling[1]) * scaling[1] @@ -434,11 +437,11 @@
pt = wx.Point(*self.Parent.CalcUnscrolledPosition(pos.x, pos.y))
left = (self.BoundingBox.x - 2) * scalex - HANDLE_SIZE
- center = (self.BoundingBox.x + self.BoundingBox.width / 2) * scalex - HANDLE_SIZE / 2
+ center = (self.BoundingBox.x + self.BoundingBox.width // 2) * scalex - HANDLE_SIZE // 2 right = (self.BoundingBox.x + self.BoundingBox.width + 2) * scalex
top = (self.BoundingBox.y - 2) * scaley - HANDLE_SIZE
- middle = (self.BoundingBox.y + self.BoundingBox.height / 2) * scaley - HANDLE_SIZE / 2
+ middle = (self.BoundingBox.y + self.BoundingBox.height / 2) * scaley - HANDLE_SIZE // 2 bottom = (self.BoundingBox.y + self.BoundingBox.height + 2) * scaley
extern_rect = wx.Rect(left, top, right + HANDLE_SIZE - left, bottom + HANDLE_SIZE - top)
@@ -682,11 +685,11 @@
dc.SetBrush(wx.BLACK_BRUSH)
left = (self.BoundingBox.x - 2) * scalex - HANDLE_SIZE
- center = (self.BoundingBox.x + self.BoundingBox.width / 2) * scalex - HANDLE_SIZE / 2
+ center = (self.BoundingBox.x + self.BoundingBox.width // 2) * scalex - HANDLE_SIZE // 2 right = (self.BoundingBox.x + self.BoundingBox.width + 2) * scalex
top = (self.BoundingBox.y - 2) * scaley - HANDLE_SIZE
- middle = (self.BoundingBox.y + self.BoundingBox.height / 2) * scaley - HANDLE_SIZE / 2
+ middle = (self.BoundingBox.y + self.BoundingBox.height // 2) * scaley - HANDLE_SIZE // 2 bottom = (self.BoundingBox.y + self.BoundingBox.height + 2) * scaley
for x, y in [(left, top), (center, top), (right, top),
@@ -858,13 +861,13 @@
if horizontally == ALIGN_LEFT:
elif horizontally == ALIGN_CENTER:
- movex = (maxx + minx - width) / 2 - posx
+ movex = (maxx + minx - width) // 2 - posx elif horizontally == ALIGN_RIGHT:
movex = maxx - width - posx
if vertically == ALIGN_TOP:
elif vertically == ALIGN_MIDDLE:
- movey = (maxy + miny - height) / 2 - posy
+ movey = (maxy + miny - height) // 2 - posy elif vertically == ALIGN_BOTTOM:
movey = maxy - height - posy
if movex != 0 or movey != 0:
@@ -1079,14 +1082,14 @@
rect = wx.Rect(x - abs(movex), y - abs(movey), width + 2 * abs(movex), height + 2 * abs(movey))
- if self.ValueSize is None and isinstance(self.ComputedValue, (StringType, UnicodeType)):
+ if self.ValueSize is None and isinstance(self.ComputedValue, string_types): self.ValueSize = self.ParentBlock.Parent.GetMiniTextExtent(self.ComputedValue)
if self.ValueSize is not None:
width, height = self.ValueSize
parent_pos[0] + self.Pos.x + CONNECTOR_SIZE * self.Direction[0] +
- width * (self.Direction[0] - 1) / 2,
+ width * (self.Direction[0] - 1) // 2, parent_pos[1] + self.Pos.y + CONNECTOR_SIZE * self.Direction[1] +
height * (self.Direction[1] - 1),
@@ -1161,7 +1164,7 @@
self.Parent.ElementNeedRefresh(self)
def GetComputedValue(self):
- if self.Value is not None and self.Value != "undefined" and not isinstance(self.Value, BooleanType):
+ if self.Value is not None and self.Value != "undefined" and not isinstance(self.Value, bool): @@ -1198,7 +1201,7 @@
for wire, _handle in self.Wires:
- if current != "undefined" and isinstance(value, BooleanType):
+ if current != "undefined" and isinstance(value, bool): current |= wire.GetValue()
elif value == "undefined":
@@ -1470,7 +1473,7 @@
dc.SetPen(MiterPen(wx.RED))
- elif isinstance(self.Value, BooleanType) and self.Value:
+ elif isinstance(self.Value, bool) and self.Value: dc.SetPen(MiterPen(wx.CYAN))
@@ -1491,9 +1494,9 @@
# If connector is negated, draw a circle
- xcenter = parent_pos[0] + self.Pos.x + (CONNECTOR_SIZE * self.Direction[0]) / 2
- ycenter = parent_pos[1] + self.Pos.y + (CONNECTOR_SIZE * self.Direction[1]) / 2
- dc.DrawCircle(xcenter, ycenter, CONNECTOR_SIZE / 2)
+ xcenter = parent_pos[0] + self.Pos.x + (CONNECTOR_SIZE * self.Direction[0]) // 2 + ycenter = parent_pos[1] + self.Pos.y + (CONNECTOR_SIZE * self.Direction[1]) // 2 + dc.DrawCircle(xcenter, ycenter, CONNECTOR_SIZE // 2) xstart = parent_pos[0] + self.Pos.x
ystart = parent_pos[1] + self.Pos.y
@@ -1518,13 +1521,13 @@
yend = ystart + CONNECTOR_SIZE * self.Direction[1]
dc.DrawLine(xstart + self.Direction[0], ystart + self.Direction[1], xend, yend)
if self.Direction[0] != 0:
- ytext = parent_pos[1] + self.Pos.y - name_size[1] / 2
+ ytext = parent_pos[1] + self.Pos.y - name_size[1] // 2 if self.Direction[0] < 0:
xtext = parent_pos[0] + self.Pos.x + 5
xtext = parent_pos[0] + self.Pos.x - (name_size[0] + 5)
if self.Direction[1] != 0:
- xtext = parent_pos[0] + self.Pos.x - name_size[0] / 2
+ xtext = parent_pos[0] + self.Pos.x - name_size[0] // 2 if self.Direction[1] < 0:
ytext = parent_pos[1] + self.Pos.y + 5
@@ -1534,16 +1537,16 @@
if not getattr(dc, "printing", False):
DrawHighlightedText(dc, self.Name, self.Highlights, xtext, ytext)
- if self.Value is not None and not isinstance(self.Value, BooleanType) and self.Value != "undefined":
+ if self.Value is not None and not isinstance(self.Value, bool) and self.Value != "undefined": dc.SetFont(self.ParentBlock.Parent.GetMiniFont())
dc.SetTextForeground(wx.NamedColour("purple"))
- if self.ValueSize is None and isinstance(self.ComputedValue, (StringType, UnicodeType)):
+ if self.ValueSize is None and isinstance(self.ComputedValue, string_types): self.ValueSize = self.ParentBlock.Parent.GetMiniTextExtent(self.ComputedValue)
if self.ValueSize is not None:
width, height = self.ValueSize
dc.DrawText(self.ComputedValue,
parent_pos[0] + self.Pos.x + CONNECTOR_SIZE * self.Direction[0] +
- width * (self.Direction[0] - 1) / 2,
+ width * (self.Direction[0] - 1) // 2, parent_pos[1] + self.Pos.y + CONNECTOR_SIZE * self.Direction[1] +
height * (self.Direction[1] - 1))
dc.SetFont(self.ParentBlock.Parent.GetFont())
@@ -1605,22 +1608,22 @@
rect = rect.Union(self.StartConnected.GetRedrawRect(movex, movey))
rect = rect.Union(self.EndConnected.GetRedrawRect(movex, movey))
- if self.ValueSize is None and isinstance(self.ComputedValue, (StringType, UnicodeType)):
+ if self.ValueSize is None and isinstance(self.ComputedValue, string_types): self.ValueSize = self.Parent.GetMiniTextExtent(self.ComputedValue)
if self.ValueSize is not None:
width, height = self.ValueSize
if self.BoundingBox[2] > width * 4 or self.BoundingBox[3] > height * 4:
- x = self.Points[0].x + width * self.StartPoint[1][0] / 2
+ x = self.Points[0].x + width * self.StartPoint[1][0] // 2 y = self.Points[0].y + height * (self.StartPoint[1][1] - 1)
rect = rect.Union(wx.Rect(x, y, width, height))
- x = self.Points[-1].x + width * self.EndPoint[1][0] / 2
+ x = self.Points[-1].x + width * self.EndPoint[1][0] // 2 y = self.Points[-1].y + height * (self.EndPoint[1][1] - 1)
rect = rect.Union(wx.Rect(x, y, width, height))
- middle = len(self.Segments) / 2 + len(self.Segments) % 2 - 1
- x = (self.Points[middle].x + self.Points[middle + 1].x - width) / 2
+ middle = len(self.Segments) // 2 + len(self.Segments) % 2 - 1 + x = (self.Points[middle].x + self.Points[middle + 1].x - width) // 2 if self.BoundingBox[3] > height and self.Segments[middle] in [NORTH, SOUTH]:
- y = (self.Points[middle].y + self.Points[middle + 1].y - height) / 2
+ y = (self.Points[middle].y + self.Points[middle + 1].y - height) // 2 y = self.Points[middle].y - height
rect = rect.Union(wx.Rect(x, y, width, height))
@@ -1754,7 +1757,7 @@
self.Parent.ElementNeedRefresh(self)
def GetComputedValue(self):
- if self.Value is not None and self.Value != "undefined" and not isinstance(self.Value, BooleanType):
+ if self.Value is not None and self.Value != "undefined" and not isinstance(self.Value, bool): @@ -1786,7 +1789,7 @@
self.EndConnected.RefreshValue()
self.Parent.ElementNeedRefresh(self)
- if isinstance(value, BooleanType) and self.StartConnected is not None:
+ if isinstance(value, bool) and self.StartConnected is not None: block = self.StartConnected.GetParentBlock()
@@ -2091,9 +2094,9 @@
# Current point is positioned in the middle of start point
# and end point on the current direction and a point is added
if self.Segments[0][0] != 0:
- self.Points[1].x = (end.x + start.x) / 2
+ self.Points[1].x = (end.x + start.x) // 2 if self.Segments[0][1] != 0:
- self.Points[1].y = (end.y + start.y) / 2
+ self.Points[1].y = (end.y + start.y) // 2 self.Points.insert(2, wx.Point(self.Points[1].x, self.Points[1].y))
self.Segments.insert(2, DirectionChoice(
@@ -2135,9 +2138,9 @@
# Current point is positioned in the middle of previous point
# and end point on the current direction and a point is added
if self.Segments[1][0] != 0:
- self.Points[2].x = (self.Points[1].x + end.x) / 2
+ self.Points[2].x = (self.Points[1].x + end.x) // 2 if self.Segments[1][1] != 0:
- self.Points[2].y = (self.Points[1].y + end.y) / 2
+ self.Points[2].y = (self.Points[1].y + end.y) // 2 self.Points.insert(3, wx.Point(self.Points[2].x, self.Points[2].y))
@@ -2159,9 +2162,9 @@
# Current point is positioned in the middle of previous point
# and end point on the current direction
if self.Segments[i - 1][0] != 0:
- self.Points[i].x = (end.x + self.Points[i - 1].x) / 2
+ self.Points[i].x = (end.x + self.Points[i - 1].x) // 2 if self.Segments[i - 1][1] != 0:
- self.Points[i].y = (end.y + self.Points[i - 1].y) / 2
+ self.Points[i].y = (end.y + self.Points[i - 1].y) // 2 self.Points.insert(i + 1, wx.Point(self.Points[i].x, self.Points[i].y))
@@ -2241,9 +2244,9 @@
- pointx = max(-dir[0] * MIN_SEGMENT_SIZE, min(int(round(point[0] * width / float(max(lastwidth, 1)))),
+ pointx = max(-dir[0] * MIN_SEGMENT_SIZE, min(int(round(point[0] * width / max(lastwidth, 1))), width - dir[0] * MIN_SEGMENT_SIZE))
- pointy = max(-dir[1] * MIN_SEGMENT_SIZE, min(int(round(point[1] * height / float(max(lastheight, 1)))),
+ pointy = max(-dir[1] * MIN_SEGMENT_SIZE, min(int(round(point[1] * height / max(lastheight, 1))), height - dir[1] * MIN_SEGMENT_SIZE))
self.Points[i] = wx.Point(minx + x + pointx, miny + y + pointy)
self.StartPoint[0] = self.Points[0]
@@ -2265,8 +2268,8 @@
# during a resize dragging
for i, point in enumerate(self.RealPoints):
if not (i == 0 and self.StartConnected) and not (i == len(self.Points) - 1 and self.EndConnected):
- point[0] = point[0] * width / float(max(lastwidth, 1))
- point[1] = point[1] * height / float(max(lastheight, 1))
+ point[0] = point[0] * width / max(lastwidth, 1) + point[1] = point[1] * height / max(lastheight, 1) # Calculate the correct position of the points from real points
for i, point in enumerate(self.RealPoints):
if not (i == 0 and self.StartConnected) and not (i == len(self.Points) - 1 and self.EndConnected):
@@ -2398,9 +2401,9 @@
pointx = self.Points[segment].x
pointy = self.Points[segment].y
- pointx = (self.Points[segment].x + self.Points[segment + 1].x) / 2
+ pointx = (self.Points[segment].x + self.Points[segment + 1].x) // 2 - pointy = (self.Points[segment].y + self.Points[segment + 1].y) / 2
+ pointy = (self.Points[segment].y + self.Points[segment + 1].y) // 2 self.Points.insert(segment + 1, wx.Point(pointx, pointy))
self.Segments.insert(segment + 1, (dir[1], dir[0]))
self.Points.insert(segment + 2, wx.Point(pointx, pointy))
@@ -2409,11 +2412,11 @@
p1x = p2x = self.Points[segment].x
p1y = p2y = self.Points[segment].y
- p1x = (2 * self.Points[segment].x + self.Points[segment + 1].x) / 3
- p2x = (self.Points[segment].x + 2 * self.Points[segment + 1].x) / 3
+ p1x = (2 * self.Points[segment].x + self.Points[segment + 1].x) // 3 + p2x = (self.Points[segment].x + 2 * self.Points[segment + 1].x) // 3 - p1y = (2 * self.Points[segment].y + self.Points[segment + 1].y) / 3
- p2y = (self.Points[segment].y + 2 * self.Points[segment + 1].y) / 3
+ p1y = (2 * self.Points[segment].y + self.Points[segment + 1].y) // 3 + p2y = (self.Points[segment].y + 2 * self.Points[segment + 1].y) // 3 self.Points.insert(segment + 1, wx.Point(p1x, p1y))
self.Segments.insert(segment + 1, (dir[1], dir[0]))
self.Points.insert(segment + 2, wx.Point(p1x, p1y))
@@ -2476,9 +2479,9 @@
direction = (self.StartPoint[1], self.EndPoint[1])
if direction in [(EAST, WEST), (WEST, EAST)]:
- avgy = (self.StartPoint[0].y + self.EndPoint[0].y) / 2
+ avgy = (self.StartPoint[0].y + self.EndPoint[0].y) // 2 - avgy = round(float(avgy) / scaling[1]) * scaling[1]
+ avgy = round(avgy / scaling[1]) * scaling[1] if self.StartConnected is not None:
movey = avgy - self.StartPoint[0].y
startblock = self.StartConnected.GetParentBlock()
@@ -2497,9 +2500,9 @@
self.MoveEndPoint(wx.Point(self.EndPoint[0].x, avgy))
self.Parent.RefreshBuffer()
elif direction in [(NORTH, SOUTH), (SOUTH, NORTH)]:
- avgx = (self.StartPoint[0].x + self.EndPoint[0].x) / 2
+ avgx = (self.StartPoint[0].x + self.EndPoint[0].x) // 2 - avgx = round(float(avgx) / scaling[0]) * scaling[0]
+ avgx = round(avgx / scaling[0]) * scaling[0] if self.StartConnected is not None:
movex = avgx - self.StartPoint[0].x
startblock = self.StartConnected.GetParentBlock()
@@ -2679,7 +2682,7 @@
dc.SetPen(MiterPen(wx.RED))
dc.SetBrush(wx.RED_BRUSH)
- elif isinstance(self.Value, BooleanType) and self.Value:
+ elif isinstance(self.Value, bool) and self.Value: dc.SetPen(MiterPen(wx.CYAN))
dc.SetBrush(wx.CYAN_BRUSH)
@@ -2717,25 +2720,25 @@
dc.DrawLine(self.Points[self.SelectedSegment].x - 1, self.Points[self.SelectedSegment].y,
self.Points[self.SelectedSegment + 1].x + end, self.Points[self.SelectedSegment + 1].y)
- if self.Value is not None and not isinstance(self.Value, BooleanType) and self.Value != "undefined":
+ if self.Value is not None and not isinstance(self.Value, bool) and self.Value != "undefined": dc.SetFont(self.Parent.GetMiniFont())
dc.SetTextForeground(wx.NamedColour("purple"))
- if self.ValueSize is None and isinstance(self.ComputedValue, (StringType, UnicodeType)):
+ if self.ValueSize is None and isinstance(self.ComputedValue, string_types): self.ValueSize = self.Parent.GetMiniTextExtent(self.ComputedValue)
if self.ValueSize is not None:
width, height = self.ValueSize
if self.BoundingBox[2] > width * 4 or self.BoundingBox[3] > height * 4:
- x = self.Points[0].x + width * (self.StartPoint[1][0] - 1) / 2
+ x = self.Points[0].x + width * (self.StartPoint[1][0] - 1) // 2 y = self.Points[0].y + height * (self.StartPoint[1][1] - 1)
dc.DrawText(self.ComputedValue, x, y)
- x = self.Points[-1].x + width * (self.EndPoint[1][0] - 1) / 2
+ x = self.Points[-1].x + width * (self.EndPoint[1][0] - 1) // 2 y = self.Points[-1].y + height * (self.EndPoint[1][1] - 1)
dc.DrawText(self.ComputedValue, x, y)
- middle = len(self.Segments) / 2 + len(self.Segments) % 2 - 1
- x = (self.Points[middle].x + self.Points[middle + 1].x - width) / 2
+ middle = len(self.Segments) // 2 + len(self.Segments) % 2 - 1 + x = (self.Points[middle].x + self.Points[middle + 1].x - width) // 2 if self.BoundingBox[3] > height and self.Segments[middle] in [NORTH, SOUTH]:
- y = (self.Points[middle].y + self.Points[middle + 1].y - height) / 2
+ y = (self.Points[middle].y + self.Points[middle + 1].y - height) // 2 y = self.Points[middle].y - height
dc.DrawText(self.ComputedValue, x, y)
--- a/graphics/LD_Objects.py Fri Nov 23 11:01:20 2018 +0100
+++ b/graphics/LD_Objects.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,7 +24,10 @@
from __future__ import absolute_import
+from __future__ import division +from future.builtins import round +from six.moves import xrange from graphics.GraphicCommons import *
from graphics.DebugDataConsumer import DebugDataConsumer
@@ -48,7 +51,7 @@
self.RealConnectors = None
- self.Extensions = [LD_LINE_SIZE / 2, LD_LINE_SIZE / 2]
+ self.Extensions = [LD_LINE_SIZE // 2, LD_LINE_SIZE // 2] self.SetType(type, connectors)
@@ -183,14 +186,14 @@
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
height = self.Size[1] - self.Extensions[0] - self.Extensions[1]
- interval = float(height) / float(max(len(self.Connectors) - 1, 1))
+ interval = height / max(len(self.Connectors) - 1, 1) for i, connector in enumerate(self.Connectors):
position = self.Extensions[0] + int(round(self.RealConnectors[i] * height))
position = self.Extensions[0] + int(round(i * interval))
- position = round(float(self.Pos.y + position) / float(scaling[1])) * scaling[1] - self.Pos.y
+ position = round((self.Pos.y + position) / scaling[1]) * scaling[1] - self.Pos.y if self.Type == LEFTRAIL:
connector.SetPosition(wx.Point(self.Size[0], position))
elif self.Type == RIGHTRAIL:
@@ -250,7 +253,7 @@
for connector in self.Connectors:
position = connector.GetRelPosition()
- self.RealConnectors.append(max(0., min(float(position.y - self.Extensions[0]) / float(height), 1.)))
+ self.RealConnectors.append(max(0., min((position.y - self.Extensions[0]) / height, 1.))) elif len(self.Connectors) > 1:
self.RealConnectors = map(lambda x: x * 1 / (len(self.Connectors) - 1), xrange(len(self.Connectors)))
@@ -311,7 +314,7 @@
movey = max(-self.BoundingBox.y, movey)
position = handle.GetRelPosition()
- movey = round(float(self.Pos.y + position.y + movey) / float(scaling[1])) * scaling[1] - self.Pos.y - position.y
+ movey = round((self.Pos.y + position.y + movey) / scaling[1]) * scaling[1] - self.Pos.y - position.y self.MoveConnector(handle, movey)
elif self.Parent.GetDrawingMode() == FREEDRAWING_MODE:
@@ -362,8 +365,8 @@
self.Size = wx.Size(LD_ELEMENT_SIZE[0], LD_ELEMENT_SIZE[1])
# Create an input and output connector
- self.Input = Connector(self, "", "BOOL", wx.Point(0, self.Size[1] / 2 + 1), WEST)
- self.Output = Connector(self, "", "BOOL", wx.Point(self.Size[0], self.Size[1] / 2 + 1), EAST)
+ self.Input = Connector(self, "", "BOOL", wx.Point(0, self.Size[1] // 2 + 1), WEST) + self.Output = Connector(self, "", "BOOL", wx.Point(self.Size[0], self.Size[1] // 2 + 1), EAST) self.PreviousValue = False
self.PreviousSpreading = False
@@ -492,7 +495,7 @@
text_width, text_height = self.Parent.GetTextExtent(self.Name)
# Calculate the bounding box size
- bbx_x = self.Pos.x - max(0, (text_width - self.Size[0]) / 2)
+ bbx_x = self.Pos.x - max(0, (text_width - self.Size[0]) // 2) bbx_width = max(self.Size[0], text_width)
bbx_y = self.Pos.y - (text_height + 2)
bbx_height = self.Size[1] + (text_height + 2)
@@ -540,9 +543,9 @@
# Refresh the positions of the block connectors
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
- position = self.Size[1] / 2 + 1
+ position = self.Size[1] // 2 + 1 - position = round(float(self.Pos.y + position) / float(scaling[1])) * scaling[1] - self.Pos.y
+ position = round((self.Pos.y + position) / scaling[1]) * scaling[1] - self.Pos.y self.Input.SetPosition(wx.Point(0, position))
self.Output.SetPosition(wx.Point(self.Size[0], position))
@@ -669,13 +672,13 @@
dc.DrawRectangle(self.Pos.x, self.Pos.y, 2, self.Size[1] + 1)
dc.DrawRectangle(self.Pos.x + self.Size[0] - 1, self.Pos.y, 2, self.Size[1] + 1)
- name_pos = (self.Pos.x + (self.Size[0] - name_size[0]) / 2,
+ name_pos = (self.Pos.x + (self.Size[0] - name_size[0]) // 2, self.Pos.y - (name_size[1] + 2))
dc.DrawText(self.Name, name_pos[0], name_pos[1])
# Draw the modifier symbol in the middle of contact
- type_pos = (self.Pos.x + (self.Size[0] - type_size[0]) / 2 + 1,
- self.Pos.y + (self.Size[1] - type_size[1]) / 2)
+ type_pos = (self.Pos.x + (self.Size[0] - type_size[0]) // 2 + 1, + self.Pos.y + (self.Size[1] - type_size[1]) // 2) dc.DrawText(typetext, type_pos[0], type_pos[1])
# Draw input and output connectors
@@ -708,8 +711,8 @@
self.Size = wx.Size(LD_ELEMENT_SIZE[0], LD_ELEMENT_SIZE[1])
# Create an input and output connector
- self.Input = Connector(self, "", "BOOL", wx.Point(0, self.Size[1] / 2 + 1), WEST)
- self.Output = Connector(self, "", "BOOL", wx.Point(self.Size[0], self.Size[1] / 2 + 1), EAST)
+ self.Input = Connector(self, "", "BOOL", wx.Point(0, self.Size[1] // 2 + 1), WEST) + self.Output = Connector(self, "", "BOOL", wx.Point(self.Size[0], self.Size[1] // 2 + 1), EAST) self.PreviousValue = False
@@ -812,7 +815,7 @@
text_width, text_height = self.Parent.GetTextExtent(self.Name)
# Calculate the bounding box size
- bbx_x = self.Pos.x - max(0, (text_width - self.Size[0]) / 2)
+ bbx_x = self.Pos.x - max(0, (text_width - self.Size[0]) // 2) bbx_width = max(self.Size[0], text_width)
bbx_y = self.Pos.y - (text_height + 2)
bbx_height = self.Size[1] + (text_height + 2)
@@ -860,9 +863,9 @@
# Refresh the positions of the block connectors
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
- position = self.Size[1] / 2 + 1
+ position = self.Size[1] // 2 + 1 - position = round(float(self.Pos.y + position) / float(scaling[1])) * scaling[1] - self.Pos.y
+ position = round((self.Pos.y + position) / scaling[1]) * scaling[1] - self.Pos.y self.Input.SetPosition(wx.Point(0, position))
self.Output.SetPosition(wx.Point(self.Size[0], position))
@@ -992,19 +995,19 @@
dc.SetPen(MiterPen(wx.GREEN))
dc.SetPen(MiterPen(wx.BLACK))
- dc.DrawPoint(self.Pos.x + 1, self.Pos.y + self.Size[1] / 2 + 1)
+ dc.DrawPoint(self.Pos.x + 1, self.Pos.y + self.Size[1] // 2 + 1) name_size = self.NameSize
type_size = self.TypeSize
- name_pos = (self.Pos.x + (self.Size[0] - name_size[0]) / 2,
+ name_pos = (self.Pos.x + (self.Size[0] - name_size[0]) // 2, self.Pos.y - (name_size[1] + 2))
dc.DrawText(self.Name, name_pos[0], name_pos[1])
# Draw the modifier symbol in the middle of coil
- type_pos = (self.Pos.x + (self.Size[0] - type_size[0]) / 2 + 1,
- self.Pos.y + (self.Size[1] - type_size[1]) / 2)
+ type_pos = (self.Pos.x + (self.Size[0] - type_size[0]) // 2 + 1, + self.Pos.y + (self.Size[1] - type_size[1]) // 2) dc.DrawText(typetext, type_pos[0], type_pos[1])
# Draw input and output connectors
--- a/graphics/SFC_Objects.py Fri Nov 23 11:01:20 2018 +0100
+++ b/graphics/SFC_Objects.py Fri Nov 23 12:13:24 2018 +0100
@@ -24,7 +24,11 @@
from __future__ import absolute_import
+from __future__ import division +from future.builtins import round +from six.moves import xrange from graphics.GraphicCommons import *
from graphics.DebugDataConsumer import DebugDataConsumer
@@ -58,7 +62,7 @@
self.Size = wx.Size(SFC_STEP_DEFAULT_SIZE[0], SFC_STEP_DEFAULT_SIZE[1])
# Create an input and output connector
- self.Input = Connector(self, "", None, wx.Point(self.Size[0] / 2, 0), NORTH)
+ self.Input = Connector(self, "", None, wx.Point(self.Size[0] // 2, 0), NORTH) @@ -170,7 +174,7 @@
# Add output connector to step
- self.Input = Connector(self, "", None, wx.Point(self.Size[0] / 2, 0), NORTH)
+ self.Input = Connector(self, "", None, wx.Point(self.Size[0] // 2, 0), NORTH) self.RefreshBoundingBox()
# Remove output connector from step
@@ -183,7 +187,7 @@
# Add output connector to step
- self.Output = Connector(self, "", None, wx.Point(self.Size[0] / 2, self.Size[1]), SOUTH, onlyone=True)
+ self.Output = Connector(self, "", None, wx.Point(self.Size[0] // 2, self.Size[1]), SOUTH, onlyone=True) self.RefreshBoundingBox()
# Remove output connector from step
@@ -196,7 +200,7 @@
# Add action connector to step
- self.Action = Connector(self, "", None, wx.Point(self.Size[0], self.Size[1] / 2), EAST, onlyone=True)
+ self.Action = Connector(self, "", None, wx.Point(self.Size[0], self.Size[1] // 2), EAST, onlyone=True) self.RefreshBoundingBox()
# Remove action connector from step
@@ -231,11 +235,11 @@
# Refresh the positions of the step connectors
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
- horizontal_pos = self.Size[0] / 2
- vertical_pos = self.Size[1] / 2
+ horizontal_pos = self.Size[0] // 2 + vertical_pos = self.Size[1] // 2 - horizontal_pos = round(float(self.Pos.x + horizontal_pos) / float(scaling[0])) * scaling[0] - self.Pos.x
- vertical_pos = round(float(self.Pos.y + vertical_pos) / float(scaling[1])) * scaling[1] - self.Pos.y
+ horizontal_pos = round((self.Pos.x + horizontal_pos) / scaling[0]) * scaling[0] - self.Pos.x + vertical_pos = round((self.Pos.y + vertical_pos) / scaling[1]) * scaling[1] - self.Pos.y # Update input position if it exists
self.Input.SetPosition(wx.Point(horizontal_pos, 0))
@@ -362,7 +366,7 @@
def UpdateSize(self, width, height):
- diffx = self.Size.GetWidth() / 2 - width / 2
+ diffx = self.Size.GetWidth() // 2 - width // 2 diffy = height - self.Size.GetHeight()
Graphic_Element.SetSize(self, width, height)
@@ -462,8 +466,8 @@
movex = max(-self.BoundingBox.x, movex)
movey = max(-self.BoundingBox.y, movey)
- movex = round(float(self.Pos.x + movex) / float(scaling[0])) * scaling[0] - self.Pos.x
- movey = round(float(self.Pos.y + movey) / float(scaling[1])) * scaling[1] - self.Pos.y
+ movex = round((self.Pos.x + movex) / scaling[0]) * scaling[0] - self.Pos.x + movey = round((self.Pos.y + movey) / scaling[1]) * scaling[1] - self.Pos.y if self.Parent.GetDrawingMode() == FREEDRAWING_MODE:
@@ -556,8 +560,8 @@
dc.DrawRectangle(self.Pos.x + 2, self.Pos.y + 2, self.Size[0] - 3, self.Size[1] - 3)
- name_pos = (self.Pos.x + (self.Size[0] - name_size[0]) / 2,
- self.Pos.y + (self.Size[1] - name_size[1]) / 2)
+ name_pos = (self.Pos.x + (self.Size[0] - name_size[0]) // 2, + self.Pos.y + (self.Size[1] - name_size[1]) // 2) dc.DrawText(self.Name, name_pos[0], name_pos[1])
# Draw input and output connectors
@@ -590,8 +594,8 @@
self.Size = wx.Size(SFC_TRANSITION_SIZE[0], SFC_TRANSITION_SIZE[1])
# Create an input and output connector
- self.Input = Connector(self, "", None, wx.Point(self.Size[0] / 2, 0), NORTH, onlyone=True)
- self.Output = Connector(self, "", None, wx.Point(self.Size[0] / 2, self.Size[1]), SOUTH, onlyone=True)
+ self.Input = Connector(self, "", None, wx.Point(self.Size[0] // 2, 0), NORTH, onlyone=True) + self.Output = Connector(self, "", None, wx.Point(self.Size[0] // 2, self.Size[1]), SOUTH, onlyone=True) self.SetType(type, condition)
self.SetPriority(priority)
@@ -712,7 +716,7 @@
# Calculate the bounding box of the condition outside the transition
text_width, text_height = self.ConditionSize
text_bbx = wx.Rect(self.Pos.x + self.Size[0] + 5,
- self.Pos.y + (self.Size[1] - text_height) / 2,
+ self.Pos.y + (self.Size[1] - text_height) // 2, test_text = text_bbx.InsideXY(pt.x, pt.y)
@@ -734,8 +738,8 @@
text_width, text_height = self.ConditionSize
# Calculate the bounding box size
bbx_width = max(bbx_width, self.Size[0] + 5 + text_width)
- bbx_y = min(bbx_y, self.Pos.y - max(0, (text_height - self.Size[1]) / 2))
- bbx_height = max(bbx_height, self.Pos.y - bbx_y + (self.Size[1] + text_height) / 2)
+ bbx_y = min(bbx_y, self.Pos.y - max(0, (text_height - self.Size[1]) // 2)) + bbx_height = max(bbx_height, self.Pos.y - bbx_y + (self.Size[1] + text_height) // 2) self.BoundingBox = wx.Rect(bbx_x, bbx_y, bbx_width + 1, bbx_height + 1)
# Returns the connector connected to input
@@ -755,11 +759,11 @@
# Refresh the positions of the transition connectors
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
- horizontal_pos = self.Size[0] / 2
- vertical_pos = self.Size[1] / 2
+ horizontal_pos = self.Size[0] // 2 + vertical_pos = self.Size[1] // 2 - horizontal_pos = round(float(self.Pos.x + horizontal_pos) / float(scaling[0])) * scaling[0] - self.Pos.x
- vertical_pos = round(float(self.Pos.y + vertical_pos) / float(scaling[1])) * scaling[1] - self.Pos.y
+ horizontal_pos = round((self.Pos.x + horizontal_pos) / scaling[0]) * scaling[0] - self.Pos.x + vertical_pos = round((self.Pos.y + vertical_pos) / scaling[1]) * scaling[1] - self.Pos.y self.Input.SetPosition(wx.Point(horizontal_pos, 0))
@@ -821,7 +825,7 @@
self.Condition.UnConnect(delete=self.Parent.GetDrawingMode() == FREEDRAWING_MODE)
- self.Condition = Connector(self, "", "BOOL", wx.Point(0, self.Size[1] / 2), WEST)
+ self.Condition = Connector(self, "", "BOOL", wx.Point(0, self.Size[1] // 2), WEST) @@ -916,7 +920,7 @@
if self.Parent.GetDrawingMode() != FREEDRAWING_MODE:
movex = max(-self.BoundingBox.x, movex)
- movex = round(float(self.Pos.x + movex) / float(scaling[0])) * scaling[0] - self.Pos.x
+ movex = round((self.Pos.x + movex) / scaling[0]) * scaling[0] - self.Pos.x self.RefreshInputPosition()
self.RefreshOutputPosition()
@@ -1008,7 +1012,7 @@
# Draw plain rectangle for representing the transition
dc.DrawRectangle(self.Pos.x,
- self.Pos.y + (self.Size[1] - SFC_TRANSITION_SIZE[1])/2,
+ self.Pos.y + (self.Size[1] - SFC_TRANSITION_SIZE[1]) // 2, SFC_TRANSITION_SIZE[1] + 1)
vertical_line_x = self.Input.GetPosition()[0]
@@ -1020,7 +1024,7 @@
condition_pos = (self.Pos.x + self.Size[0] + 5,
- self.Pos.y + (self.Size[1] - condition_size[1]) / 2)
+ self.Pos.y + (self.Size[1] - condition_size[1]) // 2) dc.DrawText(condition, condition_pos[0], condition_pos[1])
@@ -1061,7 +1065,7 @@
self.Size = wx.Size((number - 1) * SFC_DEFAULT_SEQUENCE_INTERVAL, self.GetMinSize()[1])
# Create an input and output connector
if self.Type in [SELECTION_DIVERGENCE, SIMULTANEOUS_DIVERGENCE]:
- self.Inputs = [Connector(self, "", None, wx.Point(self.Size[0] / 2, 0), NORTH, onlyone=True)]
+ self.Inputs = [Connector(self, "", None, wx.Point(self.Size[0] // 2, 0), NORTH, onlyone=True)] self.Outputs.append(Connector(self, "", None, wx.Point(i * SFC_DEFAULT_SEQUENCE_INTERVAL, self.Size[1]), SOUTH, onlyone=True))
@@ -1069,7 +1073,7 @@
self.Inputs.append(Connector(self, "", None, wx.Point(i * SFC_DEFAULT_SEQUENCE_INTERVAL, 0), NORTH, onlyone=True))
- self.Outputs = [Connector(self, "", None, wx.Point(self.Size[0] / 2, self.Size[1]), SOUTH, onlyone=True)]
+ self.Outputs = [Connector(self, "", None, wx.Point(self.Size[0] // 2, self.Size[1]), SOUTH, onlyone=True)] self.PreviousValue = None
@@ -1284,14 +1288,14 @@
input.SetPosition(wx.Point(int(round(self.RealConnectors["Inputs"][i] * width)), 0))
- input.SetPosition(wx.Point(int(round(float(position.x)*float(width)/float(self.Size[0]))), 0))
+ input.SetPosition(wx.Point(int(round(position.x*width / self.Size[0])), 0)) for i, output in enumerate(self.Outputs):
position = output.GetRelPosition()
output.SetPosition(wx.Point(int(round(self.RealConnectors["Outputs"][i] * width)), height))
- output.SetPosition(wx.Point(int(round(float(position.x)*float(width)/float(self.Size[0]))), height))
+ output.SetPosition(wx.Point(int(round(position.x*width / self.Size[0])), height)) self.Size = wx.Size(width, height)
self.RefreshBoundingBox()
@@ -1367,10 +1371,10 @@
self.RealConnectors = {"Inputs": [], "Outputs": []}
for input in self.Inputs:
position = input.GetRelPosition()
- self.RealConnectors["Inputs"].append(float(position.x)/float(self.Size[0]))
+ self.RealConnectors["Inputs"].append(position.x / self.Size[0]) for output in self.Outputs:
position = output.GetRelPosition()
- self.RealConnectors["Outputs"].append(float(position.x)/float(self.Size[0]))
+ self.RealConnectors["Outputs"].append(position.x / self.Size[0]) Graphic_Element.OnLeftDown(self, event, dc, scaling)
# Method called when a LeftUp event have been generated
@@ -1424,7 +1428,7 @@
if handle_type == HANDLE_CONNECTOR:
movex = max(-self.BoundingBox.x, movex)
- movex = round(float(self.Pos.x + movex) / float(scaling[0])) * scaling[0] - self.Pos.x
+ movex = round((self.Pos.x + movex) / scaling[0]) * scaling[0] - self.Pos.x self.MoveConnector(handle, movex)
if self.Parent.GetDrawingMode() != FREEDRAWING_MODE:
self.RefreshConnectedPosition(handle)
@@ -1518,7 +1522,7 @@
self.Size = wx.Size(SFC_JUMP_SIZE[0], SFC_JUMP_SIZE[1])
# Create an input and output connector
- self.Input = Connector(self, "", None, wx.Point(self.Size[0] / 2, 0), NORTH, onlyone=True)
+ self.Input = Connector(self, "", None, wx.Point(self.Size[0] // 2, 0), NORTH, onlyone=True) self.PreviousValue = None
@@ -1585,7 +1589,7 @@
# Calculate the bounding box of the condition outside the transition
text_width, text_height = self.TargetSize
text_bbx = wx.Rect(self.Pos.x + self.Size[0] + 2,
- self.Pos.y + (self.Size[1] - text_height) / 2,
+ self.Pos.y + (self.Size[1] - text_height) // 2, return text_bbx.InsideXY(pt.x, pt.y) or Graphic_Element.HitTest(self, pt, connectors)
@@ -1608,9 +1612,9 @@
# Refresh the element connectors position
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
- horizontal_pos = self.Size[0] / 2
+ horizontal_pos = self.Size[0] // 2 - horizontal_pos = round(float(self.Pos.x + horizontal_pos) / float(scaling[0])) * scaling[0] - self.Pos.x
+ horizontal_pos = round((self.Pos.x + horizontal_pos) / scaling[0]) * scaling[0] - self.Pos.x self.Input.SetPosition(wx.Point(horizontal_pos, 0))
@@ -1684,7 +1688,7 @@
if self.Parent.GetDrawingMode() != FREEDRAWING_MODE:
movex = max(-self.BoundingBox.x, movex)
- movex = round(float(self.Pos.x + movex) / float(scaling[0])) * scaling[0] - self.Pos.x
+ movex = round((self.Pos.x + movex) / scaling[0]) * scaling[0] - self.Pos.x self.RefreshInputPosition()
@@ -1759,14 +1763,14 @@
target_size = self.TargetSize
# Draw plain rectangle for representing the divergence
- dc.DrawLine(self.Pos.x + self.Size[0] / 2, self.Pos.y, self.Pos.x + self.Size[0] / 2, self.Pos.y + self.Size[1])
+ dc.DrawLine(self.Pos.x + self.Size[0] // 2, self.Pos.y, self.Pos.x + self.Size[0] // 2, self.Pos.y + self.Size[1]) points = [wx.Point(self.Pos.x, self.Pos.y),
- wx.Point(self.Pos.x + self.Size[0] / 2, self.Pos.y + self.Size[1] / 3),
+ wx.Point(self.Pos.x + self.Size[0] // 2, self.Pos.y + self.Size[1] // 3), wx.Point(self.Pos.x + self.Size[0], self.Pos.y),
- wx.Point(self.Pos.x + self.Size[0] / 2, self.Pos.y + self.Size[1])]
+ wx.Point(self.Pos.x + self.Size[0] // 2, self.Pos.y + self.Size[1])] target_pos = (self.Pos.x + self.Size[0] + 2,
- self.Pos.y + (self.Size[1] - target_size[1]) / 2)
+ self.Pos.y + (self.Size[1] - target_size[1]) // 2) dc.DrawText(self.Target, target_pos[0], target_pos[1])
@@ -1794,7 +1798,7 @@
self.MinSize = wx.Size(SFC_ACTION_MIN_SIZE[0], SFC_ACTION_MIN_SIZE[1])
# Create an input and output connector
- self.Input = Connector(self, "", None, wx.Point(0, SFC_ACTION_MIN_SIZE[1] / 2), WEST, onlyone=True)
+ self.Input = Connector(self, "", None, wx.Point(0, SFC_ACTION_MIN_SIZE[1] // 2), WEST, onlyone=True) self.PreviousValue = None
@@ -1842,7 +1846,7 @@
if len(self.Actions) > 0:
- return self.Size[1] / len(self.Actions)
+ return self.Size[1] // len(self.Actions) return SFC_ACTION_MIN_SIZE[1]
@@ -1888,9 +1892,9 @@
# Refresh the element connectors position
def RefreshConnectors(self):
scaling = self.Parent.GetScaling()
- vertical_pos = SFC_ACTION_MIN_SIZE[1] / 2
+ vertical_pos = SFC_ACTION_MIN_SIZE[1] // 2 - vertical_pos = round(float(self.Pos.y + vertical_pos) / float(scaling[1])) * scaling[1] - self.Pos.y
+ vertical_pos = round((self.Pos.y + vertical_pos) / scaling[1]) * scaling[1] - self.Pos.y self.Input.SetPosition(wx.Point(0, vertical_pos))
@@ -1961,7 +1965,7 @@
if handle_type == HANDLE_MOVE:
movex = max(-self.BoundingBox.x, movex)
- movex = round(float(self.Pos.x + movex) / float(scaling[0])) * scaling[0] - self.Pos.x
+ movex = round((self.Pos.x + movex) / scaling[0]) * scaling[0] - self.Pos.x wires = self.Input.GetWires()
input_pos = wires[0][0].GetOtherConnected(self.Input).GetPosition(False)
@@ -2032,24 +2036,24 @@
self.Pos.x + self.Size[0], self.Pos.y + i * line_size)
qualifier_size = dc.GetTextExtent(action.qualifier)
if action.duration != "":
- qualifier_pos = (self.Pos.x + (colsize[0] - qualifier_size[0]) / 2,
- self.Pos.y + i * line_size + line_size / 2 - qualifier_size[1])
+ qualifier_pos = (self.Pos.x + (colsize[0] - qualifier_size[0]) // 2, + self.Pos.y + i * line_size + line_size // 2 - qualifier_size[1]) duration_size = dc.GetTextExtent(action.duration)
- duration_pos = (self.Pos.x + (colsize[0] - duration_size[0]) / 2,
- self.Pos.y + i * line_size + line_size / 2)
+ duration_pos = (self.Pos.x + (colsize[0] - duration_size[0]) // 2, + self.Pos.y + i * line_size + line_size // 2) dc.DrawText(action.duration, duration_pos[0], duration_pos[1])
- qualifier_pos = (self.Pos.x + (colsize[0] - qualifier_size[0]) / 2,
- self.Pos.y + i * line_size + (line_size - qualifier_size[1]) / 2)
+ qualifier_pos = (self.Pos.x + (colsize[0] - qualifier_size[0]) // 2, + self.Pos.y + i * line_size + (line_size - qualifier_size[1]) // 2) dc.DrawText(action.qualifier, qualifier_pos[0], qualifier_pos[1])
content_size = dc.GetTextExtent(action.value)
- content_pos = (self.Pos.x + colsize[0] + (colsize[1] - content_size[0]) / 2,
- self.Pos.y + i * line_size + (line_size - content_size[1]) / 2)
+ content_pos = (self.Pos.x + colsize[0] + (colsize[1] - content_size[0]) // 2, + self.Pos.y + i * line_size + (line_size - content_size[1]) // 2) dc.DrawText(action.value, content_pos[0], content_pos[1])
if action.indicator != "":
indicator_size = dc.GetTextExtent(action.indicator)
- indicator_pos = (self.Pos.x + colsize[0] + colsize[1] + (colsize[2] - indicator_size[0]) / 2,
- self.Pos.y + i * line_size + (line_size - indicator_size[1]) / 2)
+ indicator_pos = (self.Pos.x + colsize[0] + colsize[1] + (colsize[2] - indicator_size[0]) // 2, + self.Pos.y + i * line_size + (line_size - indicator_size[1]) // 2) dc.DrawText(action.indicator, indicator_pos[0], indicator_pos[1])
if not getattr(dc, "printing", False):
--- a/svgui/pyjs/pyjs.py Fri Nov 23 11:01:20 2018 +0100
+++ b/svgui/pyjs/pyjs.py Fri Nov 23 12:13:24 2018 +0100
@@ -13,16 +13,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-# pylint: disable=no-absolute-import
+# pylint: disable=no-absolute-import,bad-python3-import from __future__ import print_function
-from types import StringType
+from builtins import str as text +from past.builtins import basestring +from six.moves import cStringIO # the standard location for builtins (e.g. pyjslib) can be
# over-ridden by changing this. it defaults to sys.prefix
@@ -1359,7 +1360,7 @@
elif isinstance(node.value, basestring):
- if isinstance(node.value, unicode):
+ if isinstance(node.value, text): return "String('%s')" % escapejs(v)
@@ -1386,7 +1387,7 @@
return self.expr(node.left, current_klass) + " * " + self.expr(node.right, current_klass)
def _mod(self, node, current_klass):
- if isinstance(node.left, ast.Const) and isinstance(node.left.value, StringType):
+ if isinstance(node.left, ast.Const) and isinstance(node.left.value, str): self.imported_js.add("sprintf.js") # Include the sprintf functionality if it is used
return "sprintf("+self.expr(node.left, current_klass) + ", " + self.expr(node.right, current_klass)+")"
return self.expr(node.left, current_klass) + " % " + self.expr(node.right, current_klass)
@@ -1443,7 +1444,7 @@
raise TranslationError("varargs are not supported in Lambdas", node)
raise TranslationError("kwargs are not supported in Lambdas", node)
- res = cStringIO.StringIO()
arg_names = list(node.argnames)
function_args = ", ".join(arg_names)
for child in node.getChildNodes():
@@ -1531,10 +1532,10 @@
def translate(file_name, module_name, debug=False):
- f = file(file_name, "r")
+ f = open(file_name, "r") - output = cStringIO.StringIO()
mod = compiler.parseFile(file_name)
Translator(module_name, module_name, module_name, src, debug, mod, output)
@@ -1683,9 +1684,9 @@
file_name = self.findFile(module_name + self.extension)
- output = cStringIO.StringIO()
- f = file(file_name, "r")
+ f = open(file_name, "r") @@ -1718,8 +1719,8 @@
def translate(self, module_name, is_app=True, debug=False,
- app_code = cStringIO.StringIO()
- lib_code = cStringIO.StringIO()
self.library_modules = []
@@ -1748,7 +1749,7 @@
print('Including JS', js)
print('\n//\n// BEGIN JS '+js+'\n//\n', file=lib_code)
- print(file(path).read(), file=lib_code)
+ print(open(path).read(), file=lib_code) print('\n//\n// END JS '+js+'\n//\n', file=lib_code)
print('Warning: Unable to find imported javascript:', js, file=sys.stderr)
--- a/xmlclass/xmlclass.py Fri Nov 23 11:01:20 2018 +0100
+++ b/xmlclass/xmlclass.py Fri Nov 23 12:13:24 2018 +0100
@@ -28,12 +28,14 @@
from xml.dom import minidom
from xml.sax.saxutils import unescape
-from new import classobj
from collections import OrderedDict
+from builtins import str as text +from functools import reduce +from six import string_types +from six.moves import xrange @@ -51,33 +53,33 @@
def NodeSetAttr(node, name, value):
attr = minidom.Attr(name)
- attr.childNodes[0] = text
+ attr.childNodes[0] = txt # Regular expression models for checking all kind of
# string values defined in XML standard
-Name_model = re.compile('([a-zA-Z_\:][\w\.\-\:]*)$')
-Names_model = re.compile('([a-zA-Z_\:][\w\.\-\:]*(?: [a-zA-Z_\:][\w\.\-\:]*)*)$')
-NMToken_model = re.compile('([\w\.\-\:]*)$')
-NMTokens_model = re.compile('([\w\.\-\:]*(?: [\w\.\-\:]*)*)$')
-QName_model = re.compile('((?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*)$')
-QNames_model = re.compile('((?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*(?: (?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*)*)$')
-NCName_model = re.compile('([a-zA-Z_][\w]*)$')
-URI_model = re.compile('((?:htt(p|ps)://|/)?(?:[\w.-]*/?)*)$')
-LANGUAGE_model = re.compile('([a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*)$')
+Name_model = re.compile(r'([a-zA-Z_\:][\w\.\-\:]*)$') +Names_model = re.compile(r'([a-zA-Z_\:][\w\.\-\:]*(?: [a-zA-Z_\:][\w\.\-\:]*)*)$') +NMToken_model = re.compile(r'([\w\.\-\:]*)$') +NMTokens_model = re.compile(r'([\w\.\-\:]*(?: [\w\.\-\:]*)*)$') +QName_model = re.compile(r'((?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*)$') +QNames_model = re.compile(r'((?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*(?: (?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*)*)$') +NCName_model = re.compile(r'([a-zA-Z_][\w]*)$') +URI_model = re.compile(r'((?:htt(p|ps)://|/)?(?:[\w.-]*/?)*)$') +LANGUAGE_model = re.compile(r'([a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*)$') -ONLY_ANNOTATION = re.compile("((?:annotation )?)")
+ONLY_ANNOTATION = re.compile(r"((?:annotation )?)") Regular expression models for extracting dates and times from a string
-time_model = re.compile('([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)(?:Z)?$')
-date_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$')
-datetime_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})[ T]([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$')
+time_model = re.compile(r'([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)(?:Z)?$') +date_model = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$') +datetime_model = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})[ T]([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$') class xml_timezone(datetime.tzinfo):
@@ -139,13 +141,13 @@
if len(attr.childNodes) == 1:
- return unicode(unescape(attr.childNodes[0].data))
+ return text(unescape(attr.childNodes[0].data))
for node in attr.childNodes:
if not (node.nodeName == "#text" and node.data.strip() == u''):
- text += unicode(unescape(node.data))
+ txt += text(unescape(node.data)) @@ -574,7 +576,7 @@
- "check": lambda x: isinstance(x, (StringType, UnicodeType, etree.ElementBase))
+ "check": lambda x: isinstance(x, (string_types, etree.ElementBase)) @@ -606,7 +608,7 @@
def FindTypeInfos(factory, infos):
- if isinstance(infos, (UnicodeType, StringType)):
+ if isinstance(infos, string_types): namespace, name = DecomposeQualifiedName(infos)
return factory.GetQualifiedNameInfos(name, namespace)
@@ -952,7 +954,7 @@
if parent is not None else None)
parent_class = lookup_classes.get(parent)
if parent_class is not None:
- if isinstance(parent_class, ListType):
+ if isinstance(parent_class, list): if typeinfos not in parent_class:
lookup_classes[parent].append(typeinfos)
elif parent_class != typeinfos:
@@ -962,13 +964,13 @@
def AddToLookupClass(self, name, parent, typeinfos):
lookup_name = self.etreeNamespaceFormat % name
- if isinstance(typeinfos, (StringType, UnicodeType)):
+ if isinstance(typeinfos, string_types): self.AddEquivalentClass(name, typeinfos)
typeinfos = self.etreeNamespaceFormat % typeinfos
lookup_classes = self.ComputedClassesLookUp.get(lookup_name)
if lookup_classes is None:
self.ComputedClassesLookUp[lookup_name] = (typeinfos, parent)
- elif isinstance(lookup_classes, DictType):
+ elif isinstance(lookup_classes, dict): self.AddDistinctionBetweenParentsInLookupClass(
lookup_classes, parent, typeinfos)
@@ -980,7 +982,7 @@
self.ComputedClassesLookUp[lookup_name] = lookup_classes
def ExtractTypeInfos(self, name, parent, typeinfos):
- if isinstance(typeinfos, (StringType, UnicodeType)):
+ if isinstance(typeinfos, string_types): namespace, type_name = DecomposeQualifiedName(typeinfos)
infos = self.GetQualifiedNameInfos(type_name, namespace)
@@ -991,13 +993,13 @@
if infos["type"] == COMPLEXTYPE:
type_name, parent = self.SplitQualifiedName(type_name, namespace)
result = self.CreateClass(type_name, parent, infos)
- if result is not None and not isinstance(result, (UnicodeType, StringType)):
+ if result is not None and not isinstance(result, string_types): self.Namespaces[self.TargetNamespace][result["name"]] = result
elif infos["type"] == ELEMENT and infos["elmt_type"]["type"] == COMPLEXTYPE:
type_name, parent = self.SplitQualifiedName(type_name, namespace)
result = self.CreateClass(type_name, parent, infos["elmt_type"])
- if result is not None and not isinstance(result, (UnicodeType, StringType)):
+ if result is not None and not isinstance(result, string_types): self.Namespaces[self.TargetNamespace][result["name"]] = result
@@ -1019,19 +1021,19 @@
for name, infos in self.Namespaces[self.TargetNamespace].items():
if infos["type"] == ELEMENT:
- if not isinstance(infos["elmt_type"], (UnicodeType, StringType)) and \
+ if not isinstance(infos["elmt_type"], string_types) and \ infos["elmt_type"]["type"] == COMPLEXTYPE:
self.ComputeAfter.append((name, None, infos["elmt_type"], True))
while len(self.ComputeAfter) > 0:
result = self.CreateClass(*self.ComputeAfter.pop(0))
- if result is not None and not isinstance(result, (UnicodeType, StringType)):
+ if result is not None and not isinstance(result, string_types): self.Namespaces[self.TargetNamespace][result["name"]] = result
elif infos["type"] == COMPLEXTYPE:
self.ComputeAfter.append((name, None, infos))
while len(self.ComputeAfter) > 0:
result = self.CreateClass(*self.ComputeAfter.pop(0))
if result is not None and \
- not isinstance(result, (UnicodeType, StringType)):
+ not isinstance(result, string_types): self.Namespaces[self.TargetNamespace][result["name"]] = result
elif infos["type"] == ELEMENTSGROUP:
@@ -1040,17 +1042,17 @@
elements = infos["choices"]
- if not isinstance(element["elmt_type"], (UnicodeType, StringType)) and \
+ if not isinstance(element["elmt_type"], string_types) and \ element["elmt_type"]["type"] == COMPLEXTYPE:
self.ComputeAfter.append((element["name"], infos["name"], element["elmt_type"]))
while len(self.ComputeAfter) > 0:
result = self.CreateClass(*self.ComputeAfter.pop(0))
if result is not None and \
- not isinstance(result, (UnicodeType, StringType)):
+ not isinstance(result, string_types): self.Namespaces[self.TargetNamespace][result["name"]] = result
for name, parents in self.ComputedClassesLookUp.iteritems():
- if isinstance(parents, DictType):
+ if isinstance(parents, dict): computed_classes = parents.items()
elif parents[1] is not None:
computed_classes = [(self.etreeNamespaceFormat % parents[1], parents[0])]
@@ -1058,7 +1060,7 @@
for parent, computed_class in computed_classes:
for equivalent_parent in self.GetEquivalentParents(parent):
- if not isinstance(parents, DictType):
+ if not isinstance(parents, dict): parents = dict(computed_classes)
self.ComputedClassesLookUp[name] = parents
parents[equivalent_parent] = computed_class
@@ -1168,7 +1170,7 @@
classmembers["getElementInfos"] = generateGetElementInfos(self, classinfos)
classmembers["setElementValue"] = generateSetElementValue(self, classinfos)
- class_definition = classobj(str(name), bases, classmembers)
+ class_definition = type(str(name), bases, classmembers) setattr(class_definition, "__getattr__", generateGetattrMethod(self, class_definition, classinfos))
setattr(class_definition, "__setattr__", generateSetattrMethod(self, class_definition, classinfos))
@@ -1248,7 +1250,7 @@
if element["type"] == ANY:
- elements.append(ComputeMultiplicity("#text |#cdata-section |\w* ", infos))
+ elements.append(ComputeMultiplicity(r"#text |#cdata-section |\w* ", infos)) elif element["type"] == CHOICE:
for infos in element["choices"]:
@@ -1381,7 +1383,7 @@
- if not isinstance(value, ListType):
+ if not isinstance(value, list): for element in reversed(value):
@@ -1720,7 +1722,7 @@
-NAMESPACE_PATTERN = re.compile("xmlns(?:\:[^\=]*)?=\"[^\"]*\" ")
+NAMESPACE_PATTERN = re.compile(r"xmlns(?:\:[^\=]*)?=\"[^\"]*\" ") class DefaultElementClass(etree.ElementBase):
@@ -1747,13 +1749,13 @@
def GetElementClass(self, element_tag, parent_tag=None, default=DefaultElementClass):
element_class = self.LookUpClasses.get(element_tag, (default, None))
- if not isinstance(element_class, DictType):
- if isinstance(element_class[0], (StringType, UnicodeType)):
+ if not isinstance(element_class, dict): + if isinstance(element_class[0], string_types): return self.GetElementClass(element_class[0], default=default)
element_with_parent_class = element_class.get(parent_tag, default)
- if isinstance(element_with_parent_class, (StringType, UnicodeType)):
+ if isinstance(element_with_parent_class, string_types): return self.GetElementClass(element_with_parent_class, default=default)
return element_with_parent_class
@@ -1810,12 +1812,12 @@
parent = element.getparent()
element_class = self.GetElementClass(
element.tag, parent.tag if parent is not None else None)
- if isinstance(element_class, ListType):
+ if isinstance(element_class, list): "%s " % etree.QName(child.tag).localname
for possible_class in element_class:
- if isinstance(possible_class, (StringType, UnicodeType)):
+ if isinstance(possible_class, string_types): possible_class = self.GetElementClass(possible_class)
if possible_class.StructurePattern.match(children) is not None:
@@ -1889,7 +1891,7 @@
(subclass of lxml.etree._Element created by class factory)
element_class = self.GetElementClass(element_tag, parent_tag)
- if isinstance(element_class, ListType):
+ if isinstance(element_class, list): if class_idx is not None and class_idx < len(element_class):
element_class = element_class[class_idx]
--- a/xmlclass/xsdschema.py Fri Nov 23 11:01:20 2018 +0100
+++ b/xmlclass/xsdschema.py Fri Nov 23 12:13:24 2018 +0100
@@ -28,8 +28,11 @@
+from types import FunctionType from xml.dom import minidom
+from future.builtins import round +from six import string_types +from past.builtins import long from xmlclass.xmlclass import *
@@ -61,7 +64,7 @@
ind1, _ind2 = getIndent(indent, name)
text += ind1 + "<%s>" % name
- if isinstance(value, IntType):
+ if isinstance(value, int): elif value in extra_values or value % 1 != 0:
text += float_format(value)
@@ -167,7 +170,7 @@
if typeinfos["type"] in ["restriction", "extension"]:
# Search for base type definition
- if isinstance(typeinfos["base"], (StringType, UnicodeType)):
+ if isinstance(typeinfos["base"], string_types): basetypeinfos = factory.FindSchemaElement(typeinfos["base"], SIMPLETYPE)
if basetypeinfos is None:
raise "\"%s\" isn't defined!" % typeinfos["base"]
@@ -391,7 +394,7 @@
elif typeinfos["type"] == "list":
# Search for item type definition
- if isinstance(typeinfos["itemType"], (StringType, UnicodeType)):
+ if isinstance(typeinfos["itemType"], string_types): itemtypeinfos = factory.FindSchemaElement(typeinfos["itemType"], SIMPLETYPE)
if itemtypeinfos is None:
raise "\"%s\" isn't defined!" % typeinfos["itemType"]
@@ -437,7 +440,7 @@
# Search for member types definition
for membertype in typeinfos["memberTypes"]:
- if isinstance(membertype, (StringType, UnicodeType)):
+ if isinstance(membertype, string_types): infos = factory.FindSchemaElement(membertype, SIMPLETYPE)
raise ValueError("\"%s\" isn't defined!" % membertype)
@@ -478,7 +481,7 @@
SimpleTypeInitialValue = membertypesinfos[0]["initial"]
def GenerateSimpleTypeFunction(value):
- if isinstance(value, BooleanType):
+ if isinstance(value, bool): return {True: "true", False: "false"}[value]
@@ -511,7 +514,7 @@
basetypeinfos = factory.FindSchemaElement(base)
- if not isinstance(basetypeinfos, (UnicodeType, StringType)) and basetypeinfos["type"] == COMPLEXTYPE:
+ if not isinstance(basetypeinfos, string_types) and basetypeinfos["type"] == COMPLEXTYPE: attrnames = dict(map(lambda x: (x["name"], True), basetypeinfos["attributes"]))
@@ -812,7 +815,7 @@
raise ValueError("Only group composed of \"choice\" can be referenced in \"choice\" element!")
for choice in elmtgroup["choices"]:
- if not isinstance(choice["elmt_type"], (UnicodeType, StringType)) and choice["elmt_type"]["type"] == COMPLEXTYPE:
+ if not isinstance(choice["elmt_type"], string_types) and choice["elmt_type"]["type"] == COMPLEXTYPE: elmt_type = "%s_%s" % (elmtgroup["name"], choice["name"])
if factory.TargetNamespace is not None:
elmt_type = "%s:%s" % (factory.TargetNamespace, elmt_type)
@@ -846,7 +849,7 @@
raise ValueError("Only group composed of \"sequence\" can be referenced in \"sequence\" element!")
for element in elmtgroup["elements"]:
- if not isinstance(element["elmt_type"], (UnicodeType, StringType)) and element["elmt_type"]["type"] == COMPLEXTYPE:
+ if not isinstance(element["elmt_type"], string_types) and element["elmt_type"]["type"] == COMPLEXTYPE: elmt_type = "%s_%s" % (elmtgroup["name"], element["name"])
if factory.TargetNamespace is not None:
elmt_type = "%s:%s" % (factory.TargetNamespace, elmt_type)
@@ -982,16 +985,16 @@
def CompareSchema(schema, reference):
- if isinstance(schema, ListType):
- if not isinstance(reference, ListType) or len(schema) != len(reference):
+ if isinstance(schema, list): + if not isinstance(reference, list) or len(schema) != len(reference): for i, value in enumerate(schema):
result = CompareSchema(value, reference[i])
- elif isinstance(schema, DictType):
- if not isinstance(reference, DictType) or len(schema) != len(reference):
+ elif isinstance(schema, dict): + if not isinstance(reference, dict) or len(schema) != len(reference): for name, value in schema.items():
ref_value = reference.get(name, None)
@@ -2212,8 +2215,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types)}, @@ -2222,7 +2224,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2232,7 +2234,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2242,7 +2244,7 @@
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, (IntType, LongType))
+ "check": lambda x: isinstance(x, (int, long)) @@ -2252,7 +2254,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: ("%."+str(int(round(len("%X" % x)/2.)*2))+"X") % x),
- "check": lambda x: isinstance(x, (IntType, LongType))
+ "check": lambda x: isinstance(x, (int, long)) @@ -2262,7 +2264,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2272,7 +2274,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2282,7 +2284,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2292,7 +2294,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2302,7 +2304,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2312,7 +2314,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2322,7 +2324,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2332,7 +2334,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2342,7 +2344,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2352,7 +2354,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2362,7 +2364,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2372,7 +2374,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2382,7 +2384,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, IntType)
+ "check": lambda x: isinstance(x, int) @@ -2392,7 +2394,7 @@
"facets": DECIMAL_FACETS,
"generate": GenerateFloatXMLText(decimal=3),
- "check": lambda x: isinstance(x, (IntType, FloatType))
+ "check": lambda x: isinstance(x, (int, float)) @@ -2402,7 +2404,7 @@
"generate": GenerateFloatXMLText(["INF", "-INF", "NaN"]),
- "check": lambda x: {"INF": True, "-INF": True, "NaN": True}.get(x, isinstance(x, (IntType, FloatType)))
+ "check": lambda x: {"INF": True, "-INF": True, "NaN": True}.get(x, isinstance(x, (int, float))) @@ -2412,7 +2414,7 @@
"generate": GenerateFloatXMLText(["INF", "-INF", "NaN"]),
- "check": lambda x: {"INF": True, "-INF": True, "NaN": True}.get(x, isinstance(x, (IntType, FloatType)))
+ "check": lambda x: {"INF": True, "-INF": True, "NaN": True}.get(x, isinstance(x, (int, float))) @@ -2422,7 +2424,7 @@
"facets": GenerateDictFacets(["pattern", "whiteSpace"]),
"generate": GenerateSimpleTypeXMLText(lambda x: {True: "true", False: "false"}[x]),
"initial": lambda: False,
- "check": lambda x: isinstance(x, BooleanType)
+ "check": lambda x: isinstance(x, bool) @@ -2432,7 +2434,7 @@
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2472,7 +2474,7 @@
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2482,7 +2484,7 @@
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2492,7 +2494,7 @@
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2502,7 +2504,7 @@
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2512,7 +2514,7 @@
"generate": GenerateSimpleTypeXMLText(str),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2522,7 +2524,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2532,7 +2534,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2542,7 +2544,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2552,7 +2554,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2562,7 +2564,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2572,7 +2574,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2582,7 +2584,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2592,7 +2594,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2602,7 +2604,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2612,7 +2614,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2622,7 +2624,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2632,7 +2634,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types) @@ -2642,7 +2644,7 @@
"generate": GenerateSimpleTypeXMLText(lambda x: x),
- "check": lambda x: isinstance(x, (StringType, UnicodeType))
+ "check": lambda x: isinstance(x, string_types)