Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

PEP8: E501 line too long

  • Loading branch information...
commit fd3a8cadf3a46c08023e4d083a7ab9a791a8c206 1 parent 8dc79ba
Dwayne Bailey dwaynebailey authored
30 translate/misc/dictutils.py
... ... @@ -1,7 +1,8 @@
1 1 #!/usr/bin/env python
2 2 # -*- coding: utf-8 -*-
3 3
4   -"""Implements a case-insensitive (on keys) dictionary and order-sensitive dictionary"""
  4 +"""Implements a case-insensitive (on keys) dictionary and
  5 +order-sensitive dictionary"""
5 6
6 7 # Copyright 2002, 2003 St James Software
7 8 #
@@ -37,7 +38,8 @@ def __init__(self, fromdict=None):
37 38
38 39 def __getitem__(self, key):
39 40 if type(key) != str and type(key) != unicode:
40   - raise TypeError("cidict can only have str or unicode as key (got %r)" % type(key))
  41 + raise TypeError("cidict can only have str or unicode as key (got %r)" %
  42 + type(key))
41 43 for akey in self.iterkeys():
42 44 if akey.lower() == key.lower():
43 45 return dict.__getitem__(self, akey)
@@ -45,20 +47,23 @@ def __getitem__(self, key):
45 47
46 48 def __setitem__(self, key, value):
47 49 if type(key) != str and type(key) != unicode:
48   - raise TypeError("cidict can only have str or unicode as key (got %r)" % type(key))
  50 + raise TypeError("cidict can only have str or unicode as key (got %r)" %
  51 + type(key))
49 52 for akey in self.iterkeys():
50 53 if akey.lower() == key.lower():
51 54 return dict.__setitem__(self, akey, value)
52 55 return dict.__setitem__(self, key, value)
53 56
54 57 def update(self, updatedict):
55   - """D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]"""
  58 + """D.update(E) -> None.
  59 + Update D from E: for k in E.keys(): D[k] = E[k]"""
56 60 for key, value in updatedict.iteritems():
57 61 self[key] = value
58 62
59 63 def __delitem__(self, key):
60 64 if type(key) != str and type(key) != unicode:
61   - raise TypeError("cidict can only have str or unicode as key (got %r)" % type(key))
  65 + raise TypeError("cidict can only have str or unicode as key (got %r)" %
  66 + type(key))
62 67 for akey in self.iterkeys():
63 68 if akey.lower() == key.lower():
64 69 return dict.__delitem__(self, akey)
@@ -66,7 +71,8 @@ def __delitem__(self, key):
66 71
67 72 def __contains__(self, key):
68 73 if type(key) != str and type(key) != unicode:
69   - raise TypeError("cidict can only have str or unicode as key (got %r)" % type(key))
  74 + raise TypeError("cidict can only have str or unicode as key (got %r)" %
  75 + type(key))
70 76 for akey in self.iterkeys():
71 77 if akey.lower() == key.lower():
72 78 return 1
@@ -83,14 +89,16 @@ def get(self, key, default=None):
83 89
84 90
85 91 class ordereddict(dict):
86   - """a dictionary which remembers its keys in the order in which they were given"""
  92 + """a dictionary which remembers its keys in the order in which they
  93 + were given"""
87 94
88 95 def __init__(self, *args):
89 96 if len(args) == 0:
90 97 super(ordereddict, self).__init__()
91 98 self.order = []
92 99 elif len(args) > 1:
93   - raise TypeError("ordereddict() takes at most 1 argument (%d given)" % len(args))
  100 + raise TypeError("ordereddict() takes at most 1 argument (%d given)" %
  101 + len(args))
94 102 else:
95 103 initarg = args[0]
96 104 apply(super(ordereddict, self).__init__, args)
@@ -113,7 +121,8 @@ def __setitem__(self, key, value):
113 121 return result
114 122
115 123 def update(self, updatedict):
116   - """D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]"""
  124 + """D.update(E) -> None.
  125 + Update D from E: for k in E.keys(): D[k] = E[k]"""
117 126 for key, value in updatedict.iteritems():
118 127 self[key] = value
119 128
@@ -156,7 +165,8 @@ def keys(self):
156 165 return self.order[:]
157 166
158 167 def popitem(self):
159   - """D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty"""
  168 + """D.popitem() -> (k, v), remove and return some (key, value) pair
  169 + as a 2-tuple; but raise KeyError if D is empty"""
160 170 if len(self.order) == 0:
161 171 raise KeyError("popitem(): ordered dictionary is empty")
162 172 k = self.order.pop()
7 translate/misc/file_discovery.py
@@ -26,8 +26,8 @@
26 26
27 27
28 28 def get_abs_data_filename(path_parts, basedirs=None):
29   - """Get the absolute path to the given file- or directory name in the current
30   - running application's data directory.
  29 + """Get the absolute path to the given file- or directory name in the
  30 + current running application's data directory.
31 31
32 32 :type path_parts: list
33 33 :param path_parts: The path parts that can be joined by ``os.path.join()``.
@@ -61,7 +61,8 @@ def get_abs_data_filename(path_parts, basedirs=None):
61 61
62 62 for basepath, data_dir in ((x, y) for x in BASE_DIRS for y in DATA_DIRS):
63 63 dir_and_filename = data_dir + path_parts
64   - datafile = os.path.join(basepath or os.path.dirname(__file__), *dir_and_filename)
  64 + datafile = os.path.join(basepath or os.path.dirname(__file__),
  65 + *dir_and_filename)
65 66 if os.path.exists(datafile):
66 67 return datafile
67 68 raise Exception('Could not find "%s"' % (os.path.join(*path_parts)))
9 translate/misc/lru.py
@@ -31,7 +31,8 @@ class LRUCachingDict(WeakValueDictionary):
31 31 maxsize is reached.
32 32 """
33 33
34   - def __init__(self, maxsize, cullsize=2, peakmult=10, aggressive_gc=True, *args, **kwargs):
  34 + def __init__(self, maxsize, cullsize=2, peakmult=10, aggressive_gc=True,
  35 + *args, **kwargs):
35 36 self.cullsize = max(2, cullsize)
36 37 self.maxsize = max(cullsize, maxsize)
37 38 self.aggressive_gc = aggressive_gc
@@ -81,7 +82,8 @@ def __setitem__(self, key, value):
81 82 # appended again
82 83 self.queue.pop()
83 84
84   - if len(self) >= self.maxsize or len(self.queue) >= self.maxsize * self.peakmult:
  85 + if (len(self) >= self.maxsize or
  86 + len(self.queue) >= self.maxsize * self.peakmult):
85 87 self.cull()
86 88
87 89 self.queue.append((key, value))
@@ -97,7 +99,8 @@ def __getitem__(self, key):
97 99
98 100 # only append if item is not at right end of queue
99 101 if not (len(self.queue) and self.queue[-1][0] == key):
100   - if len(self) >= self.maxsize or len(self.queue) >= self.maxsize * self.peakmult:
  102 + if (len(self) >= self.maxsize or
  103 + len(self.queue) >= self.maxsize * self.peakmult):
101 104 self.cull()
102 105 self.queue.append((key, value))
103 106
18 translate/misc/multistring.py
@@ -18,7 +18,8 @@
18 18 # You should have received a copy of the GNU General Public License
19 19 # along with this program; if not, see <http://www.gnu.org/licenses/>.
20 20
21   -"""Supports a hybrid Unicode string that can also have a list of alternate strings in the strings attribute"""
  21 +"""Supports a hybrid Unicode string that can also have a list of alternate
  22 +strings in the strings attribute"""
22 23
23 24 from translate.misc import autoencode
24 25
@@ -30,10 +31,12 @@ def __new__(newtype, string=u"", encoding=None, errors=None):
30 31 if not string:
31 32 raise ValueError("multistring must contain at least one string")
32 33 mainstring = string[0]
33   - newstring = multistring.__new__(newtype, string[0], encoding, errors)
  34 + newstring = multistring.__new__(newtype, string[0],
  35 + encoding, errors)
34 36 newstring.strings = [newstring] + [autoencode.autoencode.__new__(autoencode.autoencode, altstring, encoding, errors) for altstring in string[1:]]
35 37 else:
36   - newstring = autoencode.autoencode.__new__(newtype, string, encoding, errors)
  38 + newstring = autoencode.autoencode.__new__(newtype, string,
  39 + encoding, errors)
37 40 newstring.strings = [newstring]
38 41 return newstring
39 42
@@ -67,14 +70,17 @@ def __eq__(self, otherstring):
67 70 return self.__cmp__(otherstring) == 0
68 71
69 72 def __repr__(self):
70   - parts = [autoencode.autoencode.__repr__(self)] + [repr(a) for a in self.strings[1:]]
  73 + parts = [autoencode.autoencode.__repr__(self)] + \
  74 + [repr(a) for a in self.strings[1:]]
71 75 return "multistring([" + ",".join(parts) + "])"
72 76
73 77 def replace(self, old, new, count=None):
74 78 if count is None:
75   - newstr = multistring(super(multistring, self).replace(old, new), self.encoding)
  79 + newstr = multistring(super(multistring, self) \
  80 + .replace(old, new), self.encoding)
76 81 else:
77   - newstr = multistring(super(multistring, self).replace(old, new, count), self.encoding)
  82 + newstr = multistring(super(multistring, self) \
  83 + .replace(old, new, count), self.encoding)
78 84 for s in self.strings[1:]:
79 85 if count is None:
80 86 newstr.strings.append(s.replace(old, new))
69 translate/misc/optrecurse.py
@@ -329,7 +329,8 @@ def seterrorleveloptions(self):
329 329 errorleveloption = optparse.Option(None, "--errorlevel",
330 330 dest="errorlevel", default="message",
331 331 choices=self.errorleveltypes, metavar="ERRORLEVEL",
332   - help="show errorlevel as: %s" % (", ".join(self.errorleveltypes)))
  332 + help="show errorlevel as: %s" % \
  333 + (", ".join(self.errorleveltypes)))
333 334 self.define_option(errorleveloption)
334 335
335 336 def getformathelp(self, formats):
@@ -417,11 +418,14 @@ def getoutputoptions(self, options, inputpath, templatepath):
417 418 if inputext is None:
418 419 raise ValueError("don't know what to do with input format (no file extension), no template file")
419 420 elif templateext is None:
420   - raise ValueError("don't know what to do with input format %s, no template file" % (os.extsep + inputext))
  421 + raise ValueError("don't know what to do with input format %s, no template file" %
  422 + (os.extsep + inputext))
421 423 else:
422   - raise ValueError("don't know what to do with input format %s, template format %s" % (os.extsep + inputext, os.extsep + templateext))
  424 + raise ValueError("don't know what to do with input format %s, template format %s" %
  425 + (os.extsep + inputext, os.extsep + templateext))
423 426 else:
424   - raise ValueError("don't know what to do with input format %s" % os.extsep + inputext)
  427 + raise ValueError("don't know what to do with input format %s" %
  428 + (os.extsep + inputext))
425 429 if outputformat == "*":
426 430 if inputext:
427 431 outputformat = inputext
@@ -432,11 +436,14 @@ def getoutputoptions(self, options, inputpath, templatepath):
432 436 else:
433 437 if self.usetemplates:
434 438 if templateext is None:
435   - raise ValueError("don't know what to do with input format %s, no template file" % (os.extsep + inputext))
  439 + raise ValueError("don't know what to do with input format %s, no template file" %
  440 + (os.extsep + inputext))
436 441 else:
437   - raise ValueError("don't know what to do with input format %s, template format %s" % (os.extsep + inputext, os.extsep + templateext))
  442 + raise ValueError("don't know what to do with input format %s, template format %s" %
  443 + (os.extsep + inputext, os.extsep + templateext))
438 444 else:
439   - raise ValueError("don't know what to do with input format %s" % os.extsep + inputext)
  445 + raise ValueError("don't know what to do with input format %s" %
  446 + (os.extsep + inputext))
440 447 return outputformat, fileprocessor
441 448
442 449 def initprogressbar(self, allfiles, options):
@@ -465,7 +472,8 @@ def getfulltemplatepath(self, options, templatepath):
465 472 """Gets the absolute path to a template file."""
466 473 if not options.recursivetemplate:
467 474 return templatepath
468   - elif templatepath is not None and self.usetemplates and options.template:
  475 + elif (templatepath is not None and
  476 + self.usetemplates and options.template):
469 477 return os.path.join(options.template, templatepath)
470 478 else:
471 479 return None
@@ -502,20 +510,26 @@ def recursiveprocess(self, options):
502 510 options.input = os.path.dirname(options.input)
503 511 else:
504 512 inputfiles = [options.input]
505   - options.recursiveoutput = self.isrecursive(options.output, 'output') and getattr(options, "allowrecursiveoutput", True)
506   - options.recursivetemplate = self.usetemplates and self.isrecursive(options.template, 'template') and getattr(options, "allowrecursivetemplate", True)
  513 + options.recursiveoutput = (self.isrecursive(options.output, 'output') and
  514 + getattr(options, "allowrecursiveoutput", True))
  515 + options.recursivetemplate = (self.usetemplates and
  516 + self.isrecursive(options.template, 'template') and
  517 + getattr(options, "allowrecursivetemplate", True))
507 518 self.initprogressbar(inputfiles, options)
508 519 for inputpath in inputfiles:
509 520 try:
510 521 templatepath = self.gettemplatename(options, inputpath)
511 522 # If we have a recursive template, but the template doesn't
512 523 # have this input file, let's drop it.
513   - if options.recursivetemplate and templatepath is None and not self.allowmissingtemplate:
514   - self.warning("No template at %s. Skipping %s." % (templatepath, inputpath))
  524 + if (options.recursivetemplate and templatepath is None and
  525 + not self.allowmissingtemplate):
  526 + self.warning("No template at %s. Skipping %s." %
  527 + (templatepath, inputpath))
515 528 continue
516 529 outputformat, fileprocessor = self.getoutputoptions(options, inputpath, templatepath)
517 530 fullinputpath = self.getfullinputpath(options, inputpath)
518   - fulltemplatepath = self.getfulltemplatepath(options, templatepath)
  531 + fulltemplatepath = self.getfulltemplatepath(options,
  532 + templatepath)
519 533 outputpath = self.getoutputname(options, inputpath, outputformat)
520 534 fulloutputpath = self.getfulloutputpath(options, outputpath)
521 535 if options.recursiveoutput and outputpath:
@@ -523,7 +537,8 @@ def recursiveprocess(self, options):
523 537 except Exception, error:
524 538 if isinstance(error, KeyboardInterrupt):
525 539 raise
526   - self.warning("Couldn't handle input file %s" % inputpath, options, sys.exc_info())
  540 + self.warning("Couldn't handle input file %s" %
  541 + inputpath, options, sys.exc_info())
527 542 continue
528 543 try:
529 544 success = self.processfile(fileprocessor, options,
@@ -532,7 +547,9 @@ def recursiveprocess(self, options):
532 547 except Exception, error:
533 548 if isinstance(error, KeyboardInterrupt):
534 549 raise
535   - self.warning("Error processing: input %s, output %s, template %s" % (fullinputpath, fulloutputpath, fulltemplatepath), options, sys.exc_info())
  550 + self.warning("Error processing: input %s, output %s, template %s" %
  551 + (fullinputpath, fulloutputpath,
  552 + fulltemplatepath), options, sys.exc_info())
536 553 success = False
537 554 self.reportprogress(inputpath, success)
538 555 del self.progressbar
@@ -574,7 +591,8 @@ def processfile(self, fileprocessor, options, fullinputpath,
574 591 fulloutputpath, fulltemplatepath):
575 592 """Process an individual file."""
576 593 inputfile = self.openinputfile(options, fullinputpath)
577   - if fulloutputpath and fulloutputpath in (fullinputpath, fulltemplatepath):
  594 + if (fulloutputpath and
  595 + fulloutputpath in (fullinputpath, fulltemplatepath)):
578 596 outputfile = self.opentempoutputfile(options, fulloutputpath)
579 597 tempoutput = True
580 598 else:
@@ -586,7 +604,8 @@ def processfile(self, fileprocessor, options, fullinputpath,
586 604 **passthroughoptions):
587 605 if tempoutput:
588 606 self.warning("writing to temporary output...")
589   - self.finalizetempoutputfile(options, outputfile, fulloutputpath)
  607 + self.finalizetempoutputfile(options, outputfile,
  608 + fulloutputpath)
590 609 return True
591 610 else:
592 611 # remove the file if it is a file (could be stdout etc)
@@ -603,7 +622,8 @@ def reportprogress(self, filename, success):
603 622 def mkdir(self, parent, subdir):
604 623 """Makes a subdirectory (recursively if neccessary)."""
605 624 if not os.path.isdir(parent):
606   - raise ValueError("cannot make child directory %r if parent %r does not exist" % (subdir, parent))
  625 + raise ValueError("cannot make child directory %r if parent %r does not exist" %
  626 + (subdir, parent))
607 627 currentpath = parent
608 628 subparts = subdir.split(os.sep)
609 629 for part in subparts:
@@ -628,7 +648,8 @@ def isexcluded(self, options, inputpath):
628 648
629 649 def recurseinputfilelist(self, options):
630 650 """Use a list of files, and find a common base directory for them."""
631   - # find a common base directory for the files to do everything relative to
  651 + # find a common base directory for the files to do everything
  652 + # relative to
632 653 commondir = os.path.dirname(os.path.commonprefix(options.input))
633 654 inputfiles = []
634 655 for inputfile in options.input:
@@ -642,7 +663,7 @@ def recurseinputfilelist(self, options):
642 663 return inputfiles
643 664
644 665 def recurseinputfiles(self, options):
645   - """Recurse through directories and return files to be processed..."""
  666 + """Recurse through directories and return files to be processed."""
646 667 dirstack = ['']
647 668 join = os.path.join
648 669 inputfiles = []
@@ -660,10 +681,11 @@ def recurseinputfiles(self, options):
660 681 dirs.append(inputpath)
661 682 elif os.path.isfile(fullinputpath):
662 683 if not self.isvalidinputname(options, name):
663   - # only handle names that match recognized input file extensions
  684 + # only handle names that match recognized input
  685 + # file extensions
664 686 continue
665 687 inputfiles.append(inputpath)
666   - # make sure the directories are processed next time round...
  688 + # make sure the directories are processed next time round.
667 689 dirs.reverse()
668 690 dirstack.extend(dirs)
669 691 return inputfiles
@@ -733,4 +755,5 @@ def getoutputname(self, options, inputname, outputformat):
733 755 def isvalidinputname(self, options, inputname):
734 756 """Checks if this is a valid input filename."""
735 757 inputbase, inputext = self.splitinputext(inputname)
736   - return (inputext in options.inputformats) or ("*" in options.inputformats)
  758 + return ((inputext in options.inputformats) or
  759 + ("*" in options.inputformats))
25 translate/misc/ourdom.py
@@ -30,12 +30,14 @@
30 30 from xml.dom import minidom
31 31 from xml.dom import expatbuilder
32 32
33   -# helper functions we use to do xml the way we want, used by modified classes below
  33 +# helper functions we use to do xml the way we want, used by modified
  34 +# classes below
34 35
35 36
36 37 def writexml_helper(self, writer, indent="", addindent="", newl=""):
37 38 """A replacement for writexml that formats it like typical XML files.
38   - Nodes are intendented but text nodes, where whitespace can be significant, are not indented."""
  39 + Nodes are intendented but text nodes, where whitespace can be
  40 + significant, are not indented."""
39 41 # indent = current indentation
40 42 # addindent = indentation to add to higher levels
41 43 # newl = newline string
@@ -84,8 +86,8 @@ def getElementsByTagName_helper(parent, name, dummy=None):
84 86 list, therefore, the class below exposes this through yieldElementsByTagName"""
85 87
86 88 for node in parent.childNodes:
87   - if node.nodeType == minidom.Node.ELEMENT_NODE and \
88   - (name == "*" or node.tagName == name):
  89 + if (node.nodeType == minidom.Node.ELEMENT_NODE and
  90 + (name == "*" or node.tagName == name)):
89 91 yield node
90 92 if node.hasChildNodes():
91 93 for othernode in node.getElementsByTagName(name):
@@ -95,10 +97,11 @@ def getElementsByTagName_helper(parent, name, dummy=None):
95 97 def searchElementsByTagName_helper(parent, name, onlysearch):
96 98 """limits the search to within tags occuring in onlysearch"""
97 99 for node in parent.childNodes:
98   - if node.nodeType == minidom.Node.ELEMENT_NODE and \
99   - (name == "*" or node.tagName == name):
  100 + if (node.nodeType == minidom.Node.ELEMENT_NODE and
  101 + (name == "*" or node.tagName == name)):
100 102 yield node
101   - if node.nodeType == minidom.Node.ELEMENT_NODE and node.tagName in onlysearch:
  103 + if (node.nodeType == minidom.Node.ELEMENT_NODE and
  104 + node.tagName in onlysearch):
102 105 for node in node.searchElementsByTagName(name, onlysearch):
103 106 yield node
104 107
@@ -181,8 +184,9 @@ def reset(self):
181 184 self._initNamespaces()
182 185
183 186 def start_element_handler(self, name, attributes):
184   - # all we want to do is construct our own Element instead of minidom.Element
185   - # unfortunately the only way to do this is to copy this whole function from expatbuilder.py
  187 + # All we want to do is construct our own Element instead of
  188 + # minidom.Element, unfortunately the only way to do this is to
  189 + # copy this whole function from expatbuilder.py
186 190 if ' ' in name:
187 191 uri, localname, prefix, qname = expatbuilder._parse_ns_name(self, name)
188 192 else:
@@ -198,7 +202,8 @@ def start_element_handler(self, name, attributes):
198 202 if self._ns_ordered_prefixes:
199 203 for prefix, uri in self._ns_ordered_prefixes:
200 204 if prefix:
201   - a = minidom.Attr(expatbuilder._intern(self, 'xmlns:' + prefix),
  205 + a = minidom.Attr(expatbuilder._intern(self,
  206 + 'xmlns:' + prefix),
202 207 expatbuilder.XMLNS_NAMESPACE, prefix, "xmlns")
203 208 else:
204 209 a = minidom.Attr("xmlns", expatbuilder.XMLNS_NAMESPACE,
12 translate/misc/quote.py
@@ -87,7 +87,8 @@ def extract(source, startdelim, enddelim,
87 87 extracted += source[lastpos:pos]
88 88 instring = False
89 89 lastpos = pos
90   - if (not instring) and pos in startdelim_places and not (enteredonce and not allowreentry):
  90 + if ((not instring) and pos in startdelim_places and
  91 + not (enteredonce and not allowreentry)):
91 92 instring = True
92 93 enteredonce = True
93 94 lastpos = pos
@@ -164,7 +165,8 @@ def extractwithoutquotes(source, startdelim, enddelim, escape=None,
164 165 extracted += section
165 166 instring = False
166 167 lastpos = pos
167   - if (not instring) and pos in startdelim_places and not (enteredonce and not allowreentry):
  168 + if ((not instring) and pos in startdelim_places and
  169 + not (enteredonce and not allowreentry)):
168 170 instring = True
169 171 enteredonce = True
170 172 lastpos = pos
@@ -177,7 +179,8 @@ def extractwithoutquotes(source, startdelim, enddelim, escape=None,
177 179 last_epos = 0
178 180 for epos in escape_list:
179 181 new_section += section[last_epos:epos]
180   - if callable_includeescapes and includeescapes(section[epos:epos + lenescape + 1]):
  182 + if (callable_includeescapes and
  183 + includeescapes(section[epos:epos + lenescape + 1])):
181 184 last_epos = epos
182 185 else:
183 186 last_epos = epos + lenescape
@@ -226,7 +229,8 @@ def htmlentitydecode(source):
226 229 continue
227 230 if inentity:
228 231 if char == ";":
229   - if len(possibleentity) > 0 and possibleentity in htmlentitydefs.name2codepoint:
  232 + if (len(possibleentity) > 0 and
  233 + possibleentity in htmlentitydefs.name2codepoint):
230 234 output += unichr(htmlentitydefs.name2codepoint[possibleentity])
231 235 inentity = False
232 236 else:
33 translate/misc/sparse.py
@@ -2,8 +2,9 @@
2 2 # -*- coding: utf-8 -*-
3 3
4 4 """simple parser / string tokenizer
5   -rather than returning a list of token types etc, we simple return a list of tokens...
6   -each tokenizing function takes a string as input and returns a list of tokens
  5 +rather than returning a list of token types etc, we simple return a list
  6 +of tokens. Each tokenizing function takes a string as input and returns
  7 +a list of tokens.
7 8 """
8 9
9 10 # Copyright 2002, 2003 St James Software
@@ -25,7 +26,8 @@
25 26
26 27
27 28 def stringeval(text):
28   - """takes away repeated quotes (escapes) and returns the string represented by the text"""
  29 + """takes away repeated quotes (escapes) and returns the string
  30 + represented by the text"""
29 31 stringchar = text[0]
30 32 if text[-1] != stringchar or stringchar not in ("'", '"'):
31 33 # scratch your head
@@ -34,7 +36,8 @@ def stringeval(text):
34 36
35 37
36 38 def stringquote(text):
37   - """escapes quotes as neccessary and returns a string representing the text"""
  39 + """escapes quotes as neccessary and returns a string representing
  40 + the text"""
38 41 if "'" in text:
39 42 if '"' in text:
40 43 return '"' + text.replace('"', '""') + '"'
@@ -60,15 +63,19 @@ def __init__(self, parser, message, tokennum):
60 63 class SimpleParser:
61 64 """this is a simple parser"""
62 65
63   - def __init__(self, defaulttokenlist=None, whitespacechars=" \t\r\n", includewhitespacetokens=0):
  66 + def __init__(self, defaulttokenlist=None, whitespacechars=" \t\r\n",
  67 + includewhitespacetokens=0):
64 68 if defaulttokenlist is None:
65   - self.defaulttokenlist = ['<=', '>=', '==', '!=', '+=', '-=', '*=', '/=', '<>']
  69 + self.defaulttokenlist = ['<=', '>=', '==', '!=',
  70 + '+=', '-=', '*=', '/=', '<>']
66 71 self.defaulttokenlist.extend('(),[]:=+-')
67 72 else:
68 73 self.defaulttokenlist = defaulttokenlist
69 74 self.whitespacechars = whitespacechars
70 75 self.includewhitespacetokens = includewhitespacetokens
71   - self.standardtokenizers = [self.stringtokenize, self.removewhitespace, self.separatetokens]
  76 + self.standardtokenizers = [
  77 + self.stringtokenize, self.removewhitespace, self.separatetokens
  78 + ]
72 79 self.quotechars = ('"', "'")
73 80 self.endquotechars = {'"': '"', "'": "'"}
74 81 self.stringescaping = 1
@@ -83,7 +90,8 @@ def stringtokenize(self, text):
83 90 for pos in range(len(text)):
84 91 char = text[pos]
85 92 if instring:
86   - if self.stringescaping and (gotescape or char == escapechar) and not gotclose:
  93 + if (self.stringescaping and
  94 + (gotescape or char == escapechar) and not gotclose):
87 95 gotescape = not gotescape
88 96 elif char == endstringchar:
89 97 gotclose = not gotclose
@@ -136,7 +144,8 @@ def separatetokens(self, text, tokenlist=None):
136 144 return tokens
137 145
138 146 def removewhitespace(self, text):
139   - """this removes whitespace but lets it separate things out into separate tokens"""
  147 + """this removes whitespace but lets it separate things out into
  148 + separate tokens"""
140 149 if self.keeptogether(text):
141 150 return [text]
142 151 # loop through and put tokens into a list
@@ -156,7 +165,8 @@ def removewhitespace(self, text):
156 165 if laststart < pos:
157 166 tokens.append(text[laststart:pos])
158 167 inwhitespace, laststart = 1, pos
159   - if laststart < len(text) and (not inwhitespace or self.includewhitespacetokens):
  168 + if (laststart < len(text) and
  169 + (not inwhitespace or self.includewhitespacetokens)):
160 170 tokens.append(text[laststart:])
161 171 return tokens
162 172
@@ -185,7 +195,8 @@ def findtokenpos(self, tokennum):
185 195 """finds the position of the given token in the text"""
186 196 currenttokenpos = 0
187 197 for currenttokennum in range(tokennum + 1):
188   - currenttokenpos = self.source.find(self.tokens[currenttokennum], currenttokenpos)
  198 + currenttokenpos = self.source.find(self.tokens[currenttokennum],
  199 + currenttokenpos)
189 200 return currenttokenpos
190 201
191 202 def getlinepos(self, tokenpos):
15 translate/misc/wStringIO.py
@@ -18,7 +18,8 @@
18 18 # You should have received a copy of the GNU General Public License
19 19 # along with this program; if not, see <http://www.gnu.org/licenses/>.
20 20
21   -"""A wrapper for cStringIO that provides more of the functions of StringIO at the speed of cStringIO"""
  21 +"""A wrapper for cStringIO that provides more of the functions of
  22 +StringIO at the speed of cStringIO"""
22 23
23 24 import cStringIO
24 25
@@ -139,20 +140,24 @@ def getvalue(self):
139 140
140 141
141 142 class CatchStringOutput(StringIO, object):
142   - """catches the output before it is closed and sends it to an onclose method"""
  143 + """catches the output before it is closed and sends it to an onclose
  144 + method"""
143 145
144 146 def __init__(self, onclose):
145   - """Set up the output stream, and remember a method to call on closing"""
  147 + """Set up the output stream, and remember a method to call on
  148 + closing"""
146 149 StringIO.__init__(self)
147 150 self.onclose = onclose
148 151
149 152 def close(self):
150   - """wrap the underlying close method, to pass the value to onclose before it goes"""
  153 + """wrap the underlying close method, to pass the value to onclose
  154 + before it goes"""
151 155 value = self.getvalue()
152 156 self.onclose(value)
153 157 super(CatchStringOutput, self).close()
154 158
155 159 def slam(self):
156   - """use this method to force the closing of the stream if it isn't closed yet"""
  160 + """use this method to force the closing of the stream if it isn't
  161 + closed yet"""
157 162 if not self.closed:
158 163 self.close()
12 translate/misc/wsgi.py
@@ -40,15 +40,18 @@ def log_error(self, format, *args):
40 40 """Log errors using logging instead of printing to
41 41 stderror"""
42 42 logging.error("%s - - [%s] %s",
43   - self.address_string(), self.log_date_time_string(), format % args)
  43 + self.address_string(), self.log_date_time_string(),
  44 + format % args)
44 45
45 46 def log_message(self, format, *args):
46 47 """Log requests using logging instead of printing to
47 48 stderror."""
48 49 logging.info("%s - - [%s] %s",
49   - self.address_string(), self.log_date_time_string(), format % args)
  50 + self.address_string(), self.log_date_time_string(),
  51 + format % args)
50 52
51   - server = simple_server.make_server(host, port, app, handler_class=CustomRequestHandler)
  53 + server = simple_server.make_server(host, port, app,
  54 + handler_class=CustomRequestHandler)
52 55 logging.info("Starting wsgiref server, listening on port %s", port)
53 56 server.serve_forever()
54 57
@@ -85,7 +88,8 @@ def launch_server_werkzeug(host, port, app):
85 88
86 89 #FIXME: implement threading http server based on BaseHTTPServer and wsgiref
87 90
88   -servers = [launch_server_cherrypy, launch_server_werkzeug, launch_server_django, launch_server_wsgiref]
  91 +servers = [launch_server_cherrypy, launch_server_werkzeug,
  92 + launch_server_django, launch_server_wsgiref]
89 93
90 94
91 95 def launch_server(host, port, app):
3  translate/misc/xml_helpers.py
@@ -102,7 +102,8 @@ def namespaced(namespace, name):
102 102
103 103
104 104 def normalize_space(text):
105   - """Normalize the given text for implementation of ``xml:space="default"``."""
  105 + """Normalize the given text for implementation of
  106 + ``xml:space="default"``."""
106 107 text = MULTIWHITESPACE_RE.sub(u" ", text)
107 108 return text
108 109
6 translate/misc/xmlwrapper.py
@@ -31,10 +31,12 @@
31 31
32 32
33 33 def makefixtagproc(namespacemap):
34   - """this constructs an alternative fixtag procedure that will use appropriate names for namespaces..."""
  34 + """Constructs an alternative fixtag procedure that will use appropriate
  35 + names for namespaces."""
35 36
36 37 def fixtag(tag, namespaces):
37   - """given a decorated tag (of the form {uri}tag), return prefixed tag and namespace declaration, if any"""
  38 + """Given a decorated tag (of the form {uri}tag), return prefixed
  39 + tag and namespace declaration, if any."""
38 40 if isinstance(tag, ElementTree.QName):
39 41 tag = tag.text
40 42 namespace_uri, tag = tag[1:].split("}", 1)
31 translate/misc/zipfileext.py
@@ -18,9 +18,11 @@
18 18 # You should have received a copy of the GNU General Public License
19 19 # along with this program; if not, see <http://www.gnu.org/licenses/>.
20 20
21   -"""extensions to zipfile standard module that will hopefully get included in future..."""
  21 +"""Extensions to zipfile standard module that will hopefully get
  22 +included in future."""
22 23
23   -from zipfile import ZipFile, struct, structCentralDir, stringCentralDir, structEndArchive, stringEndArchive
  24 +from zipfile import ZipFile, struct, structCentralDir, \
  25 + stringCentralDir, structEndArchive, stringEndArchive
24 26
25 27
26 28 class ZipFileExt(ZipFile, object):
@@ -36,13 +38,20 @@ def delete(self, name):
36 38 deleted_offset = self.filelist[i].header_offset
37 39 # "file_offset" is only available in python up to 2.4
38 40 if hasattr(self.filelist[i], "file_offset"):
39   - deleted_size = (self.filelist[i].file_offset - self.filelist[i].header_offset) + self.filelist[i].compress_size
  41 + deleted_size = ((self.filelist[i].file_offset -
  42 + self.filelist[i].header_offset) +
  43 + self.filelist[i].compress_size)
40 44 else:
41   - deleted_size = (len(self.filelist[i].FileHeader()) - self.filelist[i].header_offset) + self.filelist[i].compress_size
42   - zinfo_size = struct.calcsize(structCentralDir) + len(self.filelist[i].filename) + len(self.filelist[i].extra)
  45 + deleted_size = ((len(self.filelist[i].FileHeader()) -
  46 + self.filelist[i].header_offset) +
  47 + self.filelist[i].compress_size)
  48 + zinfo_size = (struct.calcsize(structCentralDir) +
  49 + len(self.filelist[i].filename) +
  50 + len(self.filelist[i].extra))
43 51 # Remove the file's data from the archive.
44 52 current_offset = self.fp.tell()
45   - # go to the end of the archive to calculate the total archive_size
  53 + # go to the end of the archive to calculate the
  54 + # total archive_size
46 55 self.fp.seek(0, 2)
47 56 archive_size = self.fp.tell()
48 57 self.fp.seek(deleted_offset + deleted_size)
@@ -50,11 +59,15 @@ def delete(self, name):
50 59 self.fp.seek(deleted_offset)
51 60 self.fp.write(buf)
52 61 self.fp.truncate(archive_size - deleted_size - zinfo_size)
53   - # go to the end of the archive to calculate the total archive_size
  62 + # go to the end of the archive to calculate the
  63 + # total archive_size
54 64 self.fp.seek(0, 2)
55 65 if self.debug >= 2:
56   - if self.fp.tell() != archive_size - deleted_size - zinfo_size:
57   - print "truncation failed: %r != %r" % (self.fp.tell(), archive_size - deleted_size - zinfo_size)
  66 + if self.fp.tell() != (archive_size - deleted_size -
  67 + zinfo_size):
  68 + print "truncation failed: %r != %r" % \
  69 + (self.fp.tell(),
  70 + (archive_size - deleted_size - zinfo_size))
58 71 if current_offset > deleted_offset + deleted_size:
59 72 current_offset -= deleted_size
60 73 elif current_offset > deleted_offset:

0 comments on commit fd3a8ca

Please sign in to comment.
Something went wrong with that request. Please try again.