Drop python2 support in scripts.

Signed-off-by: Slávek Banko <slavek.banko@axis.cz>
pull/29/head
Slávek Banko 1 year ago
parent 135d005014
commit 86480e58ea
No known key found for this signature in database
GPG Key ID: 608F5293A04BE668

@ -134,7 +134,7 @@ def parseHeader(headerfile, classname):
if (function.endswith("= 0;")): if (function.endswith("= 0;")):
function = function[:-4] + ";" function = function[:-4] + ";"
print "\t", function print("\t", function)
i+=1 i+=1
@ -162,7 +162,7 @@ def createDCOP(header):
def main(args): def main(args):
for line in args[1:]: for line in args[1:]:
print "Going to create a dcop interface for:", line[:-1] print("Going to create a dcop interface for:", line[:-1])
createDCOP(line.strip()) createDCOP(line.strip())
if __name__=="__main__": if __name__=="__main__":

@ -9,6 +9,6 @@ doc = app.KoApplicationIface.getDocuments()[0]
img=doc.currentImage() img=doc.currentImage()
dev=img.activeDevice() dev=img.activeDevice()
dev.setName("A new name") dev.setName("A new name")
print dev.pixelSize() print(dev.pixelSize())
print dev.nChannels() print(dev.nChannels())
print dev.readBytes(10, 10, 1, 1) print(dev.readBytes(10, 10, 1, 1))

@ -33,7 +33,7 @@ class Inverter:
script.setProgressTotalSteps(width * height) script.setProgressTotalSteps(width * height)
layer.beginPainting("invert") layer.beginPainting("invert")
it = layer.createRectIterator( 0, 0, width, height ) it = layer.createRectIterator( 0, 0, width, height )
print "kikoo\n" print("kikoo\n")
finesh = it.isDone() finesh = it.isDone()
while (not finesh) : while (not finesh) :
p = it.getRGBA() p = it.getRGBA()
@ -42,7 +42,7 @@ class Inverter:
p[2] = 255 - p[2] p[2] = 255 - p[2]
it.setRGBA(p) it.setRGBA(p)
script.incProgress() script.incProgress()
finesh = it.next() finesh = next(it)
layer.endPainting() layer.endPainting()
Inverter() Inverter()

@ -42,10 +42,10 @@ def computeDiff(histo, histoTarget):
count = 1 count = 1
while( count < 255 ) : while( count < 255 ) :
derivdiff.append((diff[count+1] - diff[count - 1])/2.0) derivdiff.append((diff[count+1] - diff[count - 1])/2.0)
print count print(count)
print " " print(" ")
print derivdiff[count] print(derivdiff[count])
print " " print(" ")
count += 1 count += 1
derivdiff.append(diff[255] - diff[254] ) derivdiff.append(diff[255] - diff[254] )
return diff return diff
@ -53,7 +53,7 @@ def computeDiff(histo, histoTarget):
try: try:
import krosschalkcore import krosschalkcore
except: except:
raise "Import of the ChalkCore module failed." raise Exception("Import of the ChalkCore module failed.")
#histoTarget = [ 0.0, 0.01226531745085, 0.024528789662323, 0.0367885716726463, 0.049042819075215, 0.0612896882960706, 0.0735273368712555, 0.0857539237239997, 0.0979676094416996, 0.110166556552646, 0.122348929802458, 0.13451289643019, 0.146656626444054, 0.158778292896733, 0.170876072160234, 0.18294814420024, 0.194992692849922, 0.207007906083172, 0.218991976287209, 0.230943100534525, 0.242859480854121, 0.254739324502003, 0.266580844230888, 0.278382258559083, 0.290141792038499, 0.301857675521758, 0.313528146428344, 0.325151449009778, 0.336725834613756, 0.348249561947225, 0.359720897338346, 0.371138114997318, 0.38249949727601, 0.393803334926368, 0.405047927357568, 0.416231582891849, 0.427352619019025, 0.4384093626496, 0.449400150366478, 0.460323328675215, 0.471177254252771, 0.481960294194744, 0.492670826261026, 0.50330723911986, 0.513867932590253, 0.524351317882718, 0.534755817838293, 0.545079867165813, 0.555321912677404, 0.565480413522147, 0.575553841417885, 0.585540680881154, 0.595439429455167, 0.605248597935856, 0.614966710595909, 0.624592305406788, 0.634123934258679, 0.643560163178352, 0.652899572544893, 0.662140757303275, 0.671282327175744, 0.680322906870975, 0.689261136290974, 0.698095670735701, 0.706825181105366, 0.715448354100387, 0.723963892418968, 0.732370514952268, 0.740666956977137, 0.748851970346384, 0.756924323676554, 0.764882802533185, 0.772726209613504, 0.780453364926561, 0.788063105970749, 0.795554287908693, 0.802925783739486, 0.810176484468239, 0.817305299272921, 0.824311155668464, 0.83119299966812, 0.837949795942015, 0.84458052797292, 0.851084198209167, 0.857459828214736, 0.863706458816447, 0.869823150248263, 0.875808982292675, 0.881663054419139, 0.887384485919556, 0.892972416040772, 0.898426004114068, 0.903744429681637, 0.908926892620016, 0.913972613260457, 0.918880832506229, 0.923650811946811, 0.928281833968988, 0.93277320186481, 0.937124239936404, 0.941334293597632, 0.945402729472569, 0.949328935490789, 0.953112320979447, 0.956752316752142, 0.960248375194552, 0.963599970346811, 0.966806597982642, 0.969867775685214, 0.972783042919718, 0.97555196110265, 0.978174113667795, 0.980649106128898, 0.982976566139007, 0.985156143546496, 0.987187510447739, 0.989070361236445, 0.990804412649628, 0.99238940381023, 0.993825096266363, 0.995111274027184, 0.99624774359539, 0.997234333996328, 0.998070896803715, 0.998757306161974, 0.99929345880516, 0.999679274072503, 0.999914693920536, 0.999999682931835, 0.99993422832034, 0.999718339933283, 0.999352050249705, 0.998835414375572, 0.998168510035481, 0.997351437560967, 0.996384319875413, 0.995267302475555, 0.994000553409588, 0.992584263251893, 0.991018645074359, 0.989303934414332, 0.987440389239176, 0.985428289907469, 0.983267939126818, 0.980959661908326, 0.978503805517689, 0.975900739422957, 0.973150855238948, 0.970254566668332, 0.967212309439392, 0.964024541240472, 0.960691741651122, 0.957214412069943, 0.953593075639162, 0.949828277165924, 0.945920583040329, 0.941870581150226, 0.937678880792763, 0.933346112582728, 0.928872928357675, 0.924260001079857, 0.919508024734984, 0.914617714227821, 0.909589805274631, 0.90442505429249, 0.899124238285494, 0.89368815472786, 0.888117621443952, 0.882413476485242, 0.876576578004235, 0.870607804125365, 0.86450805281288, 0.858278241735758, 0.851919308129644, 0.845432208655849, 0.83881791925743, 0.832077435012361, 0.825211769983833, 0.818221957067693, 0.811109047837053, 0.803874112384084, 0.796518239159033, 0.789042534806467, 0.781448123998789, 0.773736149267035, 0.76590777082899, 0.757964166414642, 0.749906531088995, 0.741736077072283, 0.733454033557598, 0.725061646525966, 0.716560178558895, 0.707950908648432, 0.699235132004742, 0.690414159861254, 0.681489319277395, 0.672461952938941, 0.663333418956019, 0.654105090658787, 0.644778356390828, 0.635354619300277, 0.625835297128734, 0.616221821997965, 0.606515640194456, 0.596718211951823, 0.586831011231134, 0.576855525499155, 0.566793255504575, 0.556645715052225, 0.546414430775338, 0.536100941905873, 0.525706800042952, 0.515233568919429, 0.504682824166636, 0.49405615307734, 0.483355154366944, 0.472581437932973, 0.461736624612871, 0.450822345940161, 0.439840243898986, 0.428791970677089, 0.417679188417244, 0.406503568967204, 0.39526679362818, 0.383970552901897, 0.372616546236274, 0.361206481769749, 0.349742076074299, 0.338225053897198, 0.326657147901536, 0.315040098405551, 0.303375653120808, 0.291665566889271, 0.279911601419294, 0.268115525020586, 0.256279112338177, 0.244404144085436, 0.232492406776176, 0.220545692455878, 0.208565798432095, 0.196554527004056, 0.184513685191523, 0.172445084462932, 0.160350540462877, 0.148231872738948, 0.136090904468, 0.123929462181863, 0.111749375492553, 0.0995524768170189, 0.0873406011014653, 0.0751155855452987, 0.0628792693247314, 0.0506334933160884, 0.0383800998188613, 0.0261209322785436, 0.0138578350092972 ] #histoTarget = [ 0.0, 0.01226531745085, 0.024528789662323, 0.0367885716726463, 0.049042819075215, 0.0612896882960706, 0.0735273368712555, 0.0857539237239997, 0.0979676094416996, 0.110166556552646, 0.122348929802458, 0.13451289643019, 0.146656626444054, 0.158778292896733, 0.170876072160234, 0.18294814420024, 0.194992692849922, 0.207007906083172, 0.218991976287209, 0.230943100534525, 0.242859480854121, 0.254739324502003, 0.266580844230888, 0.278382258559083, 0.290141792038499, 0.301857675521758, 0.313528146428344, 0.325151449009778, 0.336725834613756, 0.348249561947225, 0.359720897338346, 0.371138114997318, 0.38249949727601, 0.393803334926368, 0.405047927357568, 0.416231582891849, 0.427352619019025, 0.4384093626496, 0.449400150366478, 0.460323328675215, 0.471177254252771, 0.481960294194744, 0.492670826261026, 0.50330723911986, 0.513867932590253, 0.524351317882718, 0.534755817838293, 0.545079867165813, 0.555321912677404, 0.565480413522147, 0.575553841417885, 0.585540680881154, 0.595439429455167, 0.605248597935856, 0.614966710595909, 0.624592305406788, 0.634123934258679, 0.643560163178352, 0.652899572544893, 0.662140757303275, 0.671282327175744, 0.680322906870975, 0.689261136290974, 0.698095670735701, 0.706825181105366, 0.715448354100387, 0.723963892418968, 0.732370514952268, 0.740666956977137, 0.748851970346384, 0.756924323676554, 0.764882802533185, 0.772726209613504, 0.780453364926561, 0.788063105970749, 0.795554287908693, 0.802925783739486, 0.810176484468239, 0.817305299272921, 0.824311155668464, 0.83119299966812, 0.837949795942015, 0.84458052797292, 0.851084198209167, 0.857459828214736, 0.863706458816447, 0.869823150248263, 0.875808982292675, 0.881663054419139, 0.887384485919556, 0.892972416040772, 0.898426004114068, 0.903744429681637, 0.908926892620016, 0.913972613260457, 0.918880832506229, 0.923650811946811, 0.928281833968988, 0.93277320186481, 0.937124239936404, 0.941334293597632, 0.945402729472569, 0.949328935490789, 0.953112320979447, 0.956752316752142, 0.960248375194552, 0.963599970346811, 0.966806597982642, 0.969867775685214, 0.972783042919718, 0.97555196110265, 0.978174113667795, 0.980649106128898, 0.982976566139007, 0.985156143546496, 0.987187510447739, 0.989070361236445, 0.990804412649628, 0.99238940381023, 0.993825096266363, 0.995111274027184, 0.99624774359539, 0.997234333996328, 0.998070896803715, 0.998757306161974, 0.99929345880516, 0.999679274072503, 0.999914693920536, 0.999999682931835, 0.99993422832034, 0.999718339933283, 0.999352050249705, 0.998835414375572, 0.998168510035481, 0.997351437560967, 0.996384319875413, 0.995267302475555, 0.994000553409588, 0.992584263251893, 0.991018645074359, 0.989303934414332, 0.987440389239176, 0.985428289907469, 0.983267939126818, 0.980959661908326, 0.978503805517689, 0.975900739422957, 0.973150855238948, 0.970254566668332, 0.967212309439392, 0.964024541240472, 0.960691741651122, 0.957214412069943, 0.953593075639162, 0.949828277165924, 0.945920583040329, 0.941870581150226, 0.937678880792763, 0.933346112582728, 0.928872928357675, 0.924260001079857, 0.919508024734984, 0.914617714227821, 0.909589805274631, 0.90442505429249, 0.899124238285494, 0.89368815472786, 0.888117621443952, 0.882413476485242, 0.876576578004235, 0.870607804125365, 0.86450805281288, 0.858278241735758, 0.851919308129644, 0.845432208655849, 0.83881791925743, 0.832077435012361, 0.825211769983833, 0.818221957067693, 0.811109047837053, 0.803874112384084, 0.796518239159033, 0.789042534806467, 0.781448123998789, 0.773736149267035, 0.76590777082899, 0.757964166414642, 0.749906531088995, 0.741736077072283, 0.733454033557598, 0.725061646525966, 0.716560178558895, 0.707950908648432, 0.699235132004742, 0.690414159861254, 0.681489319277395, 0.672461952938941, 0.663333418956019, 0.654105090658787, 0.644778356390828, 0.635354619300277, 0.625835297128734, 0.616221821997965, 0.606515640194456, 0.596718211951823, 0.586831011231134, 0.576855525499155, 0.566793255504575, 0.556645715052225, 0.546414430775338, 0.536100941905873, 0.525706800042952, 0.515233568919429, 0.504682824166636, 0.49405615307734, 0.483355154366944, 0.472581437932973, 0.461736624612871, 0.450822345940161, 0.439840243898986, 0.428791970677089, 0.417679188417244, 0.406503568967204, 0.39526679362818, 0.383970552901897, 0.372616546236274, 0.361206481769749, 0.349742076074299, 0.338225053897198, 0.326657147901536, 0.315040098405551, 0.303375653120808, 0.291665566889271, 0.279911601419294, 0.268115525020586, 0.256279112338177, 0.244404144085436, 0.232492406776176, 0.220545692455878, 0.208565798432095, 0.196554527004056, 0.184513685191523, 0.172445084462932, 0.160350540462877, 0.148231872738948, 0.136090904468, 0.123929462181863, 0.111749375492553, 0.0995524768170189, 0.0873406011014653, 0.0751155855452987, 0.0628792693247314, 0.0506334933160884, 0.0383800998188613, 0.0261209322785436, 0.0138578350092972 ]
@ -71,10 +71,10 @@ height = layer.getHeight()
countreshaping = 0 countreshaping = 0
while countreshaping < 1: while countreshaping < 1:
histo = layer.createHistogram("RGB8HISTO",0) histo = layer.createHistogram("RGB8HISTO",0)
print "################################### histogram reshaping ##################################################" print("################################### histogram reshaping ##################################################")
if histo == 0: if histo == 0:
raise "Uncompatible histogram\n" raise Exception("Uncompatible histogram")
print "Max : " + str( histo.getMax() ) + " Min : " + str( histo.getMin() ) print("Max : " + str( histo.getMax() ) + " Min : " + str( histo.getMin() ))
#Compute the area of the target histogram #Compute the area of the target histogram
aireHistoTarget = 0.0 aireHistoTarget = 0.0
@ -133,7 +133,7 @@ while countreshaping < 1:
count += 1 count += 1
it = layer.createRectIterator( 0, 0, width, height ) it = layer.createRectIterator( 0, 0, width, height )
print "kikoo : " + str(countreshaping) print("kikoo : " + str(countreshaping))
while (not it.isDone()) : while (not it.isDone()) :
r = it.getRed() r = it.getRed()
g = it.getGreen() g = it.getGreen()
@ -145,7 +145,7 @@ while countreshaping < 1:
it.setRed(tabler[r]) it.setRed(tabler[r])
it.setGreen(tableg[g]) it.setGreen(tableg[g])
it.setBlue(tableb[b]) it.setBlue(tableb[b])
it.next() next(it)
#histo.setChannel(0) #histo.setChannel(0)
#diff = [ ] #diff = [ ]

@ -27,7 +27,7 @@ class CopyCenter:
return getattr(self.plugin, plugintype)(self.plugin) return getattr(self.plugin, plugintype)(self.plugin)
except: except:
import traceback import traceback
print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
return None return None
def __init__(self, scriptpath): def __init__(self, scriptpath):
@ -38,7 +38,7 @@ class CopyCenter:
import os import os
import sys import sys
if not os.path.exists(scriptpath): if not os.path.exists(scriptpath):
print "The Path %s does not exist" % scriptpath print("The Path %s does not exist" % scriptpath)
else: else:
import re import re
regexp = re.compile('^CopyCenterPlugin(.*)\\.py$') regexp = re.compile('^CopyCenterPlugin(.*)\\.py$')
@ -47,17 +47,17 @@ class CopyCenter:
if not os.path.isfile(file): continue if not os.path.isfile(file): continue
m = regexp.match(f) m = regexp.match(f)
if not m: continue if not m: continue
print "Plugin name=%s file=%s" % (m.group(1),file) print("Plugin name=%s file=%s" % (m.group(1),file))
mylocals = {} mylocals = {}
try: try:
execfile(file, globals(), mylocals) exec(compile(open(file, "rb").read(), file, 'exec'), globals(), mylocals)
if mylocals.has_key("CopyCenterPlugin"): if "CopyCenterPlugin" in mylocals:
plugin = mylocals.get("CopyCenterPlugin")(self) plugin = mylocals.get("CopyCenterPlugin")(self)
self.plugins[plugin.name] = self.Plugin(plugin) self.plugins[plugin.name] = self.Plugin(plugin)
except: except:
print "Failed to import file=%s" % file print("Failed to import file=%s" % file)
import traceback import traceback
print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
def getHomePath(self): def getHomePath(self):
""" Return the homedirectory. """ """ Return the homedirectory. """
@ -163,20 +163,20 @@ def runGuiApp(copycenter, name):
#qt.TQObject.connect(self.listview, qt.SIGNAL("itemRenamed(QListViewItem*, int, const QString&)"), self.itemRenamed) #qt.TQObject.connect(self.listview, qt.SIGNAL("itemRenamed(QListViewItem*, int, const QString&)"), self.itemRenamed)
def doubleClicked(self, **args): def doubleClicked(self, **args):
print "CopyJobWidget.doubleClicked" print("CopyJobWidget.doubleClicked")
item = self.listview.selectedItem() item = self.listview.selectedItem()
if item and item.parent(): item.startRename(1) if item and item.parent(): item.startRename(1)
def readOptions(self,domnode,plugininst): def readOptions(self,domnode,plugininst):
print "CopyJobWidget.readOptions plugintype=\"%s\"" % plugininst.plugintype print("CopyJobWidget.readOptions plugintype=\"%s\"" % plugininst.plugintype)
for node in domnode.childNodes: for node in domnode.childNodes:
if node.nodeType == node.ELEMENT_NODE: if node.nodeType == node.ELEMENT_NODE:
v = node.getAttribute("value") v = node.getAttribute("value")
plugininst.options[node.nodeName] = v plugininst.options[node.nodeName] = v
print "Option \"%s\" has value \"%s\" now." % (node.nodeName, v) print("Option \"%s\" has value \"%s\" now." % (node.nodeName, v))
def jobfilecomboboxChanged(self, **args): def jobfilecomboboxChanged(self, **args):
print "CopyJobWidget.jobfilecomboboxChanged" print("CopyJobWidget.jobfilecomboboxChanged")
import os import os
import xml.dom.minidom import xml.dom.minidom
filename = str(self.jobfilecombobox.currentText()) filename = str(self.jobfilecombobox.currentText())
@ -187,16 +187,16 @@ def runGuiApp(copycenter, name):
sourcenode = elements.getElementsByTagName("Source")[0] sourcenode = elements.getElementsByTagName("Source")[0]
destinationnode = elements.getElementsByTagName("Destination")[0] destinationnode = elements.getElementsByTagName("Destination")[0]
except: except:
raise "The XML-file \"%s\" does not contain a valid copy-job." % filename raise Exception("The XML-file \"%s\" does not contain a valid copy-job." % filename)
sourcepluginname = str(sourcenode.getAttribute('plugin')) sourcepluginname = str(sourcenode.getAttribute('plugin'))
if not self.dialog.sourcedata.combobox.listBox().findItem(sourcepluginname,qt.TQt.ExactMatch): if not self.dialog.sourcedata.combobox.listBox().findItem(sourcepluginname,qt.TQt.ExactMatch):
raise "There exists no plugin with the name \"%s\"." % sourcepluginname raise Exception("There exists no plugin with the name \"%s\"." % sourcepluginname)
self.dialog.sourcedata.combobox.setCurrentText(sourcepluginname) self.dialog.sourcedata.combobox.setCurrentText(sourcepluginname)
destinationpluginname = str(destinationnode.getAttribute('plugin')) destinationpluginname = str(destinationnode.getAttribute('plugin'))
if not self.dialog.destinationdata.combobox.listBox().findItem(destinationpluginname,qt.TQt.ExactMatch): if not self.dialog.destinationdata.combobox.listBox().findItem(destinationpluginname,qt.TQt.ExactMatch):
raise "There exists no plugin with the name \"%s\"." % destinationpluginname raise Exception("There exists no plugin with the name \"%s\"." % destinationpluginname)
self.dialog.destinationdata.combobox.setCurrentText(destinationpluginname) self.dialog.destinationdata.combobox.setCurrentText(destinationpluginname)
self.readOptions(sourcenode,self.dialog.getSourcePluginImpl()) self.readOptions(sourcenode,self.dialog.getSourcePluginImpl())
@ -213,10 +213,10 @@ def runGuiApp(copycenter, name):
return s.replace("&", "&amp;").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;") return s.replace("&", "&amp;").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
def writeOptions(self,writer,pluginname,plugininst): def writeOptions(self,writer,pluginname,plugininst):
print "CopyJobWidget.writeOptions" print("CopyJobWidget.writeOptions")
writer.write("<%s plugin=\"%s\">\n" % (plugininst.plugintype, pluginname)) writer.write("<%s plugin=\"%s\">\n" % (plugininst.plugintype, pluginname))
for optionname in plugininst.options: for optionname in plugininst.options:
value = self.escape( unicode(plugininst.options[optionname]).encode("utf-8") ) value = self.escape( str(plugininst.options[optionname]).encode("utf-8") )
writer.write("\t<%s value=\"%s\" />\n" % (optionname,value)) writer.write("\t<%s value=\"%s\" />\n" % (optionname,value))
writer.write("</%s>\n" % plugininst.plugintype) writer.write("</%s>\n" % plugininst.plugintype)
@ -236,7 +236,7 @@ def runGuiApp(copycenter, name):
self.writeOptions(f, destinationpluginname, self.dialog.getDestinationPluginImpl()) self.writeOptions(f, destinationpluginname, self.dialog.getDestinationPluginImpl())
f.write("</CopyCenterJob>\n") f.write("</CopyCenterJob>\n")
f.close() f.close()
print "File \%s\" successfully written." % filename print("File \%s\" successfully written." % filename)
def addItem(self, pluginimpl, afteritem = None, parentitem = None): def addItem(self, pluginimpl, afteritem = None, parentitem = None):
#print "CopyJobWidget.addItem" #print "CopyJobWidget.addItem"
@ -262,11 +262,11 @@ def runGuiApp(copycenter, name):
def okRename(self, columnindex): def okRename(self, columnindex):
if columnindex == 1: if columnindex == 1:
n = str(self.text(0)) n = str(self.text(0))
if not self.pluginimpl.options.has_key(n): if n not in self.pluginimpl.options:
raise "No such option \"%s\"" % n raise Exception("No such option \"%s\"" % n)
qt.TQListViewItem.okRename(self,columnindex) qt.TQListViewItem.okRename(self,columnindex)
v = str(qt.TQListViewItem.text(self,1)) v = str(qt.TQListViewItem.text(self,1))
print "Option \"%s\" has value \"%s\" now." % (n,v) print("Option \"%s\" has value \"%s\" now." % (n,v))
self.pluginimpl.options[n] = v self.pluginimpl.options[n] = v
def text(self, columnindex): def text(self, columnindex):
@ -287,18 +287,18 @@ def runGuiApp(copycenter, name):
afteritem = self.addItem(pluginimpl, afteritem, item) afteritem = self.addItem(pluginimpl, afteritem, item)
afteritem.setText(0,str(i)) afteritem.setText(0,str(i))
afteritem.setText(1,str(pluginimpl.options[i])) afteritem.setText(1,str(pluginimpl.options[i]))
print "CopyJobWidget.updateItem Added item with name \"%s\" and value \"%s\"" % (str(i),str(pluginimpl.options[i])) print("CopyJobWidget.updateItem Added item with name \"%s\" and value \"%s\"" % (str(i),str(pluginimpl.options[i])))
pass pass
def maybeUpdate(self): def maybeUpdate(self):
print "CopyJobWidget.maybeUpdate" print("CopyJobWidget.maybeUpdate")
self.listview.clear() self.listview.clear()
try: try:
self.updateItem(self.dialog.getDestinationPluginName(), self.dialog.getDestinationPluginImpl()) self.updateItem(self.dialog.getDestinationPluginName(), self.dialog.getDestinationPluginImpl())
self.updateItem(self.dialog.getSourcePluginName(), self.dialog.getSourcePluginImpl()) self.updateItem(self.dialog.getSourcePluginName(), self.dialog.getSourcePluginImpl())
except: except:
import traceback import traceback
print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
self.listview.clear() self.listview.clear()
#-------------------------------------------------------------------- #--------------------------------------------------------------------
@ -382,7 +382,7 @@ def runGuiApp(copycenter, name):
sourceimpl = self.dialog.getSourcePluginImpl() sourceimpl = self.dialog.getSourcePluginImpl()
self.textbrowser.append("Source: %s" % sourcename) self.textbrowser.append("Source: %s" % sourcename)
if sourceimpl == None: if sourceimpl == None:
raise "No such source." raise Exception("No such source.")
try: try:
sourceimpl.init(copierer) sourceimpl.init(copierer)
@ -391,7 +391,7 @@ def runGuiApp(copycenter, name):
destinationimpl = self.dialog.getDestinationPluginImpl() destinationimpl = self.dialog.getDestinationPluginImpl()
self.textbrowser.append("<hr>Destination: %s" % destinationname) self.textbrowser.append("<hr>Destination: %s" % destinationname)
if destinationimpl == None: if destinationimpl == None:
raise "No such destination." raise Exception("No such destination.")
try: try:
destinationimpl.init(copierer) destinationimpl.init(copierer)
@ -418,7 +418,7 @@ def runGuiApp(copycenter, name):
self.setCaption("Copy failed") self.setCaption("Copy failed")
self.textbrowser.append("<b>Error: %s</b>" % sys.exc_info()[0]) self.textbrowser.append("<b>Error: %s</b>" % sys.exc_info()[0])
import traceback import traceback
print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
#self.progressbar.setEnabled(False) #self.progressbar.setEnabled(False)
self.donebtn.setEnabled(True) self.donebtn.setEnabled(True)
self.cancelbtn.setEnabled(False) self.cancelbtn.setEnabled(False)
@ -468,11 +468,11 @@ def runGuiApp(copycenter, name):
self.scrollview.viewport().setPaletteBackgroundColor(self.paletteBackgroundColor()) self.scrollview.viewport().setPaletteBackgroundColor(self.paletteBackgroundColor())
except: except:
import traceback import traceback
print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
qt.TQObject.connect(self.combobox, qt.SIGNAL("activated(int)"), self.activated) qt.TQObject.connect(self.combobox, qt.SIGNAL("activated(int)"), self.activated)
def updatePlugin(self): def updatePlugin(self):
print "DataSelector.updatePlugin" print("DataSelector.updatePlugin")
self.pluginimpl = None self.pluginimpl = None
text = str(self.combobox.currentText()) text = str(self.combobox.currentText())
plugin = self.dialog.copycenter.plugins[text] plugin = self.dialog.copycenter.plugins[text]
@ -488,7 +488,7 @@ def runGuiApp(copycenter, name):
self.mainbox = None self.mainbox = None
def updateMainBox(self): def updateMainBox(self):
print "DataSelector.updateMainBox" print("DataSelector.updateMainBox")
self.removeMainBox() self.removeMainBox()
self.mainbox = qt.TQVBox( self.scrollview.viewport() ) self.mainbox = qt.TQVBox( self.scrollview.viewport() )
self.mainbox.setSpacing(2) self.mainbox.setSpacing(2)
@ -497,7 +497,7 @@ def runGuiApp(copycenter, name):
self.pluginimpl.createWidget(self.dialog, self.mainbox) self.pluginimpl.createWidget(self.dialog, self.mainbox)
except: except:
import traceback import traceback
print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
self.mainbox.setStretchFactor(qt.TQWidget(self.mainbox), 1) self.mainbox.setStretchFactor(qt.TQWidget(self.mainbox), 1)
self.mainbox.show() self.mainbox.show()
self.scrollview.addChild(self.mainbox) self.scrollview.addChild(self.mainbox)
@ -507,12 +507,12 @@ def runGuiApp(copycenter, name):
self.updateMainBox() self.updateMainBox()
def maybeUpdate(self): def maybeUpdate(self):
print "DataSelector.maybeUpdate" print("DataSelector.maybeUpdate")
self.removeMainBox() self.removeMainBox()
qt.TQTimer.singleShot(50, self.activated) qt.TQTimer.singleShot(50, self.activated)
def maybeDone(self): def maybeDone(self):
print "DataSelector.maybeDone" print("DataSelector.maybeDone")
if self.pluginimpl.widget == None: return if self.pluginimpl.widget == None: return
for optionname in self.pluginimpl.options: for optionname in self.pluginimpl.options:
self.pluginimpl.options[optionname] = self.pluginimpl.widget.getOptionValue(optionname) self.pluginimpl.options[optionname] = self.pluginimpl.widget.getOptionValue(optionname)
@ -588,7 +588,7 @@ def runGuiApp(copycenter, name):
defaultfile = os.path.join(self.copycenter.homepath,"default.copycenterjob.xml") defaultfile = os.path.join(self.copycenter.homepath,"default.copycenterjob.xml")
if os.path.isfile(defaultfile): if os.path.isfile(defaultfile):
print "Reading default copy job file: %s" % defaultfile print("Reading default copy job file: %s" % defaultfile)
self.jobsbox.jobfilecombobox.setCurrentText(defaultfile) self.jobsbox.jobfilecombobox.setCurrentText(defaultfile)
def getSourcePluginName(self): def getSourcePluginName(self):

@ -104,33 +104,33 @@ class CopyCenterPlugin:
self.copierer = copierer self.copierer = copierer
if self.kexidbconnection == None: if self.kexidbconnection == None:
if self.plugin.widget == None: if self.plugin.widget == None:
raise "No connection established." raise Exception("No connection established.")
self.copierer.appendProgressMessage("<i>Trying to connect...</i>") self.copierer.appendProgressMessage("<i>Trying to connect...</i>")
if self.plugin.widget.driverbox.driver == None: if self.plugin.widget.driverbox.driver == None:
raise "Invalid driver." raise Exception("Invalid driver.")
if not self.plugin.widget.connectClicked(): if not self.plugin.widget.connectClicked():
raise "Failed to connect." raise Exception("Failed to connect.")
connectiondata = self.kexidbconnection.data() connectiondata = self.kexidbconnection.data()
self.copierer.appendProgressMessage("Connected: %s %s" % (connectiondata.driverName(),connectiondata.serverInfoString())) self.copierer.appendProgressMessage("Connected: %s %s" % (connectiondata.driverName(),connectiondata.serverInfoString()))
tablename = str(self.plugin.widget.tablebox.tableedit.text()) tablename = str(self.plugin.widget.tablebox.tableedit.text())
if tablename == "": if tablename == "":
raise "No table defined" raise Exception("No table defined")
fields = [ f.strip() for f in str(self.plugin.widget.fieldbox.fieldsedit.text()).split(",") if len(f) > 0 ] fields = [ f.strip() for f in str(self.plugin.widget.fieldbox.fieldsedit.text()).split(",") if len(f) > 0 ]
if len(fields) < 1: if len(fields) < 1:
raise "No fields defined" raise Exception("No fields defined")
self.tableschema = self.kexidbconnection.tableSchema(tablename) self.tableschema = self.kexidbconnection.tableSchema(tablename)
if not self.tableschema: raise "No such tableschema \"%s\"" % tablename if not self.tableschema: raise Exception("No such tableschema \"%s\"" % tablename)
self.copierer.appendProgressMessage("Table: %s" % self.tableschema.name()) self.copierer.appendProgressMessage("Table: %s" % self.tableschema.name())
if len(fields) == 1 and fields[0] == "*": if len(fields) == 1 and fields[0] == "*":
self.fieldlist = self.tableschema.fieldlist() self.fieldlist = self.tableschema.fieldlist()
else: else:
self.fieldlist = self.tableschema.fieldlist().subList(fields) self.fieldlist = self.tableschema.fieldlist().subList(fields)
if not self.fieldlist: raise "No such fields \"%s\"" % fields if not self.fieldlist: raise Exception("No such fields \"%s\"" % fields)
fieldlistnames = self.fieldlist.names() fieldlistnames = self.fieldlist.names()
if len(fieldlistnames) < 1: raise "No valid fields defined for \"%s\"" % fields if len(fieldlistnames) < 1: raise Exception("No valid fields defined for \"%s\"" % fields)
self.copierer.appendProgressMessage("Fields: %s" % fieldlistnames) self.copierer.appendProgressMessage("Fields: %s" % fieldlistnames)
def finish(self): def finish(self):
if self.plugin.widget == None: if self.plugin.widget == None:
@ -146,24 +146,24 @@ class CopyCenterPlugin:
return self.copierer == None return self.copierer == None
def initRead(self): def initRead(self):
print "Initialize read" print("Initialize read")
#queryschema = self.plugin.copycenterplugin.drivermanager.querySchema() #queryschema = self.plugin.copycenterplugin.drivermanager.querySchema()
queryschema = self.tableschema.query() queryschema = self.tableschema.query()
queryschema.fieldlist().setFields(self.fieldlist) queryschema.fieldlist().setFields(self.fieldlist)
print "QuerySchema: %s" % queryschema.fieldlist().names() print("QuerySchema: %s" % queryschema.fieldlist().names())
whereexpression = str(self.plugin.widget.whereedit.text()) whereexpression = str(self.plugin.widget.whereedit.text())
if whereexpression != "": if whereexpression != "":
print "WHERE-expression: %s" % whereexpression print("WHERE-expression: %s" % whereexpression)
if not queryschema.setWhereExpression(whereexpression): if not queryschema.setWhereExpression(whereexpression):
raise "Invalid WHERE-expression." raise Exception("Invalid WHERE-expression.")
#print "QuerySchema statement=%s" % queryschema.statement() #print "QuerySchema statement=%s" % queryschema.statement()
self.kexidbcursor = self.kexidbconnection.executeQuerySchema(queryschema) self.kexidbcursor = self.kexidbconnection.executeQuerySchema(queryschema)
if not self.kexidbcursor: if not self.kexidbcursor:
raise "Failed to create cursor." raise Exception("Failed to create cursor.")
if not self.kexidbcursor.moveFirst(): if not self.kexidbcursor.moveFirst():
raise "The cursor has no records to read from." raise Exception("The cursor has no records to read from.")
def readRecord(self): def readRecord(self):
if self.kexidbcursor == None or self.kexidbcursor.eof(): if self.kexidbcursor == None or self.kexidbcursor.eof():
@ -176,15 +176,15 @@ class CopyCenterPlugin:
return record return record
def initWrite(self): def initWrite(self):
print "Initialize write" print("Initialize write")
def writeRecord(self,record): def writeRecord(self,record):
print "write record: %s" % record print("write record: %s" % record)
if self.kexidbconnection.insertRecord(self.fieldlist,record): if self.kexidbconnection.insertRecord(self.fieldlist,record):
print "=> insert successfully" print("=> insert successfully")
self.copierer.writeSuccess(record, 1) self.copierer.writeSuccess(record, 1)
else: else:
print "=> insert failed: %s" % self.kexidbconnection.lastError() print("=> insert failed: %s" % self.kexidbconnection.lastError())
self.copierer.writeFailed(record) self.copierer.writeFailed(record)
#import time #import time
#time.sleep(1) #time.sleep(1)
@ -546,10 +546,10 @@ class CopyCenterPlugin:
connectiondata = self.copycenterplugin.drivermanager.createConnectionDataByFile(file) connectiondata = self.copycenterplugin.drivermanager.createConnectionDataByFile(file)
if connectiondata == None: if connectiondata == None:
raise "Unsupported file." raise Exception("Unsupported file.")
drivername = connectiondata.driverName().lower() drivername = connectiondata.driverName().lower()
print "driver: %s" % drivername print("driver: %s" % drivername)
for i in range(1,self.driverbox.drivercombo.count()): for i in range(1,self.driverbox.drivercombo.count()):
if drivername == self.driverbox.drivercombo.text(i).lower(): if drivername == self.driverbox.drivercombo.text(i).lower():
self.driverbox.drivercombo.setCurrentItem(i) self.driverbox.drivercombo.setCurrentItem(i)
@ -570,7 +570,7 @@ class CopyCenterPlugin:
def connectClicked(self): def connectClicked(self):
if self.driverbox.driver == None: if self.driverbox.driver == None:
print "No driver selected." print("No driver selected.")
return False return False
connectiondata = self.copycenterplugin.drivermanager.createConnectionData() connectiondata = self.copycenterplugin.drivermanager.createConnectionData()
if self.driverbox.driver.isFileDriver(): if self.driverbox.driver.isFileDriver():
@ -588,18 +588,18 @@ class CopyCenterPlugin:
connectiondata.setPassword(str(self.driverbox.passedit.text())) connectiondata.setPassword(str(self.driverbox.passedit.text()))
connectiondata.setUserName(str(self.driverbox.useredit.text())) connectiondata.setUserName(str(self.driverbox.useredit.text()))
connectiondata.setDatabaseName(str(self.driverbox.dbedit.text())) connectiondata.setDatabaseName(str(self.driverbox.dbedit.text()))
print "Creating connection" print("Creating connection")
connection = self.driverbox.driver.createConnection(connectiondata) connection = self.driverbox.driver.createConnection(connectiondata)
print "Trying to connect" print("Trying to connect")
if not connection.connect(): if not connection.connect():
qt.TQMessageBox.critical(self,"Failed to connect",connection.lastError()) qt.TQMessageBox.critical(self,"Failed to connect",connection.lastError())
return False return False
print "Use database \"%s\"" % connectiondata.databaseName() print("Use database \"%s\"" % connectiondata.databaseName())
if not connection.useDatabase( connectiondata.databaseName() ): if not connection.useDatabase( connectiondata.databaseName() ):
qt.TQMessageBox.critical(self,"Failed to connect",connection.lastError()) qt.TQMessageBox.critical(self,"Failed to connect",connection.lastError())
return False return False
print "dbnames = %s" % connection.databaseNames() print("dbnames = %s" % connection.databaseNames())
print "tablenames = %s" % connection.tableNames() print("tablenames = %s" % connection.tableNames())
#self.useDatabase(connection, filename) #self.useDatabase(connection, filename)
self.plugin.connection.kexidbconnection = connection self.plugin.connection.kexidbconnection = connection

@ -28,9 +28,9 @@ class CopyCenterPlugin:
def _init(self,copierer): def _init(self,copierer):
self.copierer = copierer self.copierer = copierer
if not self.widget.connectClicked(): if not self.widget.connectClicked():
raise "Failed to connect with database." raise Exception("Failed to connect with database.")
if self.database == None or not self.database.isOpen(): if self.database == None or not self.database.isOpen():
raise "Database is not initialized or not opened." raise Exception("Database is not initialized or not opened.")
self.copierer.appendProgressMessage("Connected: %s %s@%s:%i %s" % self.copierer.appendProgressMessage("Connected: %s %s@%s:%i %s" %
(str(self.database.driverName()),str(self.database.userName()),str(self.database.hostName()),self.database.port(),str(self.database.databaseName())) ) (str(self.database.driverName()),str(self.database.userName()),str(self.database.hostName()),self.database.port(),str(self.database.databaseName())) )
self.isfinished = False self.isfinished = False
@ -66,25 +66,25 @@ class CopyCenterPlugin:
self.cursor = qtsql.TQSqlCursor(tablename,True,self.database) self.cursor = qtsql.TQSqlCursor(tablename,True,self.database)
self.cursor.setFilter(wherestatement) self.cursor.setFilter(wherestatement)
if not self.cursor.select(): if not self.cursor.select():
raise "Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ) raise Exception("Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ))
self.fieldlist = [] self.fieldlist = []
for fieldname in str(self.widget.fieldedit.text()).split(","): for fieldname in str(self.widget.fieldedit.text()).split(","):
fn = fieldname.strip() fn = fieldname.strip()
if fn != "": if fn != "":
field = self.cursor.field(fn) field = self.cursor.field(fn)
if not field: if not field:
raise "There exists no such field \"%s\" in the table \"%s\"." % (fn,tablename) raise Exception("There exists no such field \"%s\" in the table \"%s\"." % (fn,tablename))
self.fieldlist.append(str(field.name())) self.fieldlist.append(str(field.name()))
if len(self.fieldlist) < 1: if len(self.fieldlist) < 1:
raise "No fields for table \"%s\" defined." % tablename raise Exception("No fields for table \"%s\" defined." % tablename)
copierer.appendProgressMessage("SQL: %s" % str(self.cursor.executedQuery())) copierer.appendProgressMessage("SQL: %s" % str(self.cursor.executedQuery()))
def read(self): def read(self):
if not self.cursor.next(): if not next(self.cursor):
return None return None
record = [] record = []
for fieldname in self.fieldlist: for fieldname in self.fieldlist:
record.append( unicode(self.cursor.value(fieldname).toString()).encode("latin-1") ) record.append( str(self.cursor.value(fieldname).toString()).encode("latin-1") )
#print "read record: %s" % record #print "read record: %s" % record
return record return record
@ -124,14 +124,14 @@ class CopyCenterPlugin:
def initInsert(self): def initInsert(self):
self.write = self.writeInsert self.write = self.writeInsert
if not self.cursor.select(): if not self.cursor.select():
raise "Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ) raise Exception("Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ))
for fieldname in self.fieldlist: # check fieldlist for fieldname in self.fieldlist: # check fieldlist
field = self.cursor.field(fieldname) field = self.cursor.field(fieldname)
if not field: raise "There exists no such field \"%s\" in the table \"%s\"." % (fieldname, self.cursor.name()) if not field: raise Exception("There exists no such field \"%s\" in the table \"%s\"." % (fieldname, self.cursor.name()))
self.copierer.appendProgressMessage("Insert SQL: %s" % str(self.cursor.executedQuery())) self.copierer.appendProgressMessage("Insert SQL: %s" % str(self.cursor.executedQuery()))
def writeInsert(self, record): def writeInsert(self, record):
print "insert record: %s" % record print("insert record: %s" % record)
from TQt import qt from TQt import qt
cursorrecord = self.cursor.primeInsert() cursorrecord = self.cursor.primeInsert()
count = len(record) count = len(record)
@ -145,9 +145,9 @@ class CopyCenterPlugin:
cursorrecord.setValue(self.fieldlist[i], v) cursorrecord.setValue(self.fieldlist[i], v)
rowcount = self.cursor.insert() rowcount = self.cursor.insert()
if rowcount < 1: if rowcount < 1:
drv = unicode(self.cursor.lastError().driverText()).encode("latin-1") drv = str(self.cursor.lastError().driverText()).encode("latin-1")
db = unicode(self.cursor.lastError().databaseText()).encode("latin-1") db = str(self.cursor.lastError().databaseText()).encode("latin-1")
print "failed: %s %s" % (drv,db) print("failed: %s %s" % (drv,db))
self.copierer.writeFailed(record) self.copierer.writeFailed(record)
else: else:
self.copierer.writeSuccess(record,rowcount) self.copierer.writeSuccess(record,rowcount)
@ -158,9 +158,9 @@ class CopyCenterPlugin:
def initUpdate(self): def initUpdate(self):
self.write = self.writeUpdate self.write = self.writeUpdate
self.indexfieldname = str(self.widget.indexedit.text()).strip() self.indexfieldname = str(self.widget.indexedit.text()).strip()
if self.indexfieldname == "": raise "No index-field defined." if self.indexfieldname == "": raise Exception("No index-field defined.")
pkindex = self.cursor.index(self.indexfieldname) pkindex = self.cursor.index(self.indexfieldname)
if not pkindex: raise "Invalid index-field defined." if not pkindex: raise Exception("Invalid index-field defined.")
self.cursor.setPrimaryIndex(pkindex) self.cursor.setPrimaryIndex(pkindex)
#self.cursor.setMode( qtsql.TQSqlCursor.Insert | qtsql.TQSqlCursor.Update ) #self.cursor.setMode( qtsql.TQSqlCursor.Insert | qtsql.TQSqlCursor.Update )
self.copierer.appendProgressMessage("Update SQL: %s" % str(self.cursor.executedQuery())) self.copierer.appendProgressMessage("Update SQL: %s" % str(self.cursor.executedQuery()))
@ -173,13 +173,13 @@ class CopyCenterPlugin:
indexvalue = record[idx] indexvalue = record[idx]
except: except:
import traceback import traceback
print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
raise "Failed to determinate the value for the primary key." raise Exception("Failed to determinate the value for the primary key.")
# select cursor and go to matching record. # select cursor and go to matching record.
wherestatement = "%s = \"%s\"" % (self.indexfieldname, indexvalue) wherestatement = "%s = \"%s\"" % (self.indexfieldname, indexvalue)
if not self.cursor.select(wherestatement): if not self.cursor.select(wherestatement):
raise "Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ) raise Exception("Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ))
if not self.cursor.next(): if not next(self.cursor):
#print "No such record to update !" #print "No such record to update !"
return False return False
# Prepare updating the record. # Prepare updating the record.
@ -202,7 +202,7 @@ class CopyCenterPlugin:
self.copierer.writeFailed(record) self.copierer.writeFailed(record)
else: else:
self.copierer.writeSuccess(record,rowcount) self.copierer.writeSuccess(record,rowcount)
print "updated record (rowcount %s): %s" % (rowcount,record) print("updated record (rowcount %s): %s" % (rowcount,record))
return True return True
def __init__(self, copycenter): def __init__(self, copycenter):
@ -441,21 +441,21 @@ class CopyCenterPlugin:
if optionname == 'indexfield': return str(self.indexedit.text()) if optionname == 'indexfield': return str(self.indexedit.text())
except: except:
import traceback import traceback
print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
return "" return ""
def connectClicked(self): def connectClicked(self):
if self.plugin.database != None and self.plugin.database.isOpen(): if self.plugin.database != None and self.plugin.database.isOpen():
print "already connected. not needed to reconnect..." print("already connected. not needed to reconnect...")
self.updateConnectState() self.updateConnectState()
return True return True
print "trying to connect..." print("trying to connect...")
from TQt import qtsql from TQt import qtsql
drivername = str(self.driveredit.currentText()) drivername = str(self.driveredit.currentText())
print "drivername: %s" % drivername print("drivername: %s" % drivername)
connectionname = "CopyCenter%s" % self.plugin.plugintype connectionname = "CopyCenter%s" % self.plugin.plugintype
print "connectionname: %s" % connectionname print("connectionname: %s" % connectionname)
self.plugin.database = qtsql.TQSqlDatabase.addDatabase(drivername,connectionname) self.plugin.database = qtsql.TQSqlDatabase.addDatabase(drivername,connectionname)
if not self.plugin.database: if not self.plugin.database:
qt.TQMessageBox.critical(self,"Failed to connect","<qt>Failed to create database for driver \"%s\"</qt>" % drivername) qt.TQMessageBox.critical(self,"Failed to connect","<qt>Failed to create database for driver \"%s\"</qt>" % drivername)
@ -479,16 +479,16 @@ class CopyCenterPlugin:
if not self.plugin.database.open(): if not self.plugin.database.open():
qt.TQMessageBox.critical(self,"Failed to connect","<qt>%s<br><br>%s</qt>" % (self.plugin.database.lastError().driverText(),self.plugin.database.lastError().databaseText())) qt.TQMessageBox.critical(self,"Failed to connect","<qt>%s<br><br>%s</qt>" % (self.plugin.database.lastError().driverText(),self.plugin.database.lastError().databaseText()))
return False return False
print "database is opened now!" print("database is opened now!")
self.updateConnectState() self.updateConnectState()
return True return True
def disconnectClicked(self): def disconnectClicked(self):
print "trying to disconnect..." print("trying to disconnect...")
if self.plugin.database: if self.plugin.database:
self.plugin.database.close() self.plugin.database.close()
self.plugin.database = None self.plugin.database = None
print "database is closed now!" print("database is closed now!")
self.updateConnectState() self.updateConnectState()
plugin.widget = MainWidget(plugin,self.dialog,parent) plugin.widget = MainWidget(plugin,self.dialog,parent)

@ -19,7 +19,7 @@ class Datasource:
try: try:
self.connection = keximainwindow.getConnection() self.connection = keximainwindow.getConnection()
except: except:
raise "No connection established. Please open a project before." raise Exception("No connection established. Please open a project before.")
self.schema = None self.schema = None
@ -65,9 +65,9 @@ class Datasource:
if not self.cursor: if not self.cursor:
self.cursor = self.connection.executeQuerySchema( self.queryschema ) self.cursor = self.connection.executeQuerySchema( self.queryschema )
if not self.cursor: if not self.cursor:
raise "Failed to execute queryschema." raise Exception("Failed to execute queryschema.")
if not self.cursor.moveFirst(): if not self.cursor.moveFirst():
raise "Failed to move cursor to first record." raise Exception("Failed to move cursor to first record.")
if self.cursor.eof(): if self.cursor.eof():
self.cursor = None self.cursor = None
return None return None
@ -131,7 +131,7 @@ class HtmlExporter:
if items == None: break if items == None: break
output.write("<tr>") output.write("<tr>")
for item in items: for item in items:
u = unicode(str(self.htmlescape(item)),"latin-1") u = str(str(self.htmlescape(item)),"latin-1")
output.write("<td>%s</td>" % u.encode("utf-8")) output.write("<td>%s</td>" % u.encode("utf-8"))
output.write("</tr>\n") output.write("</tr>\n")
output.write("</table>\n") output.write("</table>\n")
@ -144,7 +144,7 @@ class GuiApp:
try: try:
import gui import gui
except: except:
raise "Import of the Kross GUI module failed." raise Exception("Import of the Kross GUI module failed.")
self.dialog = gui.Dialog("Export XHTML") self.dialog = gui.Dialog("Export XHTML")
self.dialog.addLabel(self.dialog, "Export a table- or query-datasource to a XHTML-file.") self.dialog.addLabel(self.dialog, "Export a table- or query-datasource to a XHTML-file.")
@ -176,10 +176,10 @@ class GuiApp:
def doExport(self): def doExport(self):
file = str( self.file.get() ) file = str( self.file.get() )
query = str( self.datasourcelist.get() ) query = str( self.datasourcelist.get() )
print "Exporting '%s' to file '%s' ..." % (query,file) print("Exporting '%s' to file '%s' ..." % (query,file))
if not self.datasource.setSource(query): if not self.datasource.setSource(query):
raise "Invalid datasource selected." raise Exceptin("Invalid datasource selected.")
#return #return
style = str( self.stylelist.get() ) style = str( self.stylelist.get() )
@ -190,7 +190,7 @@ class GuiApp:
exporter.write(f, style) exporter.write(f, style)
f.close() f.close()
print "Successfully exported '%s' to file %s" % (query,file) print("Successfully exported '%s' to file %s" % (query,file))
self.dialog.close() self.dialog.close()
GuiApp( Datasource() ) GuiApp( Datasource() )

@ -28,7 +28,7 @@ class SaxInput:
import xml.sax.saxlib import xml.sax.saxlib
import xml.sax.saxexts import xml.sax.saxexts
except: except:
raise "Import of the python xml.sax.saxlib module failed. This module is needed by the ImportXHTML python script." raise Exception("Import of the python xml.sax.saxlib module failed. This module is needed by the ImportXHTML python script.")
def read(self, outputwriter): def read(self, outputwriter):
""" Start reading and parsing the XML-file. """ """ Start reading and parsing the XML-file. """
@ -83,7 +83,7 @@ class SaxInput:
# Print some debugging-output to stdout. # Print some debugging-output to stdout.
for idx in range(self.level): sys.stdout.write(' ') for idx in range(self.level): sys.stdout.write(' ')
sys.stdout.write('Element: %s' % name) sys.stdout.write('Element: %s' % name)
for attrName in attrs.keys(): for attrName in list(attrs.keys()):
sys.stdout.write(' %s="%s"' % (attrName,attrs.get(attrName))) sys.stdout.write(' %s="%s"' % (attrName,attrs.get(attrName)))
sys.stdout.write('\n') sys.stdout.write('\n')
@ -110,12 +110,12 @@ class SaxInput:
self.field = None self.field = None
elif name == "td" and (self.level == len(self.tablebase) + 1): elif name == "td" and (self.level == len(self.tablebase) + 1):
#if self.field == None: #if self.field == None:
# raise "Unexpected closing </td>" # raise Exception("Unexpected closing </td>")
self.record.setField( self.field ) self.record.setField( self.field )
self.field = None self.field = None
elif name == "th" and (self.level == len(self.tablebase) + 1): elif name == "th" and (self.level == len(self.tablebase) + 1):
#if self.field == None: #if self.field == None:
# raise "Unexpected closing </td>" # raise Exceptin("Unexpected closing </td>")
self.record.setHeader( self.field ) self.record.setHeader( self.field )
self.field = None self.field = None
@ -126,7 +126,7 @@ class SaxInput:
if self.field != None: if self.field != None:
# the xml-data is unicode and we need to encode it # the xml-data is unicode and we need to encode it
# to latin-1 cause KexiDB deals only with latin-1. # to latin-1 cause KexiDB deals only with latin-1.
u = unicode(chars[offset:offset+length]) u = str(chars[offset:offset+length])
self.field.append(u.encode("latin-1")) self.field.append(u.encode("latin-1"))
# start the job # start the job
@ -163,14 +163,14 @@ class KexiDBOutput:
def success(self, record): def success(self, record):
""" Called if a record was written successfully. """ """ Called if a record was written successfully. """
print "SUCCESS: %s" % str(record) print("SUCCESS: %s" % str(record))
self.successcount += 1 self.successcount += 1
if hasattr(self.outputwriter,"logfile"): if hasattr(self.outputwriter,"logfile"):
self.addLog(record, "Success") self.addLog(record, "Success")
def failed(self, record): def failed(self, record):
""" Called if we failed to write a record. """ """ Called if we failed to write a record. """
print "FAILED: %s" % str(record) print("FAILED: %s" % str(record))
self.failedcount += 1 self.failedcount += 1
if hasattr(self.outputwriter,"logfile"): if hasattr(self.outputwriter,"logfile"):
self.addLog(record, "Failed") self.addLog(record, "Failed")
@ -207,7 +207,7 @@ class KexiDBOutput:
try: try:
self.connection = keximainwindow.getConnection() self.connection = keximainwindow.getConnection()
except: except:
raise "No connection established. Please open a project before." raise Exception("No connection established. Please open a project before.")
self.fieldlist = None self.fieldlist = None
self.headerrecord = None self.headerrecord = None
@ -215,9 +215,9 @@ class KexiDBOutput:
def begin(self): def begin(self):
""" Called before parsing starts. """ """ Called before parsing starts. """
print "START JOB" print("START JOB")
if self.fieldlist == None: if self.fieldlist == None:
raise "Invalid tableschema or fieldlist!" raise Exceptin("Invalid tableschema or fieldlist!")
global KexiDBOutput global KexiDBOutput
self.result = KexiDBOutput.Result(self) self.result = KexiDBOutput.Result(self)
if hasattr(self,"logfilename") and self.logfilename != None and self.logfilename != "": if hasattr(self,"logfilename") and self.logfilename != None and self.logfilename != "":
@ -225,7 +225,7 @@ class KexiDBOutput:
def end(self): def end(self):
""" Called if parsing is fineshed. """ """ Called if parsing is fineshed. """
print "END JOB" print("END JOB")
self.logfile = None self.logfile = None
self.mapping = {} self.mapping = {}
#self.headerrecord = None #self.headerrecord = None
@ -240,12 +240,12 @@ class KexiDBOutput:
""" Set the tablename we like to import the data to. """ """ Set the tablename we like to import the data to. """
tableschema = self.connection.tableSchema(tablename) tableschema = self.connection.tableSchema(tablename)
if tableschema == None: if tableschema == None:
raise "There exists no table with the name '%s'!" % tablename raise Exceptin("There exists no table with the name '%s'!" % tablename)
self.fieldlist = tableschema.fieldlist() self.fieldlist = tableschema.fieldlist()
fields = self.fieldlist.fields() fields = self.fieldlist.fields()
for field in fields: for field in fields:
print "KexiDBOutput.setTable(%s): %s(%s)" % (tablename,field.name(),field.type()) print("KexiDBOutput.setTable(%s): %s(%s)" % (tablename,field.name(),field.type()))
print "names=%s" % self.fieldlist.names() print("names=%s" % self.fieldlist.names())
def setMapping(self, mapping): def setMapping(self, mapping):
""" Set the tablefieldname=xmlcolnr dictonary we should map the data to. """ """ Set the tablefieldname=xmlcolnr dictonary we should map the data to. """
@ -277,7 +277,7 @@ class KexiDBOutput:
values = [] values = []
for k in self.fieldlist.names(): for k in self.fieldlist.names():
values.append( str(record.fields[ int(self.mapping[k]) ]) ) values.append( str(record.fields[ int(self.mapping[k]) ]) )
print "Import values: %s" % values print("Import values: %s" % values)
try: try:
if self.connection.insertRecord(self.fieldlist, values): if self.connection.insertRecord(self.fieldlist, values):
@ -343,7 +343,7 @@ class GuiApp:
msgbox.show() msgbox.show()
self.doCancel() self.doCancel()
except RuntimeError, e: except RuntimeError as e:
pass pass
#except Exception, e: #except Exception, e:
# import traceback # import traceback
@ -392,7 +392,7 @@ class GuiApp:
i += 1 i += 1
if not field.isAutoInc(): if not field.isAutoInc():
l.set(i) l.set(i)
except ValueError, e: except ValueError as e:
if not field.type() in ("Integer","BigInteger","ShortInteger","Float","Double"): if not field.type() in ("Integer","BigInteger","ShortInteger","Float","Double"):
i += 1 i += 1
l.set(i) l.set(i)
@ -411,7 +411,7 @@ class GuiApp:
fieldname = field.name() fieldname = field.name()
colnr = str( l.get() ).split(":",1)[0] colnr = str( l.get() ).split(":",1)[0]
if colnr.isdigit(): if colnr.isdigit():
print "Table field '%s' is mapped to XML column '%s'" % (fieldname,colnr) print("Table field '%s' is mapped to XML column '%s'" % (fieldname,colnr))
mapping[ fieldname ] = colnr mapping[ fieldname ] = colnr
self.outputwriter.setMapping(mapping) self.outputwriter.setMapping(mapping)
self.ok = True self.ok = True

@ -20,7 +20,7 @@ class DataProvider:
try: try:
self.connection = keximainwindow.getConnection() self.connection = keximainwindow.getConnection()
except: except:
raise "No connection established. Please open the project to be documented first." raise Exception("No connection established. Please open the project to be documented first.")
def printConnection(self): def printConnection(self):
condata = self.connection.data() condata = self.connection.data()
@ -96,7 +96,7 @@ class GuiApp:
try: try:
import gui import gui
except: except:
raise "Import of the Kross GUI module failed." raise Exception("Import of the Kross GUI module failed.")
self.dialog = gui.Dialog("Project Documentor") self.dialog = gui.Dialog("Project Documentor")
@ -130,7 +130,7 @@ class GuiApp:
def toHTML(self, value): def toHTML(self, value):
import types import types
result = "" result = ""
if isinstance(value, types.TupleType): if isinstance(value, tuple):
result += "<ul>" result += "<ul>"
if len(value) == 1: if len(value) == 1:
result += "<li>%s</li>" % value result += "<li>%s</li>" % value
@ -142,7 +142,7 @@ class GuiApp:
if i != "": if i != "":
result += "<li>%s</li>" % i result += "<li>%s</li>" % i
result += "</ul>" result += "</ul>"
elif isinstance(value, types.ListType): elif isinstance(value, list):
for item in value: for item in value:
result += "%s" % self.toHTML(item) result += "%s" % self.toHTML(item)
else: else:
@ -151,7 +151,7 @@ class GuiApp:
def doSave(self): def doSave(self):
file = str( self.file.get() ) file = str( self.file.get() )
print "Attempting to save project documentation to file: %s" % file print("Attempting to save project documentation to file: %s" % file)
f = open(file, "w") f = open(file, "w")
@ -167,19 +167,19 @@ class GuiApp:
for d in dir(self.dataprovider): for d in dir(self.dataprovider):
if d.startswith("print"): if d.startswith("print"):
print "GuiApp.doSave() CHECK %s" % d print("GuiApp.doSave() CHECK %s" % d)
a = self.printCheckBoxes[d] a = self.printCheckBoxes[d]
if a and a.isChecked(): if a and a.isChecked():
print "GuiApp.doSave() BEGIN %s" % d print("GuiApp.doSave() BEGIN %s" % d)
value = getattr(self.dataprovider,d)() value = getattr(self.dataprovider,d)()
if value != None and len(value) > 0: if value != None and len(value) > 0:
f.write("<h2>%s</h2>" % d[5:]) f.write("<h2>%s</h2>" % d[5:])
f.write( self.toHTML(value) ) f.write( self.toHTML(value) )
print "GuiApp.doSave() END %s" % d print("GuiApp.doSave() END %s" % d)
f.close() f.close()
print "Successfully saved project documentation to file: %s" % file print("Successfully saved project documentation to file: %s" % file)
self.dialog.close() self.dialog.close()
GuiApp( DataProvider() ) GuiApp( DataProvider() )

@ -14,7 +14,7 @@ Dual-licensed under LGPL v2+higher and the BSD license.
try: try:
import krosskexiapp import krosskexiapp
except ImportError, e: except ImportError as e:
raise "Import of the Kross KexiApp module failed.\n%s" % e raise "Import of the Kross KexiApp module failed.\n%s" % e
def get(modulename): def get(modulename):

@ -18,7 +18,7 @@ import os, sys
try: try:
from TQt import qt from TQt import qt
except (ImportError): except (ImportError):
raise "Failed to import the required PyTQt python module." raise Exception("Failed to import the required PyTQt python module.")
class Dialog(tqt.QDialog): class Dialog(tqt.QDialog):
def __init__(self, scriptpath, parent): def __init__(self, scriptpath, parent):
@ -69,7 +69,7 @@ class Dialog(tqt.QDialog):
stylebox.setSpacing(6) stylebox.setSpacing(6)
stylelabel = qt.TQLabel("Style:",stylebox) stylelabel = qt.TQLabel("Style:",stylebox)
self.stylecombo = qt.TQComboBox(stylebox) self.stylecombo = qt.TQComboBox(stylebox)
stylenames = self.styles.keys() stylenames = list(self.styles.keys())
stylenames.sort() stylenames.sort()
for stylename in stylenames: for stylename in stylenames:
self.stylecombo.insertItem(stylename) self.stylecombo.insertItem(stylename)
@ -123,12 +123,13 @@ class Dialog(tqt.QDialog):
sheetname = str( self.sheetcombo.currentText() ) sheetname = str( self.sheetcombo.currentText() )
sheet = self.doc.sheetByName( sheetname ) sheet = self.doc.sheetByName( sheetname )
print "sheetname=%s sheet=%s" % (sheetname,sheet) print("sheetname=%s sheet=%s" % (sheetname,sheet))
filename = str( self.fileedit.text() ) filename = str( self.fileedit.text() )
try: try:
file = open(filename, "w") file = open(filename, "w")
except IOError, (errno, strerror): except IOError as xxx_todo_changeme:
(errno, strerror) = xxx_todo_changeme.args
qt.TQMessageBox.critical(self,"Error","<qt>Failed to create HTML file \"%s\"<br><br>%s</qt>" % (filename,strerror)) qt.TQMessageBox.critical(self,"Error","<qt>Failed to create HTML file \"%s\"<br><br>%s</qt>" % (filename,strerror))
return return

@ -16,7 +16,7 @@ import os, sys
try: try:
from TQt import qt from TQt import qt
except (ImportError): except (ImportError):
raise "Failed to import the required PyTQt python module." raise Exception("Failed to import the required PyTQt python module.")
#################################################################################### ####################################################################################
# Samples. # Samples.
@ -113,13 +113,13 @@ class Samples:
return ( return (
'import krosskexidb', 'import krosskexidb',
'drivermanager = krosskexidb.DriverManager()', 'drivermanager = krosskexidb.DriverManager()',
'print "drivernames: %s" % drivermanager.driverNames()', 'print("drivernames: %s" % drivermanager.driverNames())',
'', '',
'driver = drivermanager.driver( \"{DriverName}\" )', 'driver = drivermanager.driver( \"{DriverName}\" )',
'print "driver: {DriverName}"', 'print("driver: {DriverName}")',
'print "version=%s.%s" % (driver.versionMajor(),driver.versionMinor())', 'print("version=%s.%s" % (driver.versionMajor(),driver.versionMinor())ú',
'print "mimetype=%s" % driver.fileDBDriverMimeType()', 'print("mimetype=%s" % driver.fileDBDriverMimeType()ú',
'print "filedriver=%s" % driver.isFileDriver()', 'print("filedriver=%s" % driver.isFileDriver())',
) )
class ConnectWithFile: class ConnectWithFile:
@ -137,7 +137,7 @@ class Samples:
'', '',
'# Get the connectiondata from the project file.', '# Get the connectiondata from the project file.',
'connectiondata = drivermanager.createConnectionDataByFile( "{ProjectFile}" )', 'connectiondata = drivermanager.createConnectionDataByFile( "{ProjectFile}" )',
'print "Connectiondata: %s" % connectiondata.serverInfoString()', 'print("Connectiondata: %s" % connectiondata.serverInfoString())',
'', '',
'# Create the driver for the database backend.', '# Create the driver for the database backend.',
'driver = drivermanager.driver( connectiondata.driverName() )', 'driver = drivermanager.driver( connectiondata.driverName() )',
@ -146,19 +146,19 @@ class Samples:
'connection = driver.createConnection(connectiondata)', 'connection = driver.createConnection(connectiondata)',
'if not connection.isConnected():', 'if not connection.isConnected():',
' if not connection.connect():', ' if not connection.connect():',
' raise "Failed to connect"', ' raise Exception("Failed to connect")',
'', '',
'# Open the database for usage.', '# Open the database for usage.',
'print "Databases: %s" % connection.databaseNames()', 'print("Databases: %s" % connection.databaseNames())',
'if not connection.isDatabaseUsed():', 'if not connection.isDatabaseUsed():',
' if not connection.useDatabase( connectiondata.databaseName() ):', ' if not connection.useDatabase( connectiondata.databaseName() ):',
' if not connection.useDatabase( connectiondata.fileName() ):', ' if not connection.useDatabase( connectiondata.fileName() ):',
' raise "Failed to use database"', ' raise Exception("Failed to use database")',
'', '',
'# Print some infos.', '# Print some infos.',
'print "All tables: %s" % connection.allTableNames()', 'print("All tables: %s" % connection.allTableNames())',
'print "Tables: %s" % connection.tableNames()', 'print("Tables: %s" % connection.tableNames())',
'print "Queries: %s" % connection.queryNames()', 'print("Queries: %s" % connection.queryNames())',
) )
class IterateThroughTable: class IterateThroughTable:
@ -177,7 +177,7 @@ class Samples:
'', '',
'# Get the connectiondata from the project file.', '# Get the connectiondata from the project file.',
'connectiondata = drivermanager.createConnectionDataByFile( "{ProjectFile}" )', 'connectiondata = drivermanager.createConnectionDataByFile( "{ProjectFile}" )',
'print "Connectiondata: %s" % connectiondata.serverInfoString()', 'print("Connectiondata: %s" % connectiondata.serverInfoString())',
'', '',
'# Create the driver for the database backend.', '# Create the driver for the database backend.',
'driver = drivermanager.driver( connectiondata.driverName() )', 'driver = drivermanager.driver( connectiondata.driverName() )',
@ -186,13 +186,13 @@ class Samples:
'connection = driver.createConnection(connectiondata)', 'connection = driver.createConnection(connectiondata)',
'if not connection.isConnected():', 'if not connection.isConnected():',
' if not connection.connect():', ' if not connection.connect():',
' raise "Failed to connect"', ' raise Exception("Failed to connect")',
'', '',
'# Open the database for usage.', '# Open the database for usage.',
'if not connection.isDatabaseUsed():', 'if not connection.isDatabaseUsed():',
' if not connection.useDatabase( connectiondata.databaseName() ):', ' if not connection.useDatabase( connectiondata.databaseName() ):',
' if not connection.useDatabase( connectiondata.fileName() ):', ' if not connection.useDatabase( connectiondata.fileName() ):',
' raise "Failed to use database"', ' raise Exception("Failed to use database")',
'', '',
'# Get the table and create a query for it.', '# Get the table and create a query for it.',
'table = connection.tableSchema( \"{TableName}\" )', 'table = connection.tableSchema( \"{TableName}\" )',
@ -201,14 +201,14 @@ class Samples:
'# Create a cursor to walk through the records.', '# Create a cursor to walk through the records.',
'cursor = connection.executeQuerySchema( query )', 'cursor = connection.executeQuerySchema( query )',
'if not cursor:', 'if not cursor:',
' raise "Failed to create cursor."', ' raise Exception("Failed to create cursor.")',
'', '',
'# Iterate through the records.', '# Iterate through the records.',
'if not cursor.moveFirst():', 'if not cursor.moveFirst():',
' raise "The cursor has no records to read from."', ' raise Exception("The cursor has no records to read from.")',
'while not cursor.eof():', 'while not cursor.eof():',
' for i in range( cursor.fieldCount() ):', ' for i in range( cursor.fieldCount() ):',
' print "%s" % cursor.value(i)', ' print("%s" % cursor.value(i))',
' cursor.moveNext()', ' cursor.moveNext()',
) )
@ -232,7 +232,7 @@ class Samples:
except: except:
import traceback import traceback
trace = "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) trace = "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
print trace print(trace)
class _CellsWidget(ListWidget): class _CellsWidget(ListWidget):
def __init__(self, parentwidget): def __init__(self, parentwidget):
@ -279,13 +279,13 @@ class Samples:
'# Get the sheet defined by the sheetname.', '# Get the sheet defined by the sheetname.',
'sheet = document.sheetByName( \"{SheetName}\" )', 'sheet = document.sheetByName( \"{SheetName}\" )',
'if not sheet:', 'if not sheet:',
' raise "No such sheet {SheetName} %s" % document.sheetNames()', ' raise Exception("No such sheet {SheetName} %s" % document.sheetNames())',
'', '',
'( (col1,row1),(col2,row2) ) = {Cells}', '( (col1,row1),(col2,row2) ) = {Cells}',
'for c in range(col1,col2):', 'for c in range(col1,col2):',
' for r in range(row1,row2):', ' for r in range(row1,row2):',
' cell = sheet.cell(c,r)', ' cell = sheet.cell(c,r)',
' print "cell c=%s r=%s v=%s" % (c,r,cell.value())', ' print("cell c=%s r=%s v=%s" % (c,r,cell.value()))',
' cell.setText( \"{Value}\" )', ' cell.setText( \"{Value}\" )',
) )
@ -311,7 +311,7 @@ class Samples:
'# Get the sheet defined by the sheetname.', '# Get the sheet defined by the sheetname.',
'sheet = document.sheetByName( \"{SheetName}\" )', 'sheet = document.sheetByName( \"{SheetName}\" )',
'if not sheet:', 'if not sheet:',
' raise "No such sheet {SheetName} %s" % document.sheetNames()', ' raise Exception("No such sheet {SheetName} %s" % document.sheetNames())',
'', '',
'( (col1,row1),(col2,row2) ) = {Cells}', '( (col1,row1),(col2,row2) ) = {Cells}',
'for c in range(col1,col2):', 'for c in range(col1,col2):',
@ -340,12 +340,12 @@ class Samples:
'# Get the sheet defined by the sheetname.', '# Get the sheet defined by the sheetname.',
'sheet = document.sheetByName( \"{SheetName}\" )', 'sheet = document.sheetByName( \"{SheetName}\" )',
'if not sheet:', 'if not sheet:',
' raise "No such sheet {SheetName} %s" % document.sheetNames()', ' raise Exception("No such sheet {SheetName} %s" % document.sheetNames())',
'', '',
'# Iterate through the cells that have content (aka that are not empty).', '# Iterate through the cells that have content (aka that are not empty).',
'cell = sheet.firstCell()', 'cell = sheet.firstCell()',
'while cell:', 'while cell:',
' print "col=%s row=%s value=%s" % (cell.column(),cell.row(),cell.value())', ' print("col=%s row=%s value=%s" % (cell.column(),cell.row(),cell.value()))',
' cell = cell.nextCell()', ' cell = cell.nextCell()',
) )
@ -367,10 +367,10 @@ class Samples:
'# Get the sheet defined by the sheetname.', '# Get the sheet defined by the sheetname.',
'sheet = document.sheetByName( \"{SheetName}\" )', 'sheet = document.sheetByName( \"{SheetName}\" )',
'if not sheet:', 'if not sheet:',
' raise "No such sheet {SheetName} %s" % document.sheetNames()', ' raise Exception("No such sheet {SheetName} %s" % document.sheetNames())',
'', '',
'print "name=%s" % sheet.name()', 'print("name=%s" % sheet.name())',
'print "maxcolumns=%s maxrows=%s" % (sheet.maxColumn(),sheet.maxRow())', 'print("maxcolumns=%s maxrows=%s" % (sheet.maxColumn(),sheet.maxRow()))',
) )
class LoadDocFromNativeXML: class LoadDocFromNativeXML:
@ -464,10 +464,10 @@ class Samples:
'document = krosskspreadcore.get("KSpreadDocument")', 'document = krosskspreadcore.get("KSpreadDocument")',
'# Get the source sheet.', '# Get the source sheet.',
'fromsheet = document.sheetByName( "{SourceSheet}" )', 'fromsheet = document.sheetByName( "{SourceSheet}" )',
'if not fromsheet: raise "No such sheet {SourceSheet} %s" % document.sheetNames()', 'if not fromsheet: raise Exception("No such sheet {SourceSheet} %s" % document.sheetNames())',
'# Get the target sheet.', '# Get the target sheet.',
'tosheet = document.sheetByName( "{TargetSheet}" )', 'tosheet = document.sheetByName( "{TargetSheet}" )',
'if not fromsheet: raise "No such sheet {TargetSheet} %s" % document.sheetNames()', 'if not fromsheet: raise Exception("No such sheet {TargetSheet} %s" % document.sheetNames())',
'# Copy the cells.', '# Copy the cells.',
'fromcell = fromsheet.firstCell()', 'fromcell = fromsheet.firstCell()',
'while fromcell:', 'while fromcell:',
@ -492,13 +492,13 @@ class Samples:
'# Get the current document and the sheet.', '# Get the current document and the sheet.',
'document = krosskspreadcore.get("KSpreadDocument")', 'document = krosskspreadcore.get("KSpreadDocument")',
'sheet = document.sheetByName( "{Sheet}" )', 'sheet = document.sheetByName( "{Sheet}" )',
'if not sheet: raise "No such sheet {Sheet} %s" % document.sheetNames()', 'if not sheet: raise Exception("No such sheet {Sheet} %s" % document.sheetNames())',
'', '',
'filename = "{FileName}"', 'filename = "{FileName}"',
'try:', 'try:',
' file = open(filename, "r")', ' file = open(filename, "r")',
'except IOError:', 'except IOError:',
' raise "Failed to open CSV File: %s" % filename', ' raise Exception("Failed to open CSV File: %s" % filename)',
'', '',
'import csv', 'import csv',
'csvparser = csv.reader(file)', 'csvparser = csv.reader(file)',
@ -530,7 +530,7 @@ class Samples:
'try:', 'try:',
' file = open(filename, "w")', ' file = open(filename, "w")',
'except IOError:', 'except IOError:',
' raise "Failed to write CSV File: %s" % filename', ' raise Exception("Failed to write CSV File: %s" % filename)',
'# Prepare CSV-writer', '# Prepare CSV-writer',
'import csv', 'import csv',
'csvwriter = csv.writer(file)', 'csvwriter = csv.writer(file)',
@ -539,7 +539,7 @@ class Samples:
'# Get the current document and the sheet.', '# Get the current document and the sheet.',
'document = krosskspreadcore.get("KSpreadDocument")', 'document = krosskspreadcore.get("KSpreadDocument")',
'sheet = document.sheetByName( "{Sheet}" )', 'sheet = document.sheetByName( "{Sheet}" )',
'if not sheet: raise "No such sheet {Sheet} %s" % document.sheetNames()', 'if not sheet: raise Exception("No such sheet {Sheet} %s" % document.sheetNames())',
'# Iterate over the cells.', '# Iterate over the cells.',
'cell = sheet.firstCell()', 'cell = sheet.firstCell()',
'record = []', 'record = []',
@ -572,7 +572,7 @@ class Samples:
return ( return (
'from TQt import qt', 'from TQt import qt',
'openfilename = qt.TQFileDialog.getOpenFileName("{FileName}","*.txt *.html;;*", self)', 'openfilename = qt.TQFileDialog.getOpenFileName("{FileName}","*.txt *.html;;*", self)',
'print "openfile=%s" % openfilename', 'print("openfile=%s" % openfilename)',
) )
class SaveFileDialog: class SaveFileDialog:
@ -587,7 +587,7 @@ class Samples:
return ( return (
'from TQt import qt', 'from TQt import qt',
'savefilename = qt.TQFileDialog.getSaveFileName("{FileName}","*.txt *.html;;*", self)', 'savefilename = qt.TQFileDialog.getSaveFileName("{FileName}","*.txt *.html;;*", self)',
'print "savefile=%s" % savefilename', 'print("savefile=%s" % savefilename)',
) )
class CustomDialog: class CustomDialog:
@ -631,9 +631,9 @@ class Samples:
'', '',
'text, ok = qt.TQInputDialog.getText("{Caption}", "{Message}", qt.TQLineEdit.Normal, "")', 'text, ok = qt.TQInputDialog.getText("{Caption}", "{Message}", qt.TQLineEdit.Normal, "")',
'if ok:', 'if ok:',
' print "Text defined: %s" % text', ' print("Text defined: %s" % text)',
'else:', 'else:',
' print "Dialog aborted."', ' print("Dialog aborted.")',
) )
#################################################################################### ####################################################################################
@ -658,7 +658,7 @@ class Samples:
'd = dcopext.DCOPApp(apps[0], dcopclient)', 'd = dcopext.DCOPApp(apps[0], dcopclient)',
'result,typename,data = d.appclient.call(apps[0],"klipper","getClipboardContents()","")', 'result,typename,data = d.appclient.call(apps[0],"klipper","getClipboardContents()","")',
'ds = qt.TQDataStream(data, qt.IO_ReadOnly)', 'ds = qt.TQDataStream(data, qt.IO_ReadOnly)',
'print "Clipboard content:\\n%s" % tdecore.dcop_next(ds, TQSTRING_OBJECT_NAME_STRING)', 'print("Clipboard content:\\n%s" % tdecore.dcop_next(ds, TQSTRING_OBJECT_NAME_STRING))',
) )
class AmarokCollectionInfos: class AmarokCollectionInfos:
@ -685,7 +685,7 @@ class Samples:
'', '',
'for funcname in ["totalAlbums","totalArtists","totalCompilations","totalGenres","totalTracks"]:', 'for funcname in ["totalAlbums","totalArtists","totalCompilations","totalGenres","totalTracks"]:',
' result,replytype,replydata = d.appclient.call("amarok", "collection", "%s()" % funcname,"")', ' result,replytype,replydata = d.appclient.call("amarok", "collection", "%s()" % funcname,"")',
' print "%s: %s" % ( funcname, dataToList(replydata,["int"])[0] )', ' print("%s: %s" % ( funcname, dataToList(replydata,["int"])[0] ))',
) )
class KopeteContacts: class KopeteContacts:
@ -705,11 +705,11 @@ class Samples:
'd = dcopext.DCOPApp(app, dcopclient)', 'd = dcopext.DCOPApp(app, dcopclient)',
'', '',
'(state,rtype,rdata) = d.appclient.call("kopete", "KopeteIface", "contacts()","")', '(state,rtype,rdata) = d.appclient.call("kopete", "KopeteIface", "contacts()","")',
'if not state: raise "Failed to call the kopete contacts-function"', 'if not state: raise Exception("Failed to call the kopete contacts-function")',
'', '',
'ds = qt.TQDataStream(rdata.data(), qt.IO_ReadOnly)', 'ds = qt.TQDataStream(rdata.data(), qt.IO_ReadOnly)',
'sl = tdecore.dcop_next (ds, TQSTRINGLIST_OBJECT_NAME_STRING)', 'sl = tdecore.dcop_next (ds, TQSTRINGLIST_OBJECT_NAME_STRING)',
'print "contacts=%s" % [ str(s) for s in sl ]', 'print("contacts=%s" % [ str(s) for s in sl ])',
) )
class KWordSelectedText: class KWordSelectedText:
@ -740,26 +740,26 @@ class Samples:
'# Get the KWord DCOP client.', '# Get the KWord DCOP client.',
'dcopclient = tdecore.TDEApplication.dcopClient()', 'dcopclient = tdecore.TDEApplication.dcopClient()',
'apps = [ app for app in dcopclient.registeredApplications() if str(app).startswith("kword") ]', 'apps = [ app for app in dcopclient.registeredApplications() if str(app).startswith("kword") ]',
'if len(apps) < 1: raise "No KWord instance is running. Please start KWord before!"', 'if len(apps) < 1: raise Exception("No KWord instance is running. Please start KWord before!")',
'appname = apps[0]', 'appname = apps[0]',
'd = dcopext.DCOPApp(appname, dcopclient)', 'd = dcopext.DCOPApp(appname, dcopclient)',
'', '',
'# Call the getDocuments() function.', '# Call the getDocuments() function.',
'(state,rtype,rdata) = d.appclient.call(appname, "KoApplicationIface", "getDocuments()","")', '(state,rtype,rdata) = d.appclient.call(appname, "KoApplicationIface", "getDocuments()","")',
'if not state: raise "%s: Failed to call getDocuments-function" % appname', 'if not state: raise Exception("%s: Failed to call getDocuments-function" % appname)',
'documents = dataToList(rdata,["QValueList<DCOPRef>"])[0]', 'documents = dataToList(rdata,["QValueList<DCOPRef>"])[0]',
'print "documents=%s" % [ str( doc.obj() ) for doc in documents ]', 'print("documents=%s" % [ str( doc.obj() ) for doc in documents ])',
'document = documents[0] # Let\'s just take the first document.', 'document = documents[0] # Let\'s just take the first document.',
'', '',
'# Get the frameset.', '# Get the frameset.',
'ba = listToData( [ ("int",0) ] )', 'ba = listToData( [ ("int",0) ] )',
'(state,rtype,rdata) = d.appclient.call(appname, document.obj(), "textFrameSet(int)", ba)', '(state,rtype,rdata) = d.appclient.call(appname, document.obj(), "textFrameSet(int)", ba)',
'if not state: raise "%s: Failed to call frameSet-function" % appname', 'if not state: raise Exception("%s: Failed to call frameSet-function" % appname)',
'frameset = dataToList( rdata,["DCOPRef"] )[0] # Let\'s just take the first textframe.', 'frameset = dataToList( rdata,["DCOPRef"] )[0] # Let\'s just take the first textframe.',
'', '',
'# Get the selected text.', '# Get the selected text.',
'(state,rtype,rdata) = d.appclient.call(appname, frameset.obj(), "selectedText()", "")', '(state,rtype,rdata) = d.appclient.call(appname, frameset.obj(), "selectedText()", "")',
'print "Selected Text: %s" % dataToList( rdata,[TQSTRING_OBJECT_NAME_STRING] )[0]', 'print("Selected Text: %s" % dataToList( rdata,[TQSTRING_OBJECT_NAME_STRING] )[0])',
) )
#################################################################################### ####################################################################################
@ -815,8 +815,8 @@ class SampleDialog(qt.TQDialog):
def getCode(self): def getCode(self):
if not hasattr(self,"code"): return None if not hasattr(self,"code"): return None
code = "\n".join( self.code ) code = "\n".join( self.code )
for widgetname in self.samplechild.widgets.keys(): for widgetname in list(self.samplechild.widgets.keys()):
print ".............. %s" % widgetname print(".............. %s" % widgetname)
widget = self.samplechild.widgets[widgetname] widget = self.samplechild.widgets[widgetname]
value = widget.value() value = widget.value()
if value != None: if value != None:
@ -991,9 +991,9 @@ class MainDialog(qt.TQDialog):
self.scripttext.append( code ) self.scripttext.append( code )
def execCode(self,function): def execCode(self,function):
import sys, StringIO import sys, io
codeOut = StringIO.StringIO() codeOut = io.StringIO()
codeErr = StringIO.StringIO() codeErr = io.StringIO()
sys.stdout = codeOut sys.stdout = codeOut
sys.stderr = codeErr sys.stderr = codeErr
@ -1009,7 +1009,7 @@ class MainDialog(qt.TQDialog):
while hasattr(tb,"tb_next") and tb.tb_next: while hasattr(tb,"tb_next") and tb.tb_next:
tb = tb.tb_next tb = tb.tb_next
lineno = tb.tb_lineno lineno = tb.tb_lineno
print "EXCEPTION: lineno=%s" % lineno print("EXCEPTION: lineno=%s" % lineno)
self.scripttext.setCursorPosition( lineno - 1, 0 ) self.scripttext.setCursorPosition( lineno - 1, 0 )
except: except:
pass pass
@ -1019,12 +1019,12 @@ class MainDialog(qt.TQDialog):
s = codeErr.getvalue() s = codeErr.getvalue()
if s: if s:
print "ERROR:\n%s\n" % s print("ERROR:\n%s\n" % s)
self.console.append(s) self.console.append(s)
s = codeOut.getvalue() s = codeOut.getvalue()
if s: if s:
print s print(s)
self.console.append(s) self.console.append(s)
codeOut.close() codeOut.close()
@ -1042,7 +1042,7 @@ class MainDialog(qt.TQDialog):
self.console.clear() self.console.clear()
def doexecute(self): def doexecute(self):
code = str( self.scripttext.text() ) code = str( self.scripttext.text() )
exec code in globals(), locals() exec(code, globals(), locals())
self.execCode(doexecute) self.execCode(doexecute)
self.console.append("<b>Execution done!</b>") self.console.append("<b>Execution done!</b>")
@ -1058,7 +1058,8 @@ class MainDialog(qt.TQDialog):
self.scripttext.setText( str( file.read() ) ) self.scripttext.setText( str( file.read() ) )
file.close() file.close()
__main__.scripteditorfilename = filename __main__.scripteditorfilename = filename
except IOError, (errno, strerror): except IOError as xxx_todo_changeme:
(errno, strerror) = xxx_todo_changeme.args
qt.TQMessageBox.critical(self,"Error","<qt>Failed to open script file \"%s\"<br><br>%s</qt>" % (filename,strerror)) qt.TQMessageBox.critical(self,"Error","<qt>Failed to open script file \"%s\"<br><br>%s</qt>" % (filename,strerror))
def openFileAs(self): def openFileAs(self):
@ -1073,7 +1074,8 @@ class MainDialog(qt.TQDialog):
file = open(__main__.scripteditorfilename, "w") file = open(__main__.scripteditorfilename, "w")
file.write( str( self.scripttext.text() ) ) file.write( str( self.scripttext.text() ) )
file.close() file.close()
except IOError, (errno, strerror): except IOError as xxx_todo_changeme1:
(errno, strerror) = xxx_todo_changeme1.args
qt.TQMessageBox.critical(self,"Error","<qt>Failed to open script file \"%s\"<br><br>%s</qt>" % (__main__.scripteditorfilename,strerror)) qt.TQMessageBox.critical(self,"Error","<qt>Failed to open script file \"%s\"<br><br>%s</qt>" % (__main__.scripteditorfilename,strerror))
def saveFileAs(self): def saveFileAs(self):

@ -16,14 +16,14 @@ class ContentGenerator(handler.ContentHandler):
def startElement(self, name, attrs): def startElement(self, name, attrs):
if name == 'unicodetable': if name == 'unicodetable':
self.font = None self.font = None
for (name, value) in attrs.items(): for (name, value) in list(attrs.items()):
if name == "font" and value: if name == "font" and value:
self.font = value self.font = value
if value not in fonttable: if value not in fonttable:
fonttable[value] = [] fonttable[value] = []
elif self.font and name == 'entry': elif self.font and name == 'entry':
number = '' number = ''
for (name, value) in attrs.items(): for (name, value) in list(attrs.items()):
if name == "key": key = int(value) if name == "key": key = int(value)
elif name == "number": number = value elif name == "number": number = value
elif name == "name": latexName = value elif name == "name": latexName = value
@ -53,13 +53,13 @@ def writeFontTable(fontname, f):
def write_header(f): def write_header(f):
print >>f, '''// print('''//
// Created: ''' + time.ctime(time.time()) + ''' // Created: ''' + time.ctime(time.time()) + '''
// by: gensymbolfontmap.py // by: gensymbolfontmap.py
// from: symbol.xml // from: symbol.xml
// //
// WARNING! All changes made in this file will be lost! // WARNING! All changes made in this file will be lost!
''' ''', file=f)
def main(): def main():
f = open('../symbolfontmapping.cpp', 'w') f = open('../symbolfontmapping.cpp', 'w')
@ -109,8 +109,8 @@ def main():
f = open('../unicodenames.cpp', 'w') f = open('../unicodenames.cpp', 'w')
write_header(f) write_header(f)
print >>f, 'struct UnicodeNameTable { short unicode; const char* name; };' print('struct UnicodeNameTable { short unicode; const char* name; };', file=f)
print >>f, 'static UnicodeNameTable nameTable[] = {' print('static UnicodeNameTable nameTable[] = {', file=f)
nameDir = {} nameDir = {}
table = {} table = {}
for style in unicodetable: for style in unicodetable:
@ -121,9 +121,9 @@ def main():
if len(latexName) > 0: if len(latexName) > 0:
#for fn in fontnames: #for fn in fontnames:
# if fontkey(fn, style, key): # if fontkey(fn, style, key):
print >>f, ' { ' + key + ', "' + latexName + '" },' print(' { ' + key + ', "' + latexName + '" },', file=f)
#break #break
print >>f, ' { 0, 0 }\n};' print(' { 0, 0 }\n};', file=f)
f.close() f.close()
@ -132,12 +132,12 @@ def make_unicode_table():
header = [] header = []
codes = {} codes = {}
f = open('../config/unicode.tbl', 'r') f = open('../config/unicode.tbl', 'r')
for line in f.xreadlines(): for line in f:
if line[0] == '#': if line[0] == '#':
header.append(line.strip()) header.append(line.strip())
else: else:
break break
for line in f.xreadlines(): for line in f:
if len(line) > 0: if len(line) > 0:
codes[line.split(',')[0].strip()] = line codes[line.split(',')[0].strip()] = line
f.close() f.close()
@ -151,9 +151,9 @@ def make_unicode_table():
f = open('../config/unicode.tbl', 'w') f = open('../config/unicode.tbl', 'w')
for line in header: for line in header:
print >> f, line print(line, file=f)
for key in codes: for key in codes:
print >> f, codes[key] print(codes[key], file=f)
f.close() f.close()
def make_font_table(font): def make_font_table(font):
@ -178,7 +178,7 @@ def make_font_table(font):
latexName, charClass = unicodetable[key] latexName, charClass = unicodetable[key]
pos = fontkey(font, key) pos = fontkey(font, key)
if pos: if pos:
print >> f, str(pos), key, charClass, latexName print(str(pos), key, charClass, latexName, file=f)
f.close() f.close()
def make_all_font_tables(): def make_all_font_tables():
@ -186,30 +186,30 @@ def make_all_font_tables():
make_font_table(font) make_font_table(font)
def symbol_entry(pos, unicode, charClass, name): def symbol_entry(pos, str, charClass, name):
return ' <entry key="%d" number="%s" name="%s" class="%s"/>' % \ return ' <entry key="%d" number="%s" name="%s" class="%s"/>' % \
(pos, unicode, name, charClass) (pos, str, name, charClass)
def compare_font(font): def compare_font(font):
for line in file(font+".font"): for line in file(font+".font"):
list = line.split() list = line.split()
pos = int(list[0]) pos = int(list[0])
unicode = list[1] str = list[1]
charClass = list[2] charClass = list[2]
if len(list)>3: if len(list)>3:
name = list[3] name = list[3]
else: else:
name = "" name = ""
if (pos, unicode) not in fonttable[font]: if (pos, str) not in fonttable[font]:
print "not in font", font, (pos, unicode) print("not in font", font, (pos, str))
print symbol_entry(pos, unicode, charClass, name) print(symbol_entry(pos, str, charClass, name))
if unicode not in unicodetable: if str not in unicodetable:
print font, unicode, (name, charClass) print(font, str, (name, charClass))
print symbol_entry(pos, unicode, charClass, name) print(symbol_entry(pos, str, charClass, name))
elif unicodetable[unicode] != (name, charClass): elif unicodetable[str] != (name, charClass):
print font, unicode, pos, unicodetable[unicode], "!=", (name, charClass) print(font, str, pos, unicodetable[str], "!=", (name, charClass))
def compare(): def compare():
fontnames = [ "symbol", fontnames = [ "symbol",

@ -127,21 +127,21 @@ class Widget(TQWidget):
self.fonts[self.child.fontName] = self.child.fontList() self.fonts[self.child.fontName] = self.child.fontList()
f = open("symbol.xml", "w") f = open("symbol.xml", "w")
print >> f, '<?xml version="1.0" encoding="iso-8859-1"?>' print('<?xml version="1.0" encoding="iso-8859-1"?>', file=f)
print >> f, '<table>' print('<table>', file=f)
for font in self.fonts: for font in self.fonts:
print >> f, ' <unicodetable font="' + font + '">' print(' <unicodetable font="' + font + '">', file=f)
for (key, number, latexName, charClass) in self.fonts[font]: for (key, number, latexName, charClass) in self.fonts[font]:
if not charClass or charClass == '': if not charClass or charClass == '':
charClass = 'ORDINARY' charClass = 'ORDINARY'
print >> f, ' <entry key="' + str(key) + \ print(' <entry key="' + str(key) + \
'" number="' + str(number) + \ '" number="' + str(number) + \
'" name="' + str(latexName) + \ '" name="' + str(latexName) + \
'" class="' + str(charClass) + \ '" class="' + str(charClass) + \
'"/>' '"/>', file=f)
print >> f, ' </unicodetable>' print(' </unicodetable>', file=f)
print >> f, '</table>' print('</table>', file=f)
f.close() f.close()
@ -153,14 +153,14 @@ class ContentGenerator(handler.ContentHandler):
def startElement(self, name, attrs): def startElement(self, name, attrs):
if name == 'unicodetable': if name == 'unicodetable':
for (name, value) in attrs.items(): for (name, value) in list(attrs.items()):
if name == "font": if name == "font":
self.currentFont = value self.currentFont = value
self.fonts[self.currentFont] = [] self.fonts[self.currentFont] = []
elif name == 'entry': elif name == 'entry':
if not self.currentFont: if not self.currentFont:
raise "entry must belong to a font" raise "entry must belong to a font"
for (name, value) in attrs.items(): for (name, value) in list(attrs.items()):
if name == "key": if name == "key":
if len(value) > 1 and value[:2] == "0x": if len(value) > 1 and value[:2] == "0x":
key = int(value[2:], 16) key = int(value[2:], 16)

@ -25,11 +25,11 @@ from TQt import qt
def decode( fd, font, line ): def decode( fd, font, line ):
begin = string.find( line, '"' ) begin = string.find( line, '"' )
end = string.find( line, '"', begin + 1) end = string.find( line, '"', begin + 1)
unicode = line[begin + 2:end] # Remove 'U' from string aswell str = line[begin + 2:end] # Remove 'U' from string aswell
char_list = [] char_list = []
separation = string.find( unicode, '-' ) separation = string.find( str, '-' )
if separation != -1: if separation != -1:
second = unicode second = str
while separation != -1: while separation != -1:
first = second[0:separation] first = second[0:separation]
second = second[separation + 2:] second = second[separation + 2:]
@ -38,13 +38,13 @@ def decode( fd, font, line ):
if separation == -1: if separation == -1:
char_list.append( string.atoi( second, 16 ) ) char_list.append( string.atoi( second, 16 ) )
else: else:
char_list.append( string.atoi ( unicode, 16 ) ) char_list.append( string.atoi ( str, 16 ) )
fm = qt.TQFontMetrics( qt.TQFont( font ) ) fm = qt.TQFontMetrics( qt.TQFont( font ) )
in_font = True in_font = True
for c in char_list: for c in char_list:
if not fm.inFont( qt.TQChar( c ) ): if not fm.inFont( qt.TQChar( c ) ):
in_font = False in_font = False
fd.write( unicode + ' ' + str( in_font ) + '\n') fd.write( str + ' ' + str( in_font ) + '\n')
def parse( file, font ): def parse( file, font ):
fd = open( file ) fd = open( file )

@ -24,7 +24,7 @@ import time
import os import os
def write_header( f ): def write_header( f ):
print >> f, '''// print('''//
// Created: ''' + time.ctime(time.time()) + ''' // Created: ''' + time.ctime(time.time()) + '''
// by: ''' + os.path.basename( sys.argv[0] ) + ''' // by: ''' + os.path.basename( sys.argv[0] ) + '''
// from: ''' + os.path.basename( sys.argv[1] ) + ''' // from: ''' + os.path.basename( sys.argv[1] ) + '''
@ -49,10 +49,10 @@ def write_header( f ):
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA. * Boston, MA 02110-1301, USA.
*/ */
''' ''', file=f)
def write_h( f ): def write_h( f ):
print >>f, ''' print('''
#ifndef ENTITIES_H #ifndef ENTITIES_H
#define ENTITIES_H #define ENTITIES_H
@ -74,19 +74,19 @@ extern const entityMap entities[];
KFORMULA_NAMESPACE_END KFORMULA_NAMESPACE_END
#endif // ENTITIES_H #endif // ENTITIES_H
''' ''', file=f)
def write_cc( fr, fw ): def write_cc( fr, fw ):
print >> fw, ''' print('''
#include "entities.h" #include "entities.h"
KFORMULA_NAMESPACE_BEGIN KFORMULA_NAMESPACE_BEGIN
const entityMap entities[] = {''' const entityMap entities[] = {''', file=fw)
parse( fr, fw ) parse( fr, fw )
print >> fw, ''' print('''
}; };
// Needed since sizeof is a macro and we cannot be used until size is known // Needed since sizeof is a macro and we cannot be used until size is known
@ -96,7 +96,7 @@ int entityMap::size()
} }
KFORMULA_NAMESPACE_END KFORMULA_NAMESPACE_END
''' ''', file=fw)
def name_cmp( a, b ): def name_cmp( a, b ):
@ -104,7 +104,7 @@ def name_cmp( a, b ):
return -1 return -1
if a[0] > b[0]: if a[0] > b[0]:
return 1 return 1
print 'WARNING: Same name in entity: ' + a[0] + ', ' + b[0] print('WARNING: Same name in entity: ' + a[0] + ', ' + b[0])
return 0; return 0;
def parse( fr, fw ): def parse( fr, fw ):
@ -133,10 +133,10 @@ def parse( fr, fw ):
while True: while True:
e = entries.pop() e = entries.pop()
fd_list.write( e[0] + ' ' + e[1] + '\n') fd_list.write( e[0] + ' ' + e[1] + '\n')
print >> fw, ' {"' + e[0] + '", ' + e[1] + '}', print(' {"' + e[0] + '", ' + e[1] + '}', end=' ', file=fw)
if len( entries ) == 0: if len( entries ) == 0:
break break
print >> fw, ',' print(',', file=fw)
fd_list.close() fd_list.close()
if __name__ == '__main__': if __name__ == '__main__':

@ -43,7 +43,7 @@ attr_list = [
def write_header( f ): def write_header( f ):
print >> f, '''// print('''//
// Created: ''' + time.ctime(time.time()) + ''' // Created: ''' + time.ctime(time.time()) + '''
// by: ''' + os.path.basename( sys.argv[0] ) + ''' // by: ''' + os.path.basename( sys.argv[0] ) + '''
// from: ''' + os.path.basename( sys.argv[1] ) + ''' // from: ''' + os.path.basename( sys.argv[1] ) + '''
@ -68,10 +68,10 @@ def write_header( f ):
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA. * Boston, MA 02110-1301, USA.
*/ */
''' ''', file=f)
def write_h( f ): def write_h( f ):
print >>f, ''' print('''
#ifndef OPERATORDICTIONARY_H #ifndef OPERATORDICTIONARY_H
#define OPERATORDICTIONARY_H #define OPERATORDICTIONARY_H
@ -119,20 +119,20 @@ extern const OperatorDictionary operators[];
KFORMULA_NAMESPACE_END KFORMULA_NAMESPACE_END
#endif // OPERATORDICTIONARY_H #endif // OPERATORDICTIONARY_H
''' ''', file=f)
def write_cc( fr, fw ): def write_cc( fr, fw ):
print >> fw, ''' print('''
#include "operatordictionary.h" #include "operatordictionary.h"
KFORMULA_NAMESPACE_BEGIN KFORMULA_NAMESPACE_BEGIN
const OperatorDictionary operators[] = {''' const OperatorDictionary operators[] = {''', file=fw)
entities = get_entities() entities = get_entities()
parse( fr, fw, entities ) parse( fr, fw, entities )
print >> fw, ''' print('''
}; };
// Needed since sizeof is a macro and we cannot be used until size is known // Needed since sizeof is a macro and we cannot be used until size is known
@ -142,7 +142,7 @@ int OperatorDictionary::size()
} }
KFORMULA_NAMESPACE_END KFORMULA_NAMESPACE_END
''' ''', file=fw)
def get_entities(): def get_entities():
# First, read entity list into a dict # First, read entity list into a dict
@ -165,7 +165,7 @@ def key_cmp( a, b ):
return -1 return -1
if a[1] > b[1]: if a[1] > b[1]:
return 1 return 1
print 'WARNING: Same key in operator dictionary: ' + a[0] + ', ' + b[0] print('WARNING: Same key in operator dictionary: ' + a[0] + ', ' + b[0])
return 0 return 0
def parse( fr, fw, entities ): def parse( fr, fw, entities ):
@ -203,8 +203,8 @@ def parse( fr, fw, entities ):
# application. The best solution would probably to map to a single # application. The best solution would probably to map to a single
# character provided by the font in the private area of Unicode # character provided by the font in the private area of Unicode
entity_name = name[begin + 1:end] entity_name = name[begin + 1:end]
if entities.has_key( entity_name ) : if entity_name in entities :
name = name.replace( '&' + entity_name + ';', unichr(entities[entity_name])); name = name.replace( '&' + entity_name + ';', chr(entities[entity_name]));
else: else:
entities_found = False entities_found = False
break break
@ -213,9 +213,9 @@ def parse( fr, fw, entities ):
fields.pop(0) # Remove form fields.pop(0) # Remove form
for f in fields: for f in fields:
attr, value = string.split( f, '=' ) attr, value = string.split( f, '=' )
if not attr_dict.has_key( attr ) : if attr not in attr_dict :
print 'Unsupported attribute: ' + attr print('Unsupported attribute: ' + attr)
print 'If it is valid, update attribute dictionary' print('If it is valid, update attribute dictionary')
sys.exit(-1) sys.exit(-1)
# Spec has a typo, fix it # Spec has a typo, fix it
if string.count( value, '"' ) == 3: if string.count( value, '"' ) == 3:
@ -227,20 +227,20 @@ def parse( fr, fw, entities ):
while True: while True:
e = entries.pop() e = entries.pop()
print >> fw, ' { {' + e[0] + ', ' + e[1] + '},' print(' { {' + e[0] + ', ' + e[1] + '},', file=fw)
d = e[2] d = e[2]
for a in attr_list: for a in attr_list:
# Convert, at least, bool values # Convert, at least, bool values
value = d[a] value = d[a]
if value == '"true"' or value == '"false"': if value == '"true"' or value == '"false"':
value = string.strip( value, '"' ) value = string.strip( value, '"' )
print >> fw, '\t\t' + value, print('\t\t' + value, end=' ', file=fw)
if a != attr_list[len(attr_list) - 1]: if a != attr_list[len(attr_list) - 1]:
print >> fw, ',' print(',', file=fw)
print >> fw, '}', print('}', end=' ', file=fw)
if len( entries ) == 0: if len( entries ) == 0:
break break
print >> fw, ',\n' print(',\n', file=fw)
if __name__ == '__main__': if __name__ == '__main__':
fh = open( '../operatordictionary.h', 'w' ) fh = open( '../operatordictionary.h', 'w' )

@ -62,10 +62,10 @@ class RestrictionCapableEval:
self.expr, '<string>') self.expr, '<string>')
if PROFILE: if PROFILE:
end = clock() end = clock()
print 'prepRestrictedCode: %d ms for %s' % ( print('prepRestrictedCode: %d ms for %s' % (
(end - start) * 1000, `self.expr`) (end - start) * 1000, repr(self.expr)))
if err: if err:
raise SyntaxError, err[0] raise SyntaxError(err[0])
self.used = tuple(used.keys()) self.used = tuple(used.keys())
self.rcode = co self.rcode = co

@ -93,7 +93,7 @@ def _write_wrapper():
try: try:
f = getattr(self.ob, secattr) f = getattr(self.ob, secattr)
except AttributeError: except AttributeError:
raise TypeError, error_msg raise TypeError(error_msg)
f(*args) f(*args)
return handler return handler
class Wrapper: class Wrapper:

@ -25,22 +25,22 @@ def limited_range(iFirst, *args):
elif len(args) == 2: elif len(args) == 2:
iStart, iEnd, iStep = iFirst, args[0], args[1] iStart, iEnd, iStep = iFirst, args[0], args[1]
else: else:
raise AttributeError, 'range() requires 1-3 int arguments' raise AttributeError('range() requires 1-3 int arguments')
if iStep == 0: raise ValueError, 'zero step for range()' if iStep == 0: raise ValueError('zero step for range()')
iLen = int((iEnd - iStart) / iStep) iLen = int((iEnd - iStart) / iStep)
if iLen < 0: iLen = 0 if iLen < 0: iLen = 0
if iLen >= RANGELIMIT: raise ValueError, 'range() too large' if iLen >= RANGELIMIT: raise ValueError('range() too large')
return range(iStart, iEnd, iStep) return list(range(iStart, iEnd, iStep))
limited_builtins['range'] = limited_range limited_builtins['range'] = limited_range
def limited_list(seq): def limited_list(seq):
if isinstance(seq, str): if isinstance(seq, str):
raise TypeError, 'cannot convert string to list' raise TypeError('cannot convert string to list')
return list(seq) return list(seq)
limited_builtins['list'] = limited_list limited_builtins['list'] = limited_list
def limited_tuple(seq): def limited_tuple(seq):
if isinstance(seq, str): if isinstance(seq, str):
raise TypeError, 'cannot convert string to tuple' raise TypeError('cannot convert string to tuple')
return tuple(seq) return tuple(seq)
limited_builtins['tuple'] = limited_tuple limited_builtins['tuple'] = limited_tuple

@ -26,7 +26,7 @@ class MutatingWalker:
self._cache = {} self._cache = {}
def defaultVisitNode(self, node, walker=None, exclude=None): def defaultVisitNode(self, node, walker=None, exclude=None):
for name, child in node.__dict__.items(): for name, child in list(node.__dict__.items()):
if exclude is not None and name in exclude: if exclude is not None and name in exclude:
continue continue
v = self.dispatchObject(child) v = self.dispatchObject(child)

@ -52,7 +52,7 @@ class RestrictedCompileMode(AbstractCompileMode):
tree = self.parse() tree = self.parse()
MutatingWalker.walk(tree, self.rm) MutatingWalker.walk(tree, self.rm)
if self.rm.errors: if self.rm.errors:
raise SyntaxError, self.rm.errors[0] raise SyntaxError(self.rm.errors[0])
misc.set_filename(self.filename, tree) misc.set_filename(self.filename, tree)
syntax.check(tree) syntax.check(tree)
return tree return tree
@ -66,7 +66,7 @@ class RestrictedCompileMode(AbstractCompileMode):
def compileAndTuplize(gen): def compileAndTuplize(gen):
try: try:
gen.compile() gen.compile()
except SyntaxError, v: except SyntaxError as v:
return None, (str(v),), gen.rm.warnings, gen.rm.used_names return None, (str(v),), gen.rm.warnings, gen.rm.used_names
return gen.getCode(), (), gen.rm.warnings, gen.rm.used_names return gen.getCode(), (), gen.rm.warnings, gen.rm.used_names

@ -26,7 +26,7 @@ from SelectCompiler import ast, parse, OP_ASSIGN, OP_DELETE, OP_APPLY
# trees without affecting line numbers shown in tracebacks, etc. # trees without affecting line numbers shown in tracebacks, etc.
def rmLineno(node): def rmLineno(node):
"""Strip lineno attributes from a code tree.""" """Strip lineno attributes from a code tree."""
if node.__dict__.has_key('lineno'): if 'lineno' in node.__dict__:
del node.lineno del node.lineno
for child in node.getChildren(): for child in node.getChildren():
if isinstance(child, ast.Node): if isinstance(child, ast.Node):

@ -34,8 +34,8 @@ class TkDialog:
""" This class is used to wrap Tkinter into a more abstract interface.""" """ This class is used to wrap Tkinter into a more abstract interface."""
def __init__(self, title): def __init__(self, title):
import Tkinter import tkinter
self.root = Tkinter.Tk() self.root = tkinter.Tk()
self.root.title(title) self.root.title(title)
self.root.deiconify() self.root.deiconify()
@ -52,42 +52,42 @@ class TkDialog:
class Frame(Widget): class Frame(Widget):
def __init__(self, dialog, parent): def __init__(self, dialog, parent):
#TkDialog.Widget.__init__(self, dialog, parent) #TkDialog.Widget.__init__(self, dialog, parent)
import Tkinter import tkinter
self.widget = Tkinter.Frame(parent) self.widget = tkinter.Frame(parent)
self.widget.pack() self.widget.pack()
class Label(Widget): class Label(Widget):
def __init__(self, dialog, parent, caption): def __init__(self, dialog, parent, caption):
#TkDialog.Widget.__init__(self, dialog, parent) #TkDialog.Widget.__init__(self, dialog, parent)
import Tkinter import tkinter
self.widget = Tkinter.Label(parent, text=caption) self.widget = tkinter.Label(parent, text=caption)
self.widget.pack(side=Tkinter.TOP) self.widget.pack(side=tkinter.TOP)
class CheckBox(Widget): class CheckBox(Widget):
def __init__(self, dialog, parent, caption, checked = True): def __init__(self, dialog, parent, caption, checked = True):
#TkDialog.Widget.__init__(self, dialog, parent) #TkDialog.Widget.__init__(self, dialog, parent)
import Tkinter import tkinter
self.checkstate = Tkinter.IntVar() self.checkstate = tkinter.IntVar()
self.checkstate.set(checked) self.checkstate.set(checked)
self.widget = Tkinter.Checkbutton(parent, text=caption, variable=self.checkstate) self.widget = tkinter.Checkbutton(parent, text=caption, variable=self.checkstate)
self.widget.pack(side=Tkinter.TOP) self.widget.pack(side=tkinter.TOP)
def isChecked(self): def isChecked(self):
return self.checkstate.get() return self.checkstate.get()
class List(Widget): class List(Widget):
def __init__(self, dialog, parent, caption, items): def __init__(self, dialog, parent, caption, items):
#TkDialog.Widget.__init__(self, dialog, parent) #TkDialog.Widget.__init__(self, dialog, parent)
import Tkinter import tkinter
listframe = Tkinter.Frame(parent) listframe = tkinter.Frame(parent)
listframe.pack() listframe.pack()
Tkinter.Label(listframe, text=caption).pack(side=Tkinter.LEFT) tkinter.Label(listframe, text=caption).pack(side=tkinter.LEFT)
self.items = items self.items = items
self.variable = Tkinter.StringVar() self.variable = tkinter.StringVar()
itemlist = apply(Tkinter.OptionMenu, (listframe, self.variable) + tuple( items )) itemlist = tkinter.OptionMenu(*(listframe, self.variable) + tuple( items ))
itemlist.pack(side=Tkinter.LEFT) itemlist.pack(side=tkinter.LEFT)
def get(self): def get(self):
return self.variable.get() return self.variable.get()
def set(self, index): def set(self, index):
@ -96,48 +96,48 @@ class TkDialog:
class Button(Widget): class Button(Widget):
def __init__(self, dialog, parent, caption, commandmethod): def __init__(self, dialog, parent, caption, commandmethod):
#TkDialog.Widget.__init__(self, dialog, parent) #TkDialog.Widget.__init__(self, dialog, parent)
import Tkinter import tkinter
self.widget = Tkinter.Button(parent, text=caption, command=self.doCommand) self.widget = tkinter.Button(parent, text=caption, command=self.doCommand)
self.commandmethod = commandmethod self.commandmethod = commandmethod
self.widget.pack(side=Tkinter.LEFT) self.widget.pack(side=tkinter.LEFT)
def doCommand(self): def doCommand(self):
try: try:
self.commandmethod() self.commandmethod()
except: except:
#TODO why the heck we arn't able to redirect exceptions? #TODO why the heck we arn't able to redirect exceptions?
import traceback import traceback
import StringIO import io
fp = StringIO.StringIO() fp = io.StringIO()
traceback.print_exc(file=fp) traceback.print_exc(file=fp)
import tkMessageBox import tkinter.messagebox
tkMessageBox.showerror("Exception", fp.getvalue()) tkinter.messagebox.showerror("Exception", fp.getvalue())
#self.dialog.root.destroy() #self.dialog.root.destroy()
class Edit(Widget): class Edit(Widget):
def __init__(self, dialog, parent, caption, text): def __init__(self, dialog, parent, caption, text):
#TkDialog.Widget.__init__(self, dialog, parent) #TkDialog.Widget.__init__(self, dialog, parent)
import Tkinter import tkinter
self.widget = Tkinter.Frame(parent) self.widget = tkinter.Frame(parent)
self.widget.pack() self.widget.pack()
label = Tkinter.Label(self.widget, text=caption) label = tkinter.Label(self.widget, text=caption)
label.pack(side=Tkinter.LEFT) label.pack(side=tkinter.LEFT)
self.entrytext = Tkinter.StringVar() self.entrytext = tkinter.StringVar()
self.entrytext.set(text) self.entrytext.set(text)
self.entry = Tkinter.Entry(self.widget, width=36, textvariable=self.entrytext) self.entry = tkinter.Entry(self.widget, width=36, textvariable=self.entrytext)
self.entry.pack(side=Tkinter.LEFT) self.entry.pack(side=tkinter.LEFT)
def get(self): def get(self):
return self.entrytext.get() return self.entrytext.get()
class FileChooser(Edit): class FileChooser(Edit):
def __init__(self, dialog, parent, caption, initialfile = None, filetypes = None): def __init__(self, dialog, parent, caption, initialfile = None, filetypes = None):
TkDialog.Edit.__init__(self, dialog, parent, caption, initialfile) TkDialog.Edit.__init__(self, dialog, parent, caption, initialfile)
import Tkinter import tkinter
self.initialfile = initialfile self.initialfile = initialfile
self.entrytext.set(initialfile) self.entrytext.set(initialfile)
btn = Tkinter.Button(self.widget, text="...", command=self.browse) btn = tkinter.Button(self.widget, text="...", command=self.browse)
btn.pack(side=Tkinter.LEFT) btn.pack(side=tkinter.LEFT)
if filetypes: if filetypes:
self.filetypes = filetypes self.filetypes = filetypes
@ -150,8 +150,8 @@ class TkDialog:
d = os.path.dirname(text) or os.path.dirname(self.initialfile) d = os.path.dirname(text) or os.path.dirname(self.initialfile)
f = os.path.basename(text) or os.path.basename(self.initialfile) f = os.path.basename(text) or os.path.basename(self.initialfile)
import tkFileDialog import tkinter.filedialog
file = tkFileDialog.asksaveasfilename( file = tkinter.filedialog.asksaveasfilename(
initialdir=d, initialdir=d,
initialfile=f, initialfile=f,
#defaultextension='.html', #defaultextension='.html',
@ -167,11 +167,11 @@ class TkDialog:
self.caption = str(caption) self.caption = str(caption)
self.message = str(message) self.message = str(message)
def show(self): def show(self):
import tkMessageBox import tkinter.messagebox
if self.typename == "okcancel": if self.typename == "okcancel":
return tkMessageBox.askokcancel(self.caption, self.message,icon=tkmessageBox.QESTION) return tkinter.messagebox.askokcancel(self.caption, self.message,icon=tkmessageBox.QESTION)
else: else:
tkMessageBox.showinfo(self.caption, self.message) tkinter.messagebox.showinfo(self.caption, self.message)
return True return True
def show(self): def show(self):
@ -276,7 +276,7 @@ class TQtDialog:
def browseButtonClicked(self): def browseButtonClicked(self):
filtermask = "" filtermask = ""
import types import types
if isinstance(self.filetypes, types.TupleType): if isinstance(self.filetypes, tuple):
for ft in self.filetypes: for ft in self.filetypes:
if len(ft) == 1: if len(ft) == 1:
filtermask += "%s\n" % (ft[0]) filtermask += "%s\n" % (ft[0])
@ -289,12 +289,12 @@ class TQtDialog:
filename = None filename = None
try: try:
print "TQtDialog.FileChooser.browseButtonClicked() tdefile.KFileDialog" print("TQtDialog.FileChooser.browseButtonClicked() tdefile.KFileDialog")
# try to use the tdefile module included in pytde # try to use the tdefile module included in pytde
import tdefile import tdefile
filename = tdefile.KFileDialog.getOpenFileName(self.initialfile, filtermask, self, "Save to file") filename = tdefile.KFileDialog.getOpenFileName(self.initialfile, filtermask, self, "Save to file")
except: except:
print "TQtDialog.FileChooser.browseButtonClicked() qt.TQFileDialog" print("TQtDialog.FileChooser.browseButtonClicked() qt.TQFileDialog")
# fallback to TQt filedialog # fallback to TQt filedialog
filename = qt.TQFileDialog.getOpenFileName(self.initialfile, filtermask, self, "Save to file") filename = qt.TQFileDialog.getOpenFileName(self.initialfile, filtermask, self, "Save to file")
if filename != None and filename != "": if filename != None and filename != "":
@ -341,7 +341,7 @@ class TQtDialog:
qt.TQApplication.restoreOverrideCursor() qt.TQApplication.restoreOverrideCursor()
def close(self): def close(self):
print "TQtDialog.close()" print("TQtDialog.close()")
self.dialog.close() self.dialog.close()
#self.dialog.deleteLater() #self.dialog.deleteLater()
@ -352,16 +352,16 @@ class Dialog:
self.dialog = None self.dialog = None
try: try:
print "Trying to import PyTQt..." print("Trying to import PyTQt...")
self.dialog = TQtDialog(title) self.dialog = TQtDialog(title)
print "PyTQt is our toolkit!" print("PyTQt is our toolkit!")
except: except:
try: try:
print "Failed to import PyTQt. Trying to import TkInter..." print("Failed to import PyTQt. Trying to import TkInter...")
self.dialog = TkDialog(title) self.dialog = TkDialog(title)
print "Falling back to TkInter as our toolkit!" print("Falling back to TkInter as our toolkit!")
except: except:
raise "Failed to import GUI-toolkit. Please install the PyTQt or the Tkinter python module." raise Exception("Failed to import GUI-toolkit. Please install the PyTQt or the Tkinter python module.")
self.widget = self.dialog.widget self.widget = self.dialog.widget
def show(self): def show(self):

@ -59,84 +59,84 @@ class TestPlugin(unittest.TestCase):
def setUp(self): def setUp(self):
import krosstestpluginmodule import krosstestpluginmodule
self.pluginobject1 = krosstestpluginmodule.testpluginobject1() self.pluginobject1 = krosstestpluginmodule.testpluginobject1()
self.assert_( self.pluginobject1 ) self.assertTrue( self.pluginobject1 )
self.pluginobject2 = krosstestpluginmodule.testpluginobject2() self.pluginobject2 = krosstestpluginmodule.testpluginobject2()
self.assert_( self.pluginobject2 ) self.assertTrue( self.pluginobject2 )
self.testqobject1 = krosstestpluginmodule.testqobject1() self.testqobject1 = krosstestpluginmodule.testqobject1()
self.assert_( self.testqobject1 ) self.assertTrue( self.testqobject1 )
def testBasicDataTypes(self): def testBasicDataTypes(self):
self.assert_( self.pluginobject1.uintfunc(177321) == 177321 ) self.assertTrue( self.pluginobject1.uintfunc(177321) == 177321 )
self.assert_( self.pluginobject1.intfunc(93675) == 93675 ) self.assertTrue( self.pluginobject1.intfunc(93675) == 93675 )
self.assert_( self.pluginobject1.intfunc(-73673) == -73673 ) self.assertTrue( self.pluginobject1.intfunc(-73673) == -73673 )
self.assert_( self.pluginobject1.boolfunc(True) == True ) self.assertTrue( self.pluginobject1.boolfunc(True) == True )
self.assert_( self.pluginobject1.boolfunc(False) == False ) self.assertTrue( self.pluginobject1.boolfunc(False) == False )
self.assert_( self.pluginobject1.doublefunc(4265.3723) == 4265.3723 ) self.assertTrue( self.pluginobject1.doublefunc(4265.3723) == 4265.3723 )
self.assert_( self.pluginobject1.doublefunc(-4265.68) == -4265.68 ) self.assertTrue( self.pluginobject1.doublefunc(-4265.68) == -4265.68 )
self.assert_( self.pluginobject1.cstringfunc(" This is a Test! ") == " This is a Test! " ) self.assertTrue( self.pluginobject1.cstringfunc(" This is a Test! ") == " This is a Test! " )
self.assert_( self.pluginobject1.stringfunc(" Another \n\r Test! $%&\"") == " Another \n\r Test! $%&\"" ) self.assertTrue( self.pluginobject1.stringfunc(" Another \n\r Test! $%&\"") == " Another \n\r Test! $%&\"" )
#TODO #TODO
#self.assert_( self.pluginobject1.stringfunc( unicode(" Unicode test ") ) == " Unicode test " ) #self.assert_( self.pluginobject1.stringfunc( unicode(" Unicode test ") ) == " Unicode test " )
#self.assert_( self.pluginobject1.stringfunc(unicode(" Another Test! ")) == unicode(" Another Test! ") ) #self.assert_( self.pluginobject1.stringfunc(unicode(" Another Test! ")) == unicode(" Another Test! ") )
self.assert_( self.pluginobject1.stringstringfunc("MyString1", "MyString2") == "MyString1" ) self.assertTrue( self.pluginobject1.stringstringfunc("MyString1", "MyString2") == "MyString1" )
self.assert_( self.pluginobject1.uintdoublestringfunc(8529,285.246,"String") == 8529 ) self.assertTrue( self.pluginobject1.uintdoublestringfunc(8529,285.246,"String") == 8529 )
self.assert_( self.pluginobject1.stringlistbooluintdouble(["s1","s2"],True,6,7.0,"String") == ["s1","s2"] ) self.assertTrue( self.pluginobject1.stringlistbooluintdouble(["s1","s2"],True,6,7.0,"String") == ["s1","s2"] )
def testStringList(self): def testStringList(self):
self.assert_( self.pluginobject1.stringlistfunc( [] ) == [] ) self.assertTrue( self.pluginobject1.stringlistfunc( [] ) == [] )
self.assert_( self.pluginobject1.stringlistfunc( ["First Item"," Second Item "] ) == ["First Item"," Second Item "] ) self.assertTrue( self.pluginobject1.stringlistfunc( ["First Item"," Second Item "] ) == ["First Item"," Second Item "] )
self.assert_( self.pluginobject1.stringlistfunc( ("Theird Item"," Forth Item ","Fifth Item") ) == ["Theird Item"," Forth Item ","Fifth Item"] ) self.assertTrue( self.pluginobject1.stringlistfunc( ("Theird Item"," Forth Item ","Fifth Item") ) == ["Theird Item"," Forth Item ","Fifth Item"] )
def testVariant(self): def testVariant(self):
self.assert_( self.pluginobject1.variantfunc(True) == True ) self.assertTrue( self.pluginobject1.variantfunc(True) == True )
self.assert_( self.pluginobject1.variantfunc(False) == False ) self.assertTrue( self.pluginobject1.variantfunc(False) == False )
self.assert_( self.pluginobject1.variantfunc(187937) == 187937 ) self.assertTrue( self.pluginobject1.variantfunc(187937) == 187937 )
self.assert_( self.pluginobject1.variantfunc(-69825) == -69825 ) self.assertTrue( self.pluginobject1.variantfunc(-69825) == -69825 )
self.assert_( self.pluginobject1.variantfunc(8632.274) == 8632.274 ) self.assertTrue( self.pluginobject1.variantfunc(8632.274) == 8632.274 )
self.assert_( self.pluginobject1.variantfunc(-8632.351) == -8632.351 ) self.assertTrue( self.pluginobject1.variantfunc(-8632.351) == -8632.351 )
self.assert_( self.pluginobject1.variantfunc(" Test \n\r This String $%&\"") == " Test \n\r This String $%&\"") self.assertTrue( self.pluginobject1.variantfunc(" Test \n\r This String $%&\"") == " Test \n\r This String $%&\"")
def testObjects(self): def testObjects(self):
print "-----------------1" print("-----------------1")
newobjref = self.pluginobject1.objectfunc(self.pluginobject2) newobjref = self.pluginobject1.objectfunc(self.pluginobject2)
print "-----------------2" print("-----------------2")
print str(newobjref) print(str(newobjref))
#self.assert_( newobjref.myuniqueid == self.pluginobject2.myuniqueid ) #self.assert_( newobjref.myuniqueid == self.pluginobject2.myuniqueid )
#print "===========> %s" % self.pluginobject2.myName() #print "===========> %s" % self.pluginobject2.myName()
print "testqobject1 properties=%s" % self.testqobject1.propertyNames() print("testqobject1 properties=%s" % self.testqobject1.propertyNames())
print "testqobject1 Q_SLOTS=%s" % self.testqobject1.slotNames() print("testqobject1 Q_SLOTS=%s" % self.testqobject1.slotNames())
print "testqobject1 Q_SIGNALS=%s" % self.testqobject1.signalNames() print("testqobject1 Q_SIGNALS=%s" % self.testqobject1.signalNames())
print "-----------------3" print("-----------------3")
print "DIR=>%s" % dir(self.testqobject1) print("DIR=>%s" % dir(self.testqobject1))
print "===================> slotcall-result: %s" % self.testqobject1.slot("self()") print("===================> slotcall-result: %s" % self.testqobject1.slot("self()"))
#testobject = newobjref.get("TestObject") #testobject = newobjref.get("TestObject")
#print testobject #print testobject
print "-----------------9" print("-----------------9")
def testDefaultArguments(self): def testDefaultArguments(self):
self.assert_( self.pluginobject1.uintfunc_defarg(98765) == 98765 ) self.assertTrue( self.pluginobject1.uintfunc_defarg(98765) == 98765 )
self.assert_( self.pluginobject1.uintfunc_defarg() == 12345 ) self.assertTrue( self.pluginobject1.uintfunc_defarg() == 12345 )
self.assert_( self.pluginobject1.stringfunc_defarg("MyString") == "MyString" ) self.assertTrue( self.pluginobject1.stringfunc_defarg("MyString") == "MyString" )
self.assert_( self.pluginobject1.stringfunc_defarg() == "MyDefaultString" ) self.assertTrue( self.pluginobject1.stringfunc_defarg() == "MyDefaultString" )
self.assert_( self.pluginobject1.stringlistfunc_defarg(["s1","s2","s3"]) == ["s1","s2","s3"] ) self.assertTrue( self.pluginobject1.stringlistfunc_defarg(["s1","s2","s3"]) == ["s1","s2","s3"] )
self.assert_( self.pluginobject1.stringlistfunc_defarg() == ["Default1","Default2"] ) self.assertTrue( self.pluginobject1.stringlistfunc_defarg() == ["Default1","Default2"] )
self.assert_( self.pluginobject1.variantfunc_defarg(822.75173) == 822.75173 ) self.assertTrue( self.pluginobject1.variantfunc_defarg(822.75173) == 822.75173 )
self.assert_( self.pluginobject1.variantfunc_defarg() == "MyDefaultVariantString" ) self.assertTrue( self.pluginobject1.variantfunc_defarg() == "MyDefaultVariantString" )
#def testExpectedFailures(self): #def testExpectedFailures(self):
# to less arguments # to less arguments
#self.assertRaises(ValueError, self.pluginobject1.uintfunc) #self.assertRaises(ValueError, self.pluginobject1.uintfunc)
#self.assert_( self.pluginobject1.uintfunc() != 8465 ) #self.assert_( self.pluginobject1.uintfunc() != 8465 )
print "__name__ = %s" % __name__ print("__name__ = %s" % __name__)
#print "self = %s" % self #print "self = %s" % self
#print self.get("TestObject") #print self.get("TestObject")

@ -8,32 +8,32 @@
class TkTest: class TkTest:
def __init__(self): def __init__(self):
import Tkinter import tkinter
self.root = Tkinter.Tk() self.root = tkinter.Tk()
self.root.title("TkTest") self.root.title("TkTest")
self.root.deiconify() self.root.deiconify()
self.mainframe = Tkinter.Frame(self.root) self.mainframe = tkinter.Frame(self.root)
self.mainframe.pack() self.mainframe.pack()
self.button1 = Tkinter.Button(self.mainframe, text="Button1", command=self.callback1) self.button1 = tkinter.Button(self.mainframe, text="Button1", command=self.callback1)
self.button1.pack(side=Tkinter.LEFT) self.button1.pack(side=tkinter.LEFT)
self.button2 = Tkinter.Button(self.mainframe, text="Button2", command=self.callback2) self.button2 = tkinter.Button(self.mainframe, text="Button2", command=self.callback2)
self.button2.pack(side=Tkinter.LEFT) self.button2.pack(side=tkinter.LEFT)
self.exitbutton = Tkinter.Button(self.mainframe, text="Exit", command=self.root.destroy) self.exitbutton = tkinter.Button(self.mainframe, text="Exit", command=self.root.destroy)
self.exitbutton.pack(side=Tkinter.LEFT) self.exitbutton.pack(side=tkinter.LEFT)
self.root.mainloop() self.root.mainloop()
def callback1(self): def callback1(self):
import tkMessageBox import tkinter.messagebox
tkMessageBox.showinfo("Callback1", "Callback1 called.") tkinter.messagebox.showinfo("Callback1", "Callback1 called.")
def callback2(self): def callback2(self):
import tkMessageBox import tkinter.messagebox
tkMessageBox.showinfo("Callback2", "Callback2 called.") tkinter.messagebox.showinfo("Callback2", "Callback2 called.")
class TQtTest: class TQtTest:
def __init__(self): def __init__(self):
@ -41,7 +41,7 @@ class TQtTest:
class Button(qt.TQPushButton): class Button(qt.TQPushButton):
def __init__(self, *args): def __init__(self, *args):
apply(qt.TQPushButton.__init__, (self,) + args) qt.TQPushButton.__init__(*(self,) + args)
class ComboBox(qt.TQHBox): class ComboBox(qt.TQHBox):
def __init__(self, parent, caption, items = []): def __init__(self, parent, caption, items = []):
@ -56,7 +56,7 @@ class TQtTest:
class FileChooser(qt.TQHBox): class FileChooser(qt.TQHBox):
def __init__(self, *args): def __init__(self, *args):
apply(qt.TQHBox.__init__, (self,) + args) qt.TQHBox.__init__(*(self,) + args)
self.defaultfilename = "~/output.html" self.defaultfilename = "~/output.html"
self.setSpacing(6) self.setSpacing(6)
@ -119,7 +119,7 @@ class TQtTest:
qt.TQObject.connect(cancelbutton, qt.SIGNAL("clicked()"), self, qt.SLOT("close()")) qt.TQObject.connect(cancelbutton, qt.SIGNAL("clicked()"), self, qt.SLOT("close()"))
def accept(self): def accept(self):
print "ACCEPTTTTTTTT !!!!!!!!!!!!!!!!!!!!!!!!!!!!" print("ACCEPTTTTTTTT !!!!!!!!!!!!!!!!!!!!!!!!!!!!")
file = qt.TQFile( self.filechooser.file() ) file = qt.TQFile( self.filechooser.file() )
#if not file.exists(): #if not file.exists():
@ -128,13 +128,13 @@ class TQtTest:
# print "File '%s' does exist." % self.filechooser.file() # print "File '%s' does exist." % self.filechooser.file()
def exportButtonClicked(self): def exportButtonClicked(self):
print "Export to HTML !!!!!!!!!!!!!!!!!!!!!!!!!!!!" print("Export to HTML !!!!!!!!!!!!!!!!!!!!!!!!!!!!")
def __getattr__(self, attr): def __getattr__(self, attr):
print "=> Dialog.__getattr__(self,attr)" print("=> Dialog.__getattr__(self,attr)")
#def closeEvent(self, ev): pass #def closeEvent(self, ev): pass
def event(self, e): def event(self, e):
print "=> Dialog.event %s" % e print("=> Dialog.event %s" % e)
#self.deleteLater() #self.deleteLater()
#support.swapThreadState() # calls appropriate c-function #support.swapThreadState() # calls appropriate c-function
return qt.TQDialog.event(self, e) return qt.TQDialog.event(self, e)
@ -143,7 +143,7 @@ class TQtTest:
dialog = Dialog(app.mainWidget(), "Dialog", 1) dialog = Dialog(app.mainWidget(), "Dialog", 1)
dialog.show() dialog.show()
print "################## BEGIN" print("################## BEGIN")
#TkTest() #TkTest()
TQtTest() TQtTest()
print "################## END" print("################## END")

@ -15,36 +15,36 @@ class KexiDBClass:
#import KexiDB #import KexiDB
import krosskexidb import krosskexidb
self.kexidbmodule = krosskexidb self.kexidbmodule = krosskexidb
print "KrossKexiDB version=%s" % self.kexidbmodule.version() print("KrossKexiDB version=%s" % self.kexidbmodule.version())
# Create and remember the drivermanager. # Create and remember the drivermanager.
self.drivermanager = self.kexidbmodule.DriverManager() self.drivermanager = self.kexidbmodule.DriverManager()
# Print informations about the KexiDB module. # Print informations about the KexiDB module.
def printKexiDB(self): def printKexiDB(self):
print "KexiDB = %s %s" % (str(self.kexidbmodule),dir(self.kexidbmodule)) print("KexiDB = %s %s" % (str(self.kexidbmodule),dir(self.kexidbmodule)))
# Each object has __name__ and __doc__ # Each object has __name__ and __doc__
#print "KexiDB.__name__ = %s" % self.kexidbmodule.__name__ #print "KexiDB.__name__ = %s" % self.kexidbmodule.__name__
#print "KexiDB.__doc__ = %s" % self.kexidbmodule.__doc__ #print "KexiDB.__doc__ = %s" % self.kexidbmodule.__doc__
# Print some infos about the drivermanager. # Print some infos about the drivermanager.
print "drivermanager = %s %s" % (self.drivermanager,dir(self.drivermanager)) print("drivermanager = %s %s" % (self.drivermanager,dir(self.drivermanager)))
# The drivermanager holds a list of drivers he supports. # The drivermanager holds a list of drivers he supports.
print "drivermanager.driverNames() = %s" % self.driverNames() print("drivermanager.driverNames() = %s" % self.driverNames())
# Print informations about a driver. # Print informations about a driver.
def printDriverManger(self, driver): def printDriverManger(self, driver):
print "driver = %s %s" % (driver,dir(driver)) print("driver = %s %s" % (driver,dir(driver)))
# Each driver has a version to be able to determinate with what release we are working. # Each driver has a version to be able to determinate with what release we are working.
print "driver.versionMajor() = %s" % driver.versionMajor() print("driver.versionMajor() = %s" % driver.versionMajor())
print "driver.versionMinor() = %s" % driver.versionMinor() print("driver.versionMinor() = %s" % driver.versionMinor())
# Show us what connections are opened right now. # Show us what connections are opened right now.
print "driver.connectionsList() = %s" % str(driver.connectionsList()) print("driver.connectionsList() = %s" % str(driver.connectionsList()))
# Print informations about a connection. # Print informations about a connection.
def printConnection(self, connection): def printConnection(self, connection):
print "connection = %s %s" % (str(connection),dir(connection)) print("connection = %s %s" % (str(connection),dir(connection)))
# Print a list of all avaible databasenames this connection has. # Print a list of all avaible databasenames this connection has.
print "connection.databaseNames() = %s" % connection.databaseNames() print("connection.databaseNames() = %s" % connection.databaseNames())
# Return a list of drivernames. # Return a list of drivernames.
def driverNames(self): def driverNames(self):
@ -65,7 +65,7 @@ class KexiDBClass:
# Fill the new connectiondata object with what we need to connect. # Fill the new connectiondata object with what we need to connect.
connectiondata.setCaption("myFileConnection") connectiondata.setCaption("myFileConnection")
connectiondata.setFileName(filename) connectiondata.setFileName(filename)
print "connectiondata.serverInfoString = %s" % connectiondata.serverInfoString() print("connectiondata.serverInfoString = %s" % connectiondata.serverInfoString())
# Create the connection now. # Create the connection now.
connection = driver.createConnection(connectiondata) connection = driver.createConnection(connectiondata)
# Establish the connection. # Establish the connection.
@ -98,23 +98,23 @@ class KexiDBClass:
def testParser(self, connection, sqlstatement): def testParser(self, connection, sqlstatement):
parser = connection.parser() parser = connection.parser()
if not parser: if not parser:
raise "ERROR in testParser(): Failed to create parser!" raise("ERROR in testParser(): Failed to create parser!")
print "parser.parse = %s" % parser.parse(sqlstatement) print("parser.parse = %s" % parser.parse(sqlstatement))
print "parser.statement = %s" % parser.statement() print("parser.statement = %s" % parser.statement())
print "parser.operation = %s" % parser.operation() print("parser.operation = %s" % parser.operation())
print "parser.table = %s" % parser.table() print("parser.table = %s" % parser.table())
print "parser.query = %s" % parser.query() print("parser.query = %s" % parser.query())
print "parser.connection = %s" % parser.connection() print("parser.connection = %s" % parser.connection())
# Execute the sql query statement and print the single string result. # Execute the sql query statement and print the single string result.
def printQuerySingleString(self, connection, sqlstatement): def printQuerySingleString(self, connection, sqlstatement):
query = myfileconnection.querySingleString("SELECT * FROM table1", 0) query = myfileconnection.querySingleString("SELECT * FROM table1", 0)
print "querySingleString = %s" % query print("querySingleString = %s" % query)
# Execute the sql query statement and print the single stringlist result. # Execute the sql query statement and print the single stringlist result.
def printQueryStringList(self, connection, sqlstatement): def printQueryStringList(self, connection, sqlstatement):
query = myfileconnection.queryStringList("SELECT * FROM table1", 0) query = myfileconnection.queryStringList("SELECT * FROM table1", 0)
print "queryStringList = %s" % query print("queryStringList = %s" % query)
# Walk through the KexiDBCursor and print all item values. # Walk through the KexiDBCursor and print all item values.
def printQueryCursor(self, cursor): def printQueryCursor(self, cursor):
@ -130,7 +130,7 @@ class KexiDBClass:
while(not cursor.eof()): while(not cursor.eof()):
# Print for each item some infos about the fields and there content. # Print for each item some infos about the fields and there content.
for i in range( cursor.fieldCount() ): for i in range( cursor.fieldCount() ):
print "Item='%s' Field='%s' Value='%s'" % (cursor.at(), i, cursor.value(i)) print("Item='%s' Field='%s' Value='%s'" % (cursor.at(), i, cursor.value(i)))
# Move to the next item # Move to the next item
cursor.moveNext() cursor.moveNext()
@ -148,7 +148,7 @@ class KexiDBClass:
field.setType("Text") field.setType("Text")
field.setName(name) field.setName(name)
tableschema.fieldlist().addField(field) tableschema.fieldlist().addField(field)
print "tableschema.fieldlist().fieldCount() = %s" % tableschema.fieldlist().fieldCount() print("tableschema.fieldlist().fieldCount() = %s" % tableschema.fieldlist().fieldCount())
return field return field
# Create a table. # Create a table.
@ -156,7 +156,7 @@ class KexiDBClass:
# First we need a new tableschema. # First we need a new tableschema.
tableschema = self.drivermanager.tableSchema(tablename) tableschema = self.drivermanager.tableSchema(tablename)
self.addField(tableschema, "myfield") self.addField(tableschema, "myfield")
print "connection.createTable = %s" % connection.createTable(tableschema, True) print("connection.createTable = %s" % connection.createTable(tableschema, True))
return tableschema return tableschema
# Drop a table. # Drop a table.
@ -166,7 +166,7 @@ class KexiDBClass:
# Alter the name of a table. # Alter the name of a table.
def alterTableName(self, connection, tablename, newtablename): def alterTableName(self, connection, tablename, newtablename):
tableschema = connection.tableSchema(tablename) tableschema = connection.tableSchema(tablename)
print "alterTableName from=%s to=%s tableschema=%s" % (tablename, newtablename, tableschema) print("alterTableName from=%s to=%s tableschema=%s" % (tablename, newtablename, tableschema))
connection.alterTableName(tableschema, newtablename) connection.alterTableName(tableschema, newtablename)
def testKexiDB(): def testKexiDB():
@ -209,6 +209,6 @@ def testKexiDB():
#del(mydriver) #del(mydriver)
#del(mykexidbclass) #del(mykexidbclass)
print "########## BEGIN TEST: KexiDB ##########" print("########## BEGIN TEST: KexiDB ##########")
testKexiDB() testKexiDB()
print "########## END TEST: KexiDB ##########" print("########## END TEST: KexiDB ##########")

@ -10,7 +10,7 @@ def runner():
testobject1 = krosstestpluginmodule.testpluginobject1() testobject1 = krosstestpluginmodule.testpluginobject1()
def testKexiDB(kexidbfile,drivername,sqlstring): def testKexiDB(kexidbfile,drivername,sqlstring):
print "test kexidb" print("test kexidb")
import krosskexidb import krosskexidb
drivermanager = krosskexidb.DriverManager() drivermanager = krosskexidb.DriverManager()
connectiondata = drivermanager.createConnectionData() connectiondata = drivermanager.createConnectionData()
@ -29,7 +29,7 @@ def runner():
cursor.moveNext() cursor.moveNext()
def test1(): def test1():
print "test1" print("test1")
for i in range(100000): for i in range(100000):
testobject1.func1() testobject1.func1()
testobject1.func1() testobject1.func1()

Loading…
Cancel
Save