Skip to content
Browse files

PEP8: E501 line too long

  • Loading branch information...
1 parent 8dc79ba commit fd3a8cadf3a46c08023e4d083a7ab9a791a8c206 @dwaynebailey dwaynebailey committed Apr 15, 2012
View
30 translate/misc/dictutils.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-"""Implements a case-insensitive (on keys) dictionary and order-sensitive dictionary"""
+"""Implements a case-insensitive (on keys) dictionary and
+order-sensitive dictionary"""
# Copyright 2002, 2003 St James Software
#
@@ -37,36 +38,41 @@ def __init__(self, fromdict=None):
def __getitem__(self, key):
if type(key) != str and type(key) != unicode:
- raise TypeError("cidict can only have str or unicode as key (got %r)" % type(key))
+ raise TypeError("cidict can only have str or unicode as key (got %r)" %
+ type(key))
for akey in self.iterkeys():
if akey.lower() == key.lower():
return dict.__getitem__(self, akey)
raise IndexError
def __setitem__(self, key, value):
if type(key) != str and type(key) != unicode:
- raise TypeError("cidict can only have str or unicode as key (got %r)" % type(key))
+ raise TypeError("cidict can only have str or unicode as key (got %r)" %
+ type(key))
for akey in self.iterkeys():
if akey.lower() == key.lower():
return dict.__setitem__(self, akey, value)
return dict.__setitem__(self, key, value)
def update(self, updatedict):
- """D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]"""
+ """D.update(E) -> None.
+ Update D from E: for k in E.keys(): D[k] = E[k]"""
for key, value in updatedict.iteritems():
self[key] = value
def __delitem__(self, key):
if type(key) != str and type(key) != unicode:
- raise TypeError("cidict can only have str or unicode as key (got %r)" % type(key))
+ raise TypeError("cidict can only have str or unicode as key (got %r)" %
+ type(key))
for akey in self.iterkeys():
if akey.lower() == key.lower():
return dict.__delitem__(self, akey)
raise IndexError
def __contains__(self, key):
if type(key) != str and type(key) != unicode:
- raise TypeError("cidict can only have str or unicode as key (got %r)" % type(key))
+ raise TypeError("cidict can only have str or unicode as key (got %r)" %
+ type(key))
for akey in self.iterkeys():
if akey.lower() == key.lower():
return 1
@@ -83,14 +89,16 @@ def get(self, key, default=None):
class ordereddict(dict):
- """a dictionary which remembers its keys in the order in which they were given"""
+ """a dictionary which remembers its keys in the order in which they
+ were given"""
def __init__(self, *args):
if len(args) == 0:
super(ordereddict, self).__init__()
self.order = []
elif len(args) > 1:
- raise TypeError("ordereddict() takes at most 1 argument (%d given)" % len(args))
+ raise TypeError("ordereddict() takes at most 1 argument (%d given)" %
+ len(args))
else:
initarg = args[0]
apply(super(ordereddict, self).__init__, args)
@@ -113,7 +121,8 @@ def __setitem__(self, key, value):
return result
def update(self, updatedict):
- """D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]"""
+ """D.update(E) -> None.
+ Update D from E: for k in E.keys(): D[k] = E[k]"""
for key, value in updatedict.iteritems():
self[key] = value
@@ -156,7 +165,8 @@ def keys(self):
return self.order[:]
def popitem(self):
- """D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty"""
+ """D.popitem() -> (k, v), remove and return some (key, value) pair
+ as a 2-tuple; but raise KeyError if D is empty"""
if len(self.order) == 0:
raise KeyError("popitem(): ordered dictionary is empty")
k = self.order.pop()
View
7 translate/misc/file_discovery.py
@@ -26,8 +26,8 @@
def get_abs_data_filename(path_parts, basedirs=None):
- """Get the absolute path to the given file- or directory name in the current
- running application's data directory.
+ """Get the absolute path to the given file- or directory name in the
+ current running application's data directory.
:type path_parts: list
: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):
for basepath, data_dir in ((x, y) for x in BASE_DIRS for y in DATA_DIRS):
dir_and_filename = data_dir + path_parts
- datafile = os.path.join(basepath or os.path.dirname(__file__), *dir_and_filename)
+ datafile = os.path.join(basepath or os.path.dirname(__file__),
+ *dir_and_filename)
if os.path.exists(datafile):
return datafile
raise Exception('Could not find "%s"' % (os.path.join(*path_parts)))
View
9 translate/misc/lru.py
@@ -31,7 +31,8 @@ class LRUCachingDict(WeakValueDictionary):
maxsize is reached.
"""
- def __init__(self, maxsize, cullsize=2, peakmult=10, aggressive_gc=True, *args, **kwargs):
+ def __init__(self, maxsize, cullsize=2, peakmult=10, aggressive_gc=True,
+ *args, **kwargs):
self.cullsize = max(2, cullsize)
self.maxsize = max(cullsize, maxsize)
self.aggressive_gc = aggressive_gc
@@ -81,7 +82,8 @@ def __setitem__(self, key, value):
# appended again
self.queue.pop()
- if len(self) >= self.maxsize or len(self.queue) >= self.maxsize * self.peakmult:
+ if (len(self) >= self.maxsize or
+ len(self.queue) >= self.maxsize * self.peakmult):
self.cull()
self.queue.append((key, value))
@@ -97,7 +99,8 @@ def __getitem__(self, key):
# only append if item is not at right end of queue
if not (len(self.queue) and self.queue[-1][0] == key):
- if len(self) >= self.maxsize or len(self.queue) >= self.maxsize * self.peakmult:
+ if (len(self) >= self.maxsize or
+ len(self.queue) >= self.maxsize * self.peakmult):
self.cull()
self.queue.append((key, value))
View
18 translate/misc/multistring.py
@@ -18,7 +18,8 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
-"""Supports a hybrid Unicode string that can also have a list of alternate strings in the strings attribute"""
+"""Supports a hybrid Unicode string that can also have a list of alternate
+strings in the strings attribute"""
from translate.misc import autoencode
@@ -30,10 +31,12 @@ def __new__(newtype, string=u"", encoding=None, errors=None):
if not string:
raise ValueError("multistring must contain at least one string")
mainstring = string[0]
- newstring = multistring.__new__(newtype, string[0], encoding, errors)
+ newstring = multistring.__new__(newtype, string[0],
+ encoding, errors)
newstring.strings = [newstring] + [autoencode.autoencode.__new__(autoencode.autoencode, altstring, encoding, errors) for altstring in string[1:]]
else:
- newstring = autoencode.autoencode.__new__(newtype, string, encoding, errors)
+ newstring = autoencode.autoencode.__new__(newtype, string,
+ encoding, errors)
newstring.strings = [newstring]
return newstring
@@ -67,14 +70,17 @@ def __eq__(self, otherstring):
return self.__cmp__(otherstring) == 0
def __repr__(self):
- parts = [autoencode.autoencode.__repr__(self)] + [repr(a) for a in self.strings[1:]]
+ parts = [autoencode.autoencode.__repr__(self)] + \
+ [repr(a) for a in self.strings[1:]]
return "multistring([" + ",".join(parts) + "])"
def replace(self, old, new, count=None):
if count is None:
- newstr = multistring(super(multistring, self).replace(old, new), self.encoding)
+ newstr = multistring(super(multistring, self) \
+ .replace(old, new), self.encoding)
else:
- newstr = multistring(super(multistring, self).replace(old, new, count), self.encoding)
+ newstr = multistring(super(multistring, self) \
+ .replace(old, new, count), self.encoding)
for s in self.strings[1:]:
if count is None:
newstr.strings.append(s.replace(old, new))
View
69 translate/misc/optrecurse.py
@@ -329,7 +329,8 @@ def seterrorleveloptions(self):
errorleveloption = optparse.Option(None, "--errorlevel",
dest="errorlevel", default="message",
choices=self.errorleveltypes, metavar="ERRORLEVEL",
- help="show errorlevel as: %s" % (", ".join(self.errorleveltypes)))
+ help="show errorlevel as: %s" % \
+ (", ".join(self.errorleveltypes)))
self.define_option(errorleveloption)
def getformathelp(self, formats):
@@ -417,11 +418,14 @@ def getoutputoptions(self, options, inputpath, templatepath):
if inputext is None:
raise ValueError("don't know what to do with input format (no file extension), no template file")
elif templateext is None:
- raise ValueError("don't know what to do with input format %s, no template file" % (os.extsep + inputext))
+ raise ValueError("don't know what to do with input format %s, no template file" %
+ (os.extsep + inputext))
else:
- raise ValueError("don't know what to do with input format %s, template format %s" % (os.extsep + inputext, os.extsep + templateext))
+ raise ValueError("don't know what to do with input format %s, template format %s" %
+ (os.extsep + inputext, os.extsep + templateext))
else:
- raise ValueError("don't know what to do with input format %s" % os.extsep + inputext)
+ raise ValueError("don't know what to do with input format %s" %
+ (os.extsep + inputext))
if outputformat == "*":
if inputext:
outputformat = inputext
@@ -432,11 +436,14 @@ def getoutputoptions(self, options, inputpath, templatepath):
else:
if self.usetemplates:
if templateext is None:
- raise ValueError("don't know what to do with input format %s, no template file" % (os.extsep + inputext))
+ raise ValueError("don't know what to do with input format %s, no template file" %
+ (os.extsep + inputext))
else:
- raise ValueError("don't know what to do with input format %s, template format %s" % (os.extsep + inputext, os.extsep + templateext))
+ raise ValueError("don't know what to do with input format %s, template format %s" %
+ (os.extsep + inputext, os.extsep + templateext))
else:
- raise ValueError("don't know what to do with input format %s" % os.extsep + inputext)
+ raise ValueError("don't know what to do with input format %s" %
+ (os.extsep + inputext))
return outputformat, fileprocessor
def initprogressbar(self, allfiles, options):
@@ -465,7 +472,8 @@ def getfulltemplatepath(self, options, templatepath):
"""Gets the absolute path to a template file."""
if not options.recursivetemplate:
return templatepath
- elif templatepath is not None and self.usetemplates and options.template:
+ elif (templatepath is not None and
+ self.usetemplates and options.template):
return os.path.join(options.template, templatepath)
else:
return None
@@ -502,28 +510,35 @@ def recursiveprocess(self, options):
options.input = os.path.dirname(options.input)
else:
inputfiles = [options.input]
- options.recursiveoutput = self.isrecursive(options.output, 'output') and getattr(options, "allowrecursiveoutput", True)
- options.recursivetemplate = self.usetemplates and self.isrecursive(options.template, 'template') and getattr(options, "allowrecursivetemplate", True)
+ options.recursiveoutput = (self.isrecursive(options.output, 'output') and
+ getattr(options, "allowrecursiveoutput", True))
+ options.recursivetemplate = (self.usetemplates and
+ self.isrecursive(options.template, 'template') and
+ getattr(options, "allowrecursivetemplate", True))
self.initprogressbar(inputfiles, options)
for inputpath in inputfiles:
try:
templatepath = self.gettemplatename(options, inputpath)
# If we have a recursive template, but the template doesn't
# have this input file, let's drop it.
- if options.recursivetemplate and templatepath is None and not self.allowmissingtemplate:
- self.warning("No template at %s. Skipping %s." % (templatepath, inputpath))
+ if (options.recursivetemplate and templatepath is None and
+ not self.allowmissingtemplate):
+ self.warning("No template at %s. Skipping %s." %
+ (templatepath, inputpath))
continue
outputformat, fileprocessor = self.getoutputoptions(options, inputpath, templatepath)
fullinputpath = self.getfullinputpath(options, inputpath)
- fulltemplatepath = self.getfulltemplatepath(options, templatepath)
+ fulltemplatepath = self.getfulltemplatepath(options,
+ templatepath)
outputpath = self.getoutputname(options, inputpath, outputformat)
fulloutputpath = self.getfulloutputpath(options, outputpath)
if options.recursiveoutput and outputpath:
self.checkoutputsubdir(options, os.path.dirname(outputpath))
except Exception, error:
if isinstance(error, KeyboardInterrupt):
raise
- self.warning("Couldn't handle input file %s" % inputpath, options, sys.exc_info())
+ self.warning("Couldn't handle input file %s" %
+ inputpath, options, sys.exc_info())
continue
try:
success = self.processfile(fileprocessor, options,
@@ -532,7 +547,9 @@ def recursiveprocess(self, options):
except Exception, error:
if isinstance(error, KeyboardInterrupt):
raise
- self.warning("Error processing: input %s, output %s, template %s" % (fullinputpath, fulloutputpath, fulltemplatepath), options, sys.exc_info())
+ self.warning("Error processing: input %s, output %s, template %s" %
+ (fullinputpath, fulloutputpath,
+ fulltemplatepath), options, sys.exc_info())
success = False
self.reportprogress(inputpath, success)
del self.progressbar
@@ -574,7 +591,8 @@ def processfile(self, fileprocessor, options, fullinputpath,
fulloutputpath, fulltemplatepath):
"""Process an individual file."""
inputfile = self.openinputfile(options, fullinputpath)
- if fulloutputpath and fulloutputpath in (fullinputpath, fulltemplatepath):
+ if (fulloutputpath and
+ fulloutputpath in (fullinputpath, fulltemplatepath)):
outputfile = self.opentempoutputfile(options, fulloutputpath)
tempoutput = True
else:
@@ -586,7 +604,8 @@ def processfile(self, fileprocessor, options, fullinputpath,
**passthroughoptions):
if tempoutput:
self.warning("writing to temporary output...")
- self.finalizetempoutputfile(options, outputfile, fulloutputpath)
+ self.finalizetempoutputfile(options, outputfile,
+ fulloutputpath)
return True
else:
# remove the file if it is a file (could be stdout etc)
@@ -603,7 +622,8 @@ def reportprogress(self, filename, success):
def mkdir(self, parent, subdir):
"""Makes a subdirectory (recursively if neccessary)."""
if not os.path.isdir(parent):
- raise ValueError("cannot make child directory %r if parent %r does not exist" % (subdir, parent))
+ raise ValueError("cannot make child directory %r if parent %r does not exist" %
+ (subdir, parent))
currentpath = parent
subparts = subdir.split(os.sep)
for part in subparts:
@@ -628,7 +648,8 @@ def isexcluded(self, options, inputpath):
def recurseinputfilelist(self, options):
"""Use a list of files, and find a common base directory for them."""
- # find a common base directory for the files to do everything relative to
+ # find a common base directory for the files to do everything
+ # relative to
commondir = os.path.dirname(os.path.commonprefix(options.input))
inputfiles = []
for inputfile in options.input:
@@ -642,7 +663,7 @@ def recurseinputfilelist(self, options):
return inputfiles
def recurseinputfiles(self, options):
- """Recurse through directories and return files to be processed..."""
+ """Recurse through directories and return files to be processed."""
dirstack = ['']
join = os.path.join
inputfiles = []
@@ -660,10 +681,11 @@ def recurseinputfiles(self, options):
dirs.append(inputpath)
elif os.path.isfile(fullinputpath):
if not self.isvalidinputname(options, name):
- # only handle names that match recognized input file extensions
+ # only handle names that match recognized input
+ # file extensions
continue
inputfiles.append(inputpath)
- # make sure the directories are processed next time round...
+ # make sure the directories are processed next time round.
dirs.reverse()
dirstack.extend(dirs)
return inputfiles
@@ -733,4 +755,5 @@ def getoutputname(self, options, inputname, outputformat):
def isvalidinputname(self, options, inputname):
"""Checks if this is a valid input filename."""
inputbase, inputext = self.splitinputext(inputname)
- return (inputext in options.inputformats) or ("*" in options.inputformats)
+ return ((inputext in options.inputformats) or
+ ("*" in options.inputformats))
View
25 translate/misc/ourdom.py
@@ -30,12 +30,14 @@
from xml.dom import minidom
from xml.dom import expatbuilder
-# helper functions we use to do xml the way we want, used by modified classes below
+# helper functions we use to do xml the way we want, used by modified
+# classes below
def writexml_helper(self, writer, indent="", addindent="", newl=""):
"""A replacement for writexml that formats it like typical XML files.
- Nodes are intendented but text nodes, where whitespace can be significant, are not indented."""
+ Nodes are intendented but text nodes, where whitespace can be
+ significant, are not indented."""
# indent = current indentation
# addindent = indentation to add to higher levels
# newl = newline string
@@ -84,8 +86,8 @@ def getElementsByTagName_helper(parent, name, dummy=None):
list, therefore, the class below exposes this through yieldElementsByTagName"""
for node in parent.childNodes:
- if node.nodeType == minidom.Node.ELEMENT_NODE and \
- (name == "*" or node.tagName == name):
+ if (node.nodeType == minidom.Node.ELEMENT_NODE and
+ (name == "*" or node.tagName == name)):
yield node
if node.hasChildNodes():
for othernode in node.getElementsByTagName(name):
@@ -95,10 +97,11 @@ def getElementsByTagName_helper(parent, name, dummy=None):
def searchElementsByTagName_helper(parent, name, onlysearch):
"""limits the search to within tags occuring in onlysearch"""
for node in parent.childNodes:
- if node.nodeType == minidom.Node.ELEMENT_NODE and \
- (name == "*" or node.tagName == name):
+ if (node.nodeType == minidom.Node.ELEMENT_NODE and
+ (name == "*" or node.tagName == name)):
yield node
- if node.nodeType == minidom.Node.ELEMENT_NODE and node.tagName in onlysearch:
+ if (node.nodeType == minidom.Node.ELEMENT_NODE and
+ node.tagName in onlysearch):
for node in node.searchElementsByTagName(name, onlysearch):
yield node
@@ -181,8 +184,9 @@ def reset(self):
self._initNamespaces()
def start_element_handler(self, name, attributes):
- # all we want to do is construct our own Element instead of minidom.Element
- # unfortunately the only way to do this is to copy this whole function from expatbuilder.py
+ # All we want to do is construct our own Element instead of
+ # minidom.Element, unfortunately the only way to do this is to
+ # copy this whole function from expatbuilder.py
if ' ' in name:
uri, localname, prefix, qname = expatbuilder._parse_ns_name(self, name)
else:
@@ -198,7 +202,8 @@ def start_element_handler(self, name, attributes):
if self._ns_ordered_prefixes:
for prefix, uri in self._ns_ordered_prefixes:
if prefix:
- a = minidom.Attr(expatbuilder._intern(self, 'xmlns:' + prefix),
+ a = minidom.Attr(expatbuilder._intern(self,
+ 'xmlns:' + prefix),
expatbuilder.XMLNS_NAMESPACE, prefix, "xmlns")
else:
a = minidom.Attr("xmlns", expatbuilder.XMLNS_NAMESPACE,
View
12 translate/misc/quote.py
@@ -87,7 +87,8 @@ def extract(source, startdelim, enddelim,
extracted += source[lastpos:pos]
instring = False
lastpos = pos
- if (not instring) and pos in startdelim_places and not (enteredonce and not allowreentry):
+ if ((not instring) and pos in startdelim_places and
+ not (enteredonce and not allowreentry)):
instring = True
enteredonce = True
lastpos = pos
@@ -164,7 +165,8 @@ def extractwithoutquotes(source, startdelim, enddelim, escape=None,
extracted += section
instring = False
lastpos = pos
- if (not instring) and pos in startdelim_places and not (enteredonce and not allowreentry):
+ if ((not instring) and pos in startdelim_places and
+ not (enteredonce and not allowreentry)):
instring = True
enteredonce = True
lastpos = pos
@@ -177,7 +179,8 @@ def extractwithoutquotes(source, startdelim, enddelim, escape=None,
last_epos = 0
for epos in escape_list:
new_section += section[last_epos:epos]
- if callable_includeescapes and includeescapes(section[epos:epos + lenescape + 1]):
+ if (callable_includeescapes and
+ includeescapes(section[epos:epos + lenescape + 1])):
last_epos = epos
else:
last_epos = epos + lenescape
@@ -226,7 +229,8 @@ def htmlentitydecode(source):
continue
if inentity:
if char == ";":
- if len(possibleentity) > 0 and possibleentity in htmlentitydefs.name2codepoint:
+ if (len(possibleentity) > 0 and
+ possibleentity in htmlentitydefs.name2codepoint):
output += unichr(htmlentitydefs.name2codepoint[possibleentity])
inentity = False
else:
View
33 translate/misc/sparse.py
@@ -2,8 +2,9 @@
# -*- coding: utf-8 -*-
"""simple parser / string tokenizer
-rather than returning a list of token types etc, we simple return a list of tokens...
-each tokenizing function takes a string as input and returns a list of tokens
+rather than returning a list of token types etc, we simple return a list
+of tokens. Each tokenizing function takes a string as input and returns
+a list of tokens.
"""
# Copyright 2002, 2003 St James Software
@@ -25,7 +26,8 @@
def stringeval(text):
- """takes away repeated quotes (escapes) and returns the string represented by the text"""
+ """takes away repeated quotes (escapes) and returns the string
+ represented by the text"""
stringchar = text[0]
if text[-1] != stringchar or stringchar not in ("'", '"'):
# scratch your head
@@ -34,7 +36,8 @@ def stringeval(text):
def stringquote(text):
- """escapes quotes as neccessary and returns a string representing the text"""
+ """escapes quotes as neccessary and returns a string representing
+ the text"""
if "'" in text:
if '"' in text:
return '"' + text.replace('"', '""') + '"'
@@ -60,15 +63,19 @@ def __init__(self, parser, message, tokennum):
class SimpleParser:
"""this is a simple parser"""
- def __init__(self, defaulttokenlist=None, whitespacechars=" \t\r\n", includewhitespacetokens=0):
+ def __init__(self, defaulttokenlist=None, whitespacechars=" \t\r\n",
+ includewhitespacetokens=0):
if defaulttokenlist is None:
- self.defaulttokenlist = ['<=', '>=', '==', '!=', '+=', '-=', '*=', '/=', '<>']
+ self.defaulttokenlist = ['<=', '>=', '==', '!=',
+ '+=', '-=', '*=', '/=', '<>']
self.defaulttokenlist.extend('(),[]:=+-')
else:
self.defaulttokenlist = defaulttokenlist
self.whitespacechars = whitespacechars
self.includewhitespacetokens = includewhitespacetokens
- self.standardtokenizers = [self.stringtokenize, self.removewhitespace, self.separatetokens]
+ self.standardtokenizers = [
+ self.stringtokenize, self.removewhitespace, self.separatetokens
+ ]
self.quotechars = ('"', "'")
self.endquotechars = {'"': '"', "'": "'"}
self.stringescaping = 1
@@ -83,7 +90,8 @@ def stringtokenize(self, text):
for pos in range(len(text)):
char = text[pos]
if instring:
- if self.stringescaping and (gotescape or char == escapechar) and not gotclose:
+ if (self.stringescaping and
+ (gotescape or char == escapechar) and not gotclose):
gotescape = not gotescape
elif char == endstringchar:
gotclose = not gotclose
@@ -136,7 +144,8 @@ def separatetokens(self, text, tokenlist=None):
return tokens
def removewhitespace(self, text):
- """this removes whitespace but lets it separate things out into separate tokens"""
+ """this removes whitespace but lets it separate things out into
+ separate tokens"""
if self.keeptogether(text):
return [text]
# loop through and put tokens into a list
@@ -156,7 +165,8 @@ def removewhitespace(self, text):
if laststart < pos:
tokens.append(text[laststart:pos])
inwhitespace, laststart = 1, pos
- if laststart < len(text) and (not inwhitespace or self.includewhitespacetokens):
+ if (laststart < len(text) and
+ (not inwhitespace or self.includewhitespacetokens)):
tokens.append(text[laststart:])
return tokens
@@ -185,7 +195,8 @@ def findtokenpos(self, tokennum):
"""finds the position of the given token in the text"""
currenttokenpos = 0
for currenttokennum in range(tokennum + 1):
- currenttokenpos = self.source.find(self.tokens[currenttokennum], currenttokenpos)
+ currenttokenpos = self.source.find(self.tokens[currenttokennum],
+ currenttokenpos)
return currenttokenpos
def getlinepos(self, tokenpos):
View
15 translate/misc/wStringIO.py
@@ -18,7 +18,8 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
-"""A wrapper for cStringIO that provides more of the functions of StringIO at the speed of cStringIO"""
+"""A wrapper for cStringIO that provides more of the functions of
+StringIO at the speed of cStringIO"""
import cStringIO
@@ -139,20 +140,24 @@ def getvalue(self):
class CatchStringOutput(StringIO, object):
- """catches the output before it is closed and sends it to an onclose method"""
+ """catches the output before it is closed and sends it to an onclose
+ method"""
def __init__(self, onclose):
- """Set up the output stream, and remember a method to call on closing"""
+ """Set up the output stream, and remember a method to call on
+ closing"""
StringIO.__init__(self)
self.onclose = onclose
def close(self):
- """wrap the underlying close method, to pass the value to onclose before it goes"""
+ """wrap the underlying close method, to pass the value to onclose
+ before it goes"""
value = self.getvalue()
self.onclose(value)
super(CatchStringOutput, self).close()
def slam(self):
- """use this method to force the closing of the stream if it isn't closed yet"""
+ """use this method to force the closing of the stream if it isn't
+ closed yet"""
if not self.closed:
self.close()
View
12 translate/misc/wsgi.py
@@ -40,15 +40,18 @@ def log_error(self, format, *args):
"""Log errors using logging instead of printing to
stderror"""
logging.error("%s - - [%s] %s",
- self.address_string(), self.log_date_time_string(), format % args)
+ self.address_string(), self.log_date_time_string(),
+ format % args)
def log_message(self, format, *args):
"""Log requests using logging instead of printing to
stderror."""
logging.info("%s - - [%s] %s",
- self.address_string(), self.log_date_time_string(), format % args)
+ self.address_string(), self.log_date_time_string(),
+ format % args)
- server = simple_server.make_server(host, port, app, handler_class=CustomRequestHandler)
+ server = simple_server.make_server(host, port, app,
+ handler_class=CustomRequestHandler)
logging.info("Starting wsgiref server, listening on port %s", port)
server.serve_forever()
@@ -85,7 +88,8 @@ def launch_server_werkzeug(host, port, app):
#FIXME: implement threading http server based on BaseHTTPServer and wsgiref
-servers = [launch_server_cherrypy, launch_server_werkzeug, launch_server_django, launch_server_wsgiref]
+servers = [launch_server_cherrypy, launch_server_werkzeug,
+ launch_server_django, launch_server_wsgiref]
def launch_server(host, port, app):
View
3 translate/misc/xml_helpers.py
@@ -102,7 +102,8 @@ def namespaced(namespace, name):
def normalize_space(text):
- """Normalize the given text for implementation of ``xml:space="default"``."""
+ """Normalize the given text for implementation of
+ ``xml:space="default"``."""
text = MULTIWHITESPACE_RE.sub(u" ", text)
return text
View
6 translate/misc/xmlwrapper.py
@@ -31,10 +31,12 @@
def makefixtagproc(namespacemap):
- """this constructs an alternative fixtag procedure that will use appropriate names for namespaces..."""
+ """Constructs an alternative fixtag procedure that will use appropriate
+ names for namespaces."""
def fixtag(tag, namespaces):
- """given a decorated tag (of the form {uri}tag), return prefixed tag and namespace declaration, if any"""
+ """Given a decorated tag (of the form {uri}tag), return prefixed
+ tag and namespace declaration, if any."""
if isinstance(tag, ElementTree.QName):
tag = tag.text
namespace_uri, tag = tag[1:].split("}", 1)
View
31 translate/misc/zipfileext.py
@@ -18,9 +18,11 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
-"""extensions to zipfile standard module that will hopefully get included in future..."""
+"""Extensions to zipfile standard module that will hopefully get
+included in future."""
-from zipfile import ZipFile, struct, structCentralDir, stringCentralDir, structEndArchive, stringEndArchive
+from zipfile import ZipFile, struct, structCentralDir, \
+ stringCentralDir, structEndArchive, stringEndArchive
class ZipFileExt(ZipFile, object):
@@ -36,25 +38,36 @@ def delete(self, name):
deleted_offset = self.filelist[i].header_offset
# "file_offset" is only available in python up to 2.4
if hasattr(self.filelist[i], "file_offset"):
- deleted_size = (self.filelist[i].file_offset - self.filelist[i].header_offset) + self.filelist[i].compress_size
+ deleted_size = ((self.filelist[i].file_offset -
+ self.filelist[i].header_offset) +
+ self.filelist[i].compress_size)
else:
- deleted_size = (len(self.filelist[i].FileHeader()) - self.filelist[i].header_offset) + self.filelist[i].compress_size
- zinfo_size = struct.calcsize(structCentralDir) + len(self.filelist[i].filename) + len(self.filelist[i].extra)
+ deleted_size = ((len(self.filelist[i].FileHeader()) -
+ self.filelist[i].header_offset) +
+ self.filelist[i].compress_size)
+ zinfo_size = (struct.calcsize(structCentralDir) +
+ len(self.filelist[i].filename) +
+ len(self.filelist[i].extra))
# Remove the file's data from the archive.
current_offset = self.fp.tell()
- # go to the end of the archive to calculate the total archive_size
+ # go to the end of the archive to calculate the
+ # total archive_size
self.fp.seek(0, 2)
archive_size = self.fp.tell()
self.fp.seek(deleted_offset + deleted_size)
buf = self.fp.read()
self.fp.seek(deleted_offset)
self.fp.write(buf)
self.fp.truncate(archive_size - deleted_size - zinfo_size)
- # go to the end of the archive to calculate the total archive_size
+ # go to the end of the archive to calculate the
+ # total archive_size
self.fp.seek(0, 2)
if self.debug >= 2:
- if self.fp.tell() != archive_size - deleted_size - zinfo_size:
- print "truncation failed: %r != %r" % (self.fp.tell(), archive_size - deleted_size - zinfo_size)
+ if self.fp.tell() != (archive_size - deleted_size -
+ zinfo_size):
+ print "truncation failed: %r != %r" % \
+ (self.fp.tell(),
+ (archive_size - deleted_size - zinfo_size))
if current_offset > deleted_offset + deleted_size:
current_offset -= deleted_size
elif current_offset > deleted_offset:

0 comments on commit fd3a8ca

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