Commit 006353b6 authored by Thomas Holder's avatar Thomas Holder

extensions 2to3: ne raise except has_key

parent e05b578f
......@@ -52,7 +52,7 @@ class ColorEffect(inkex.Effect):
if new_val != val:
node.set(attr, new_val)
if node.attrib.has_key('style'):
if 'style' in node.attrib:
# References for style attribute:
# http://www.w3.org/TR/SVG11/styling.html#StyleAttribute,
# http://www.w3.org/TR/CSS21/syndata.html
......@@ -131,7 +131,7 @@ class ColorEffect(inkex.Effect):
for child in newnode:
self.changeStyle(child)
xlink = inkex.addNS('href','xlink')
if newnode.attrib.has_key(xlink):
if xlink in newnode.attrib:
href=newnode.get(xlink)
if href.startswith('#'):
id = href[len('#'):len(href)]
......
......@@ -66,10 +66,10 @@ class SplitIt(inkex.Effect):
dashes = []
offset = 0
style = simplestyle.parseStyle(node.get('style'))
if style.has_key('stroke-dasharray'):
if 'stroke-dasharray' in style:
if style['stroke-dasharray'].find(',') > 0:
dashes = [float (dash) for dash in style['stroke-dasharray'].split(',')]
if style.has_key('stroke-dashoffset'):
if 'stroke-dashoffset' in style:
offset = style['stroke-dashoffset']
if dashes:
p = cubicsuperpath.parsePath(node.get('d'))
......
......@@ -409,7 +409,7 @@ class DPISwitcher(inkex.Effect):
namedview = svg.find(inkex.addNS('namedview', 'sodipodi'))
namedview.set(inkex.addNS('document-units', 'inkscape'), "px")
self.units = self.parse_length(svg.get('width'))[1]
if self.units and self.units <> "px" and self.units <> "" and self.units <> "%":
if self.units and self.units != "px" and self.units != "" and self.units != "%":
if self.options.switcher == "0":
self.unitExponent = 1.0/(self.factor_a/self.__uuconv[self.units])
else:
......
......@@ -262,7 +262,7 @@ def export_DIMENSION():
y = height - scale*(vals[groups['21']][0] - ymin)
size = 12 # default fontsize in px
if vals[groups['3']]:
if DIMTXT.has_key(vals[groups['3']][0]):
if vals[groups['3']][0] in DIMTXT:
size = scale*DIMTXT[vals[groups['3']][0]]
if size < 2:
size = 2
......@@ -428,7 +428,7 @@ else:
desc.text = '%s - scale = %f, origin = (%f, %f), method = %s' % (unicode(args[0], options.input_encode), scale, xmin, ymin, options.scalemethod)
scale *= 96.0/25.4 # convert from mm to pixels
if not layer_nodes.has_key('0'):
if '0' not in layer_nodes:
attribs = {inkex.addNS('groupmode','inkscape'): 'layer', inkex.addNS('label','inkscape'): '0'}
layer_nodes['0'] = inkex.etree.SubElement(doc.getroot(), 'g', attribs)
layer_colors['0'] = 7
......@@ -454,7 +454,7 @@ while line[0] and (line[1] != 'ENDSEC' or not inENTITIES):
inENTITIES = True
elif line[1] == 'POLYLINE':
polylines += 1
if entity and groups.has_key(line[0]):
if entity and line[0] in groups:
seqs.append(line[0]) # list of group codes
if line[0] == '1' or line[0] == '2' or line[0] == '3' or line[0] == '6' or line[0] == '8': # text value
val = line[1].replace('\~', ' ')
......@@ -474,24 +474,24 @@ while line[0] and (line[1] != 'ENDSEC' or not inENTITIES):
else: # unscaled float value
val = float(line[1])
vals[groups[line[0]]].append(val)
elif entities.has_key(line[1]):
if entities.has_key(entity):
elif line[1] in entities:
if entity in entities:
if block != defs: # in a BLOCK
layer = block
elif vals[groups['8']]: # use Common Layer Name
if not vals[groups['8']][0]:
vals[groups['8']][0] = '0' # use default name
if not layer_nodes.has_key(vals[groups['8']][0]):
if vals[groups['8']][0] not in layer_nodes:
attribs = {inkex.addNS('groupmode','inkscape'): 'layer', inkex.addNS('label','inkscape'): '%s' % vals[groups['8']][0]}
layer_nodes[vals[groups['8']][0]] = inkex.etree.SubElement(doc.getroot(), 'g', attribs)
layer = layer_nodes[vals[groups['8']][0]]
color = '#000000' # default color
if vals[groups['8']]:
if layer_colors.has_key(vals[groups['8']][0]):
if colors.has_key(layer_colors[vals[groups['8']][0]]):
if vals[groups['8']][0] in layer_colors:
if layer_colors[vals[groups['8']][0]] in colors:
color = colors[layer_colors[vals[groups['8']][0]]]
if vals[groups['62']]: # Common Color Number
if colors.has_key(vals[groups['62']][0]):
if vals[groups['62']][0] in colors:
color = colors[vals[groups['62']][0]]
style = simplestyle.formatStyle({'stroke': '%s' % color, 'fill': 'none'})
w = 0.5 # default lineweight for POINT
......@@ -502,7 +502,7 @@ while line[0] and (line[1] != 'ENDSEC' or not inENTITIES):
w = 0.5
style = simplestyle.formatStyle({'stroke': '%s' % color, 'fill': 'none', 'stroke-width': '%.1f' % w})
if vals[groups['6']]: # Common Linetype
if linetypes.has_key(vals[groups['6']][0]):
if vals[groups['6']][0] in linetypes:
style += ';' + linetypes[vals[groups['6']][0]]
extrude = 1.0
if vals[groups['230']]:
......
......@@ -194,7 +194,7 @@ class MyEffect(inkex.Effect):
style = node.get('style')
if style:
style = simplestyle.parseStyle(style)
if style.has_key('stroke'):
if 'stroke' in style:
if style['stroke'] and style['stroke'] != 'none' and style['stroke'][0:3] != 'url':
rgb = simplestyle.parseColor(style['stroke'])
hsl = coloreffect.ColorEffect.rgb_to_hsl(coloreffect.ColorEffect(),rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0)
......@@ -286,7 +286,7 @@ class MyEffect(inkex.Effect):
style = group.get('style')
if style:
style = simplestyle.parseStyle(style)
if style.has_key('display'):
if 'display' in style:
if style['display'] == 'none' and self.options.layer_option and self.options.layer_option=='visible':
return
layer = group.get(inkex.addNS('label', 'inkscape'))
......
......@@ -1325,7 +1325,7 @@ def csp_segment_convex_hull(sp1,sp2):
if not (m1 and m2) and m3 : return [c,a,d]
if not (m1 and m3) and m2 : return [b,c,d]
raise ValueError, "csp_segment_convex_hull happened which is something that shouldn't happen!"
raise ValueError("csp_segment_convex_hull happened which is something that shouldn't happen!")
################################################################################
......@@ -1474,7 +1474,7 @@ def atan2(*arg):
return (math.pi/2 - math.atan2(arg[0],arg[1]) ) % math.pi2
else :
raise ValueError, "Bad argumets for atan! (%s)" % arg
raise ValueError("Bad argumets for atan! (%s)" % arg)
def get_text(node) :
value = None
......@@ -2331,11 +2331,11 @@ def biarc(sp1, sp2, z1, z2, depth=0):
elif csmall and a!=0: beta = -b/a
elif not asmall:
discr = b*b-4*a*c
if discr < 0: raise ValueError, (a,b,c,discr)
if discr < 0: raise ValueError(a,b,c,discr)
disq = discr**.5
beta1 = (-b - disq) / 2 / a
beta2 = (-b + disq) / 2 / a
if beta1*beta2 > 0 : raise ValueError, (a,b,c,disq,beta1,beta2)
if beta1*beta2 > 0 : raise ValueError(a,b,c,disq,beta1,beta2)
beta = max(beta1, beta2)
elif asmall and bsmall:
return biarc_split(sp1, sp2, z1, z2, depth)
......@@ -2984,7 +2984,7 @@ class Polygon:
while len(edges)>0 :
poly = []
if loops > len_edges : raise ValueError, "Hull error"
if loops > len_edges : raise ValueError("Hull error")
loops+=1
# Find left most vertex.
start = (1e100,1)
......@@ -2995,7 +2995,7 @@ class Polygon:
loops1 = 0
while (last[1]!=start[0] or first_run) :
first_run = False
if loops1 > len_edges : raise ValueError, "Hull error"
if loops1 > len_edges : raise ValueError("Hull error")
loops1 += 1
next = get_closes_edge_by_angle(edges[last[1]],last)
#draw_pointer(next[0]+next[1],"Green","line", comment=i, width= 1)
......@@ -4894,11 +4894,11 @@ class Gcodetools(inkex.Effect):
elif csmall and a!=0: beta = -b/a
elif not asmall:
discr = b*b-4*a*c
if discr < 0: raise ValueError, (a,b,c,discr)
if discr < 0: raise ValueError(a,b,c,discr)
disq = discr**.5
beta1 = (-b - disq) / 2 / a
beta2 = (-b + disq) / 2 / a
if beta1*beta2 > 0 : raise ValueError, (a,b,c,disq,beta1,beta2)
if beta1*beta2 > 0 : raise ValueError(a,b,c,disq,beta1,beta2)
beta = max(beta1, beta2)
elif asmall and bsmall:
return biarc_split(sp1, sp2, z1, z2, depth)
......@@ -6359,7 +6359,7 @@ G01 Z1 (going to cutting z)\n""",
time_ = l/feed
c1,c2 = self.graffiti_reference_points[layer][0][0],self.graffiti_reference_points[layer][1][0]
d = math.sqrt( (c1[0]-c2[0])**2 + (c1[1]-c2[1])**2 )
if d == 0 : raise ValueError, "Error! Reference points should not be the same!"
if d == 0 : raise ValueError("Error! Reference points should not be the same!")
for i in range(int(time_*emmit+1)) :
t = i/(time_*emmit)
r1,r2 = start[0]*(1-t) + end[0]*t, start[1]*(1-t) + end[1]*t
......
......@@ -183,14 +183,14 @@ class Pattern(inkex.Effect):
# link selected object to pattern
obj = self.selected[self.options.ids[0]]
style = {}
if obj.attrib.has_key('style'):
if 'style' in obj.attrib:
style = simplestyle.parseStyle(obj.attrib['style'])
style['fill'] = 'url(#%s)' % pattern.get('id')
obj.attrib['style'] = simplestyle.formatStyle(style)
if obj.tag == inkex.addNS('g', 'svg'):
for node in obj:
style = {}
if node.attrib.has_key('style'):
if 'style' in node.attrib:
style = simplestyle.parseStyle(node.attrib['style'])
style['fill'] = 'url(#%s)' % pattern.get('id')
node.attrib['style'] = simplestyle.formatStyle(style)
......
......@@ -189,7 +189,7 @@ class Grid_Polar(inkex.Effect):
rmax*sin(angle), rmax*cos(angle),
self.options.a_subdivs_th, 'RadialMinorGridline'+str(i), grid)
if self.options.c_dot_dia <> 0: #if a non-zero diameter, draw the centre dot
if self.options.c_dot_dia != 0: #if a non-zero diameter, draw the centre dot
draw_SVG_circle(self.options.c_dot_dia /2.0,
0, 0, 0, '#000000', 'CentreDot', grid)
......
......@@ -59,7 +59,7 @@ except Exception as inst:
exit(1)
else:
type, value, traceback = sys.exc_info()
raise ValueError, ("", type, value), traceback
raise ValueError("", type, value).with_traceback(traceback)
# issue warning if unknown commands where found
if 'UNKNOWN_COMMANDS' in warnings:
......
......@@ -58,7 +58,7 @@ class HpglOutput(inkex.Effect):
return
else:
type, value, traceback = sys.exc_info()
raise ValueError, ("", type, value), traceback
raise ValueError("", type, value).with_traceback(traceback)
# convert raw HPGL to HPGL
hpglInit = 'IN'
if self.options.force > 0:
......
......@@ -152,7 +152,7 @@ class Interp(inkex.Effect):
sst = copy.deepcopy(styles[sorted_ids[i-1]])
est = copy.deepcopy(styles[sorted_ids[i]])
basestyle = copy.deepcopy(sst)
if basestyle.has_key('stroke-width'):
if 'stroke-width' in basestyle:
basestyle['stroke-width'] = self.tweenstyleunit('stroke-width',sst,est,0)
#prepare for experimental style tweening
......
......@@ -59,7 +59,7 @@ class JessyInk_AutoTexts(inkex.Effect):
elif self.options.autoText == "numberOfSlides":
nodes[0].set("{" + inkex.NSS["jessyink"] + "}autoText","numberOfSlides")
else:
if nodes[0].attrib.has_key("{" + inkex.NSS["jessyink"] + "}autoText"):
if "{" + inkex.NSS["jessyink"] + "}autoText" in nodes[0].attrib:
del nodes[0].attrib["{" + inkex.NSS["jessyink"] + "}autoText"]
# Create effect instance
......
......@@ -55,19 +55,19 @@ class JessyInk_Effects(inkex.Effect):
if (self.options.effectIn == "appear") or (self.options.effectIn == "fade") or (self.options.effectIn == "pop"):
node.set("{" + inkex.NSS["jessyink"] + "}effectIn","name:" + self.options.effectIn + ";order:" + self.options.effectInOrder + ";length:" + str(int(self.options.effectInDuration * 1000)))
# Remove possible view argument.
if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}view"):
if "{" + inkex.NSS["jessyink"] + "}view" in node.attrib:
del node.attrib["{" + inkex.NSS["jessyink"] + "}view"]
else:
if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}effectIn"):
if "{" + inkex.NSS["jessyink"] + "}effectIn" in node.attrib:
del node.attrib["{" + inkex.NSS["jessyink"] + "}effectIn"]
if (self.options.effectOut == "appear") or (self.options.effectOut == "fade") or (self.options.effectOut == "pop"):
node.set("{" + inkex.NSS["jessyink"] + "}effectOut","name:" + self.options.effectOut + ";order:" + self.options.effectOutOrder + ";length:" + str(int(self.options.effectOutDuration * 1000)))
# Remove possible view argument.
if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}view"):
if "{" + inkex.NSS["jessyink"] + "}view" in node.attrib:
del node.attrib["{" + inkex.NSS["jessyink"] + "}view"]
else:
if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}effectOut"):
if "{" + inkex.NSS["jessyink"] + "}effectOut" in node.attrib:
del node.attrib["{" + inkex.NSS["jessyink"] + "}effectOut"]
# Create effect instance
......
......@@ -53,7 +53,7 @@ def dictToPropStr(dictio):
def setStyle(node, propKey, propValue):
props = {}
if node.attrib.has_key("style"):
if "style" in node.attrib:
props = propStrToDict(node.get("style"))
props[propKey] = propValue
......
......@@ -97,7 +97,7 @@ class JessyInk_Summary(inkex.Effect):
if transitionInAttribute:
transInDict = propListToDict(propStrToList(transitionInAttribute))
if (transInDict["name"] != "appear") and transInDict.has_key("length"):
if (transInDict["name"] != "appear") and "length" in transInDict:
inkex.errormsg(_("{0}Transition in: {1} ({2!s} s)").format(prefix, transInDict["name"], int(transInDict["length"]) / 1000.0))
else:
inkex.errormsg(_("{0}Transition in: {1}").format(prefix, transInDict["name"]))
......@@ -106,7 +106,7 @@ class JessyInk_Summary(inkex.Effect):
if transitionOutAttribute:
transOutDict = propListToDict(propStrToList(transitionOutAttribute))
if (transOutDict["name"] != "appear") and transOutDict.has_key("length"):
if (transOutDict["name"] != "appear") and "length" in transOutDict:
inkex.errormsg(_("{0}Transition out: {1} ({2!s} s)").format(prefix, transOutDict["name"], int(transOutDict["length"]) / 1000.0))
else:
inkex.errormsg(_("{0}Transition out: {1}").format(prefix, transOutDict["name"]))
......@@ -130,7 +130,7 @@ class JessyInk_Summary(inkex.Effect):
dictio["id"] = effectNode.get("id")
dictio["type"] = "effect"
if not effects.has_key(dictio["order"]):
if dictio["order"] not in effects:
effects[dictio["order"]] = []
effects[dictio["order"]].append(dictio)
......@@ -141,7 +141,7 @@ class JessyInk_Summary(inkex.Effect):
dictio["id"] = effectNode.get("id")
dictio["type"] = "effect"
if not effects.has_key(dictio["order"]):
if dictio["order"] not in effects:
effects[dictio["order"]] = []
effects[dictio["order"]].append(dictio)
......@@ -151,7 +151,7 @@ class JessyInk_Summary(inkex.Effect):
dictio["id"] = viewNode.get("id")
dictio["type"] = "view"
if not effects.has_key(dictio["order"]):
if dictio["order"] not in effects:
effects[dictio["order"]] = []
effects[dictio["order"]].append(dictio)
......@@ -182,7 +182,7 @@ class JessyInk_Summary(inkex.Effect):
if item["name"] != "appear":
tmpStr += _(" using effect \"{0}\"").format(item["name"])
if item.has_key("length"):
if "length" in item:
tmpStr += _(" in {0!s} s").format(int(item["length"]) / 1000.0)
inkex.errormsg(tmpStr + ".\n")
......
......@@ -86,15 +86,15 @@ def findInternalLinks(node, docRoot, nodeDict = {}):
for entry in re.findall("url\(#.*\)", etree.tostring(node)):
linkId = entry[5:len(entry) - 1]
if not nodeDict.has_key(linkId):
if linkId not in nodeDict:
nodeDict[linkId] = deepcopy(docRoot.xpath("//*[@id='" + linkId + "']", namespaces=inkex.NSS)[0])
nodeDict = findInternalLinks(nodeDict[linkId], docRoot, nodeDict)
for entry in node.iter():
if entry.attrib.has_key('{' + inkex.NSS['xlink'] + '}href'):
if '{' + inkex.NSS['xlink'] + '}href' in entry.attrib:
linkId = entry.attrib['{' + inkex.NSS['xlink'] + '}href'][1:len(entry.attrib['{' + inkex.NSS['xlink'] + '}href'])]
if not nodeDict.has_key(linkId):
if linkId not in nodeDict:
nodeDict[linkId] = deepcopy(docRoot.xpath("//*[@id='" + linkId + "']", namespaces=inkex.NSS)[0])
nodeDict = findInternalLinks(nodeDict[linkId], docRoot, nodeDict)
......@@ -112,7 +112,7 @@ def getNewId(prefix, docRoot):
def deleteIds(node):
for entry in node.iter():
if entry.attrib.has_key('id'):
if 'id' in entry.attrib:
del entry.attrib['id']
# Create effect instance
......
......@@ -90,13 +90,13 @@ class JessyInk_Effects(inkex.Effect):
rect.set("{" + inkex.NSS["jessyink"] + "}view","name:view;order:" + self.options.viewOrder + ";length:" + str(int(self.options.viewDuration * 1000)))
# Remove possible effect arguments.
if rect.attrib.has_key("{" + inkex.NSS["jessyink"] + "}effectIn"):
if "{" + inkex.NSS["jessyink"] + "}effectIn" in rect.attrib:
del rect.attrib["{" + inkex.NSS["jessyink"] + "}effectIn"]
if rect.attrib.has_key("{" + inkex.NSS["jessyink"] + "}effectOut"):
if "{" + inkex.NSS["jessyink"] + "}effectOut" in rect.attrib:
del rect.attrib["{" + inkex.NSS["jessyink"] + "}effectOut"]
else:
if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}view"):
if "{" + inkex.NSS["jessyink"] + "}view" in node.attrib:
del node.attrib["{" + inkex.NSS["jessyink"] + "}view"]
# Create effect instance
......
......@@ -123,7 +123,7 @@ class MyEffect(inkex.Effect):
stroke = "none";
for mprop in mprops:
if style.has_key(mprop) and style[mprop] != 'none'and style[mprop][:5] == 'url(#':
if mprop in style and style[mprop] != 'none'and style[mprop][:5] == 'url(#':
marker_id = style[mprop][5:-1]
try:
......
......@@ -56,7 +56,7 @@ class Style(dict):
def add(self, c, el):
self.total.append( (c, el) )
for name,value in c.iteritems():
if not self.has_key(name):
if name not in self:
self[name] = value
if self[name] == value:
self.weights[name] += 1
......@@ -76,7 +76,7 @@ class Style(dict):
def __eq__(self, o):
"""Not equals, prefer to overload 'in' but that doesn't seem possible"""
for arg in self.keys():
if o.has_key(arg) and self[arg] != o[arg]:
if arg in o and self[arg] != o[arg]:
return False
return True
......@@ -122,7 +122,7 @@ class MergeStyles(inkex.Effect):
st.remove(common.keys())
el.attrib['style'] = st.to_str("")
olds = el.attrib.has_key('class') and el.attrib['class'].split() or []
olds = 'class' in el.attrib and el.attrib['class'].split() or []
if newclass not in olds:
olds.append(newclass)
el.attrib['class'] = ' '.join(olds)
......
......@@ -129,7 +129,7 @@ class PathModifier(inkex.Effect):
newNode = self.document.getroot().xpath(path, namespaces=inkex.NSS)[0]
return newNode
else:
raise AssertionError, "Trying to follow empty xlink.href attribute."
raise AssertionError("Trying to follow empty xlink.href attribute.")
def unlinkClone(self,node,doReplace):
if node.tag == inkex.addNS('use','svg') or node.tag=='use':
......@@ -144,7 +144,7 @@ class PathModifier(inkex.Effect):
return newNode
else:
raise AssertionError, "Only clones can be unlinked..."
raise AssertionError("Only clones can be unlinked...")
......
......@@ -470,7 +470,7 @@ class PixelSnapEffect(inkex.Effect):
for e in elem:
try:
self.pixel_snap(e, transform)
except TransformError, e:
except TransformError as e:
print >>sys.stderr, e
return
......@@ -480,7 +480,7 @@ class PixelSnapEffect(inkex.Effect):
self.snap_transform(elem)
try:
self.snap_stroke(elem, parent_transform)
except TransformError, e:
except TransformError as e:
print >>sys.stderr, e
if elemtype(elem, 'path'):
......@@ -498,7 +498,7 @@ class PixelSnapEffect(inkex.Effect):
for id, elem in self.selected.iteritems():
try:
self.pixel_snap(elem)
except TransformError, e:
except TransformError as e:
print >>sys.stderr, e
......
......@@ -69,7 +69,7 @@ class Plot(inkex.Effect):
return 1
else:
type, value, traceback = sys.exc_info()
raise ValueError, ('', type, value), traceback
raise ValueError('', type, value).with_traceback(traceback)
# TODO: Get preview to work. This requires some work on the C++ side to be able to determine if it is
# a preview or a final run. (Remember to set <effect needs-live-preview='false'> to true)
'''
......@@ -142,7 +142,7 @@ class Plot(inkex.Effect):
# gracefully exit script when pySerial is missing
try:
import serial
except ImportError, e:
except ImportError as e:
inkex.errormsg(_("pySerial is not installed. Please follow these steps:")
+ "\n\n" + _("1. Download and extract (unzip) this file to your local harddisk:")
+ "\n" + " https://pypi.python.org/packages/source/p/pyserial/pyserial-2.7.tar.gz"
......@@ -201,7 +201,7 @@ class Plot(inkex.Effect):
return
else:
type, value, traceback = sys.exc_info()
raise ValueError, ('', type, value), traceback
raise ValueError('', type, value).with_traceback(traceback)
# send data to plotter
mySerial.write(self.hpgl)
mySerial.read(2)
......
......@@ -58,13 +58,13 @@ class MyEffect(inkex.Effect):
style = node.get('style')
if style:
style = simplestyle.parseStyle(style)
if style.has_key('stroke'):
if 'stroke' in style:
if style['stroke'] and style['stroke'] != 'none' and style['stroke'][0:3] != 'url':
rgb = simplestyle.parseColor(style['stroke'])
if style.has_key('stroke-width'):
if 'stroke-width' in style:
stroke = self.unittouu(style['stroke-width'])/self.unittouu('1px')
stroke = int(stroke*self.scale)
if style.has_key('fill'):
if 'fill' in style:
if style['fill'] and style['fill'] != 'none' and style['fill'][0:3] != 'url':
fill = simplestyle.parseColor(style['fill'])
fillcolor = fill[0] + 256*fill[1] + 256*256*fill[2]
......@@ -152,7 +152,7 @@ class MyEffect(inkex.Effect):
style = group.get('style')
if style:
style = simplestyle.parseStyle(style)
if style.has_key('display'):
if 'display' in style:
if style['display'] == 'none' and self.visibleLayers:
return
trans = group.get('transform')
......
......@@ -328,7 +328,7 @@ def randomize_input_string(tokens, zoom ): # generate a glyph starting fr
for i in range(0,len(tokens)):
char = tokens[i]
#if ( re.match("[a-zA-Z0-9?]", char)):
if ( alphabet.has_key(char)):
if ( char in alphabet):
if ((i > 0) and (char == tokens[i-1])): # if this letter matches previous letter
imagelist.append(imagelist[len(stack)-1])# make them the same image
else: # generate image for letter
......
......@@ -66,7 +66,7 @@ def run(command_format, prog_name):
msg = "%s failed:\n%s\n%s\n" % (prog_name, out, err)
elif err:
sys.stderr.write("%s executed but logged the following error:\n%s\n%s\n" % (prog_name, out, err))
except Exception, inst:
except Exception as inst:
msg = "Error attempting to run %s: %s" % (prog_name, str(inst))
# If successful, copy the output file to stdout.
......@@ -79,7 +79,7 @@ def run(command_format, prog_name):
data = f.read()
sys.stdout.write(data)
f.close()
except IOError, inst:
except IOError as inst:
msg = "Error reading temporary file: %s" % str(inst)
# Clean up.
......
......@@ -48,7 +48,7 @@ def lexPath(d):
offset = m.end()
continue
#TODO: create new exception
raise Exception, 'Invalid path data!'
raise Exception('Invalid path data!')
'''
pathdefs = {commandfamily:
[
......@@ -93,7 +93,7 @@ def parsePath(d):
needParam = True
if isCommand:
if not lastCommand and token.upper() != 'M':
raise Exception, 'Invalid path, must begin with moveto.'
raise Exception('Invalid path, must begin with moveto.')
else:
command = token
else:
......@@ -106,16 +106,16 @@ def parsePath(d):
else:
command = pathdefs[lastCommand.upper()][0].lower()
else:
raise Exception, 'Invalid path, no initial command.'
raise Exception('Invalid path, no initial command.')
numParams = pathdefs[command.upper()][1]
while numParams > 0:
if needParam:
try:
token, isCommand = lexer.next()
if isCommand:
raise Exception, 'Invalid number of parameters'
raise Exception('Invalid number of parameters')
except StopIteration:
raise Exception, 'Unexpected end of path'
raise Exception('Unexpected end of path')
cast = pathdefs[command.upper()][2][-numParams]
param = cast(token)
if command.islower():
......
......@@ -131,7 +131,7 @@ def applyTransformToPath(mat,path):
def fuseTransform(node):
if node.get('d')==None:
#FIXME: how do you raise errors?
raise AssertionError, 'can not fuse "transform" of elements that have no "d" attribute'
raise AssertionError('can not fuse "transform" of elements that have no "d" attribute')
t = node.get("transform")
if t == None:
return
......
......@@ -160,12 +160,12 @@ class CompressedMediaOutput(inkex.Effect):
if not s:
return fonts
if s.has_key('font-family'):
if s.has_key('font-weight'):
if 'font-family' in s:
if 'font-weight' in s:
fonts.append(s['font-family'] + ' ' + s['font-weight'])
else:
fonts.append(s['font-family'])
elif s.has_key('-inkscape-font-specification'):
elif '-inkscape-font-specification' in s:
fonts.append(s['-inkscape-font-specification'])
return fonts
......
......@@ -204,11 +204,11 @@ def paramType(layer, param, value=None):
if param in layer_params.keys():
return layer_params[param][0]
else:
raise Exception, "Invalid parameter type for layer"
raise Exception("Invalid parameter type for layer")
else:
# Unknown layer, try to determine parameter type based on value
if value is None:
raise Exception, "No information for given layer"
raise Exception("No information for given layer")
if type(value) == int:
return "integer"
elif type(value) == float:
......@@ -221,7 +221,7 @@ def paramType(layer, param, value=None):
elif 0.0 in value.keys():
return "gradient"
else:
raise Exception, "Could not automatically determine parameter type"
raise Exception("Could not automatically determine parameter type")
elif type(value) == list:
if len(value) == 2:
return "vector"
......
......@@ -393,7 +393,7 @@ class SynfigDocument(object):
for layer in value:
el.append(layer)