Miscellaneous modules for translate - including modules for backward compatibility with pre-2.3 versions of Python
Supports a hybrid Unicode string that knows which encoding is preferable, and uses this when converting to a string.
Utilities for with-statement contexts. See PEP 343.
@contextmanager decorator.
Typical usage:
@contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
This makes this:
with some_generator(<arguments>) as <variable>:
<body>
equivalent to this:
<setup>
try:
<variable> = <value>
<body>
finally:
<cleanup>
Support multiple context managers in a single with-statement.
Code like this:
with nested(A, B, C) as (X, Y, Z):
<body>
is equivalent to this:
with A as X:
with B as Y:
with C as Z:
<body>
Context to automatically close something at the end of a block.
Code like this:
with closing(<module>.open(<arguments>)) as f:
<block>
is equivalent to this:
f = <module>.open(<arguments>)
try:
<block>
finally:
f.close()
A function to mimic the with statement introduced in Python 2.5
The code below was taken from http://www.python.org/dev/peps/pep-0343/
Implements a case-insensitive (on keys) dictionary and order-sensitive dictionary
this uses the object’s upper method - works with string and unicode
a dictionary which remembers its keys in the order in which they were given
v defaults to None.
remove entry from dict and internal list
as a 2-tuple; but raise KeyError if D is empty
Update D from E: for k in E.keys(): D[k] = E[k]
Diff Match and Patch
Copyright 2006 Google Inc. http://code.google.com/p/google-diff-match-patch/
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Class containing the diff, match and patch methods.
Also contains the behaviour settings.
Rehydrate the text in a diff from a string of line hashes to real lines of text.
Parameters: |
|
---|
Reduce the number of edits by eliminating operationally trivial equalities.
Parameters: | diffs – Array of diff tuples. |
---|
Reorder and merge like edit sections. Merge equalities. Any edit section can move as long as it doesn’t cross an equality.
Parameters: | diffs – Array of diff tuples. |
---|
Reduce the number of edits by eliminating semantically trivial equalities.
Parameters: | diffs – Array of diff tuples. |
---|
Look for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
Parameters: | diffs – Array of diff tuples. |
---|
Determine the common prefix of two strings.
Parameters: |
|
---|---|
Returns: | The number of characters common to the start of each string. |
Determine the common suffix of two strings.
Parameters: |
|
---|---|
Returns: | The number of characters common to the end of each string. |
Parameters: |
|
---|---|
Returns: | Array of changes. |
Given the original text1, and an encoded string which describes the operations required to transform text1 into text2, compute the full diff.
Parameters: |
|
---|---|
Returns: | Array of diff tuples. |
Raises ValueError: | |
If invalid input. |
Do the two texts share a substring which is at least half the length of the longer text?
Parameters: |
|
---|---|
Returns: | Five element Array, containing the prefix of text1, the suffix of text1, the prefix of text2, the suffix of text2 and the common middle. Or None if there was no match. |
Compute the Levenshtein distance; the number of inserted, deleted or substituted characters.
Parameters: | diffs – Array of diff tuples. |
---|---|
Returns: | Number of changes. |
Split two texts into an array of strings. Reduce the texts to a string of hashes where each Unicode character represents one line.
Parameters: |
|
---|---|
Returns: | Three element tuple, containing the encoded text1, the encoded text2 and the array of unique strings. The zeroth element of the array of unique strings is intentionally blank. |
Parameters: |
|
---|---|
Returns: | Array of changes. |
Explore the intersection points between the two texts.
Parameters: |
|
---|---|
Returns: | Array of diff tuples or None if no diff available. |
Work from the middle back to the start to determine the path.
Parameters: |
|
---|---|
Returns: | Array of diff tuples. |
Work from the middle back to the end to determine the path.
Parameters: |
|
---|---|
Returns: | Array of diff tuples. |
Convert a diff array into a pretty HTML report.
Parameters: | diffs – Array of diff tuples. |
---|---|
Returns: | HTML representation. |
Compute and return the source text (all equalities and deletions).
Parameters: | diffs – Array of diff tuples. |
---|---|
Returns: | Source text. |
Compute and return the destination text (all equalities and insertions).
Parameters: | diffs – Array of diff tuples. |
---|---|
Returns: | Destination text. |
Crush the diff into an encoded string which describes the operations required to transform text1 into text2. E.g. =3 -2 +ing -> Keep 3 chars, delete 2 chars, insert ‘ing’. Operations are tab-separated. Inserted text is escaped using %xx notation.
Parameters: | diffs – Array of diff tuples. |
---|---|
Returns: | Delta text. |
loc is a location in text1, compute and return the equivalent location in text2. e.g. “The cat” vs “The big cat”, 1->1, 5->8
Parameters: |
|
---|---|
Returns: | Location within text2. |
Initialise the alphabet for the Bitap algorithm.
Parameters: | pattern – The text to encode. |
---|---|
Returns: | Hash of character locations. |
Locate the best instance of ‘pattern’ in ‘text’ near ‘loc’ using the Bitap algorithm.
Parameters: |
|
---|---|
Returns: | Best match index or -1. |
Locate the best instance of ‘pattern’ in ‘text’ near ‘loc’.
Parameters: |
|
---|---|
Returns: | Best match index or -1. |
Increase the context until it is unique, but don’t let the pattern expand beyond Match_MaxBits.
Parameters: |
|
---|
Add some padding on text start and end so that edges can match something. Intended to be called only from within patch_apply.
Parameters: | patches – Array of patch objects. |
---|---|
Returns: | The padding string added to each side. |
Merge a set of patches onto the text. Return a patched text, as well as a list of true/false values indicating which patches were applied.
Parameters: |
|
---|---|
Returns: | Two element Array, containing the new text and an array of boolean values. |
Given an array of patches, return another array that is identical.
Parameters: | patches – Array of patch objects. |
---|---|
Returns: | Array of patch objects. |
Parse a textual representation of patches and return a list of patch objects.
Parameters: | textline – Text representation of patches. |
---|---|
Returns: | Array of patch objects. |
Raises ValueError: | |
If invalid input. |
Compute a list of patches to turn text1 into text2. Use diffs if provided, otherwise compute it ourselves. There are four ways to call this function, depending on what data is available to the caller: Method 1: a = text1, b = text2 Method 2: a = diffs Method 3 (optimal): a = text1, b = diffs Method 4 (deprecated, use method 3): a = text1, b = text2, c = diffs
Parameters: |
|
---|---|
Returns: | Array of patch objects. |
Look through the patches and break up any which are longer than the maximum limit of the match algorithm.
Parameters: | patches – Array of patch objects. |
---|
Take a list of patches and return a textual representation.
Parameters: | patches – Array of patch objects. |
---|---|
Returns: | Text representation of patches. |
Class representing one patch operation.
This module contains some temporary glue to make us work with md5 hashes on old and new versions of Python. The function md5_f() wraps whatever is available.
Access and/or modify INI files
Example:
>>> from StringIO import StringIO
>>> sio = StringIO('''# configure foo-application
... [foo]
... bar1 = qualia
... bar2 = 1977
... [foo-ext]
... special = 1''')
>>> cfg = INIConfig(sio)
>>> print cfg.foo.bar1
qualia
>>> print cfg['foo-ext'].special
1
>>> cfg.foo.newopt = 'hi!'
>>> print cfg
# configure foo-application
[foo]
bar1 = qualia
bar2 = 1977
newopt = hi!
[foo-ext]
special = 1
iterate over a file by only using the file object’s readline method
Caching dictionary like object that discards the least recently used objects when number of cached items exceeds maxsize.
cullsize is the fraction of items that will be discarded when maxsize is reached.
free memory by deleting old items from cache
Return an iterator that yields the weak references to the values.
The references are not guaranteed to be ‘live’ at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the values around longer than needed.
Return a list of weak references to the values.
The references are not guaranteed to be ‘live’ at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the values around longer than needed.
Supports a hybrid Unicode string that can also have a list of alternate strings in the strings attribute
A specialized Option Parser for recursing through directories.
add_option(opt_str, ..., kwarg=val, ...)
-> (values : Values, args : [string])
Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new – whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired.
Checks to see if subdir under options.output needs to be created, creates if neccessary.
Defines the given option, replacing an existing one of the same short name if neccessary...
Declare that you are done with this OptionParser. This cleans up reference cycles so the OptionParser (and all objects referenced by it) can be garbage-collected promptly. After calling destroy(), the OptionParser is unusable.
Set parsing to stop on the first non-option. Use this if you have a command processor which runs another command that has options of its own and you want to make sure these options don’t get confused.
Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments. This is the default behavior. See also disable_interspersed_args() and the class documentation description of the attribute allow_interspersed_args.
Print a usage message incorporating ‘msg’ to stderr and exit. If you override this in a subclass, it should not return – it should either exit or raise an exception.
Write the temp outputfile to its final destination.
returns a formatted manpage
Make a nice help string for describing formats...
Gets the absolute path to an input file.
Gets the absolute path to an output file.
Gets the absolute path to a template file.
Gets an output filename based on the input filename.
Works out which output format and processor method to use...
Get the options required to pass to the filtermethod...
Gets an output filename based on the input filename.
returns the usage string for the given option
returns the usage string for the given option
Sets up a progress bar appropriate to the options and files.
Checks if this path has been excluded.
Checks if fileoption is a recursive file.
Checks if this is a valid input filename.
Makes a subdirectory (recursively if neccessary).
Opens the input file.
Opens the output file.
Opens the template file (if required).
Opens a temporary output file.
Parses the command line options, handling implicit input/output args.
Print an extended help message, listing all options and any help text provided with them, to ‘file’ (default stdout).
outputs a manpage for the program using the help information
Print the usage message for the current program (self.usage) to ‘file’ (default stdout). Any occurrence of the string “%prog” in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined.
Print the version message for this program (self.version) to ‘file’ (default stdout). As with print_usage(), any occurrence of “%prog” in self.version is replaced by the current program’s name. Does nothing if self.version is empty or undefined.
Process an individual file.
Use a list of files, and find a common base directory for them.
Recurse through directories and return files to be processed.
Recurse through directories and process files.
Shows that we are progressing...
Parses the arguments, and runs recursiveprocess with the resulting options...
sets the usage string - if usage not given, uses getusagestring for each option
Sets the errorlevel options.
Sets the format options using the given format dictionary.
Parameters: | formats (Dictionary) – The dictionary keys should be:
The dictionary values should be tuples of outputformat (string) and processor method. |
---|
creates a manpage option that allows the optionparser to generate a manpage
Sets the progress options.
Splits pathname into name and ext, and removes the extsep.
Parameters: | pathname (string) – A file path |
---|---|
Returns: | root, ext |
Return type: | tuple |
Splits an inputpath into name and extension.
Splits a templatepath into name and extension.
Returns whether the given template exists...
Print a warning message incorporating ‘msg’ to stderr and exit.
module that provides modified DOM functionality for our needs
Note that users of ourdom should ensure that no code might still use classes directly from minidom, like minidom.Element, minidom.Document or methods such as minidom.parseString, since the functionality provided here will not be in those objects.
A reimplementation of getElementsByTagName as an iterator.
Note that this is not compatible with getElementsByTagName that returns a list, therefore, the class below exposes this through yieldElementsByTagName
returns the node’s text by iterating through the child nodes
Parse a file into a DOM by filename or file object.
Parse a file into a DOM from a string.
limits the search to within tags occuring in onlysearch
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.
Function/method decorator that will cause only the decorated callable to be profiled (with a KCacheGrind profiler) and saved to the specified file.
Parameters: |
---|
Progress bar utilities for reporting feedback on the progress of an application.
An ultra-simple progress indicator that just writes a dot for each action
show a dot for progress :-)
A ProgressBar which knows how to go back to the beginning of the line.
A ProgressBar that just writes out the messages without any progress display
String processing utilities for extracting strings with various kinds of delimiters
escape control characters in the given string
Extracts a doublequote-delimited string from a string, allowing for backslash-escaping returns tuple of (quoted string with quotes, still in string at end).
Extracts a doublequote-delimited string from a string, allowing for backslash-escaping includeescapes can also be a function that takes the whole escaped string and returns the replaced version.
Returns a list of locations where substr occurs in searchin locations are not allowed to overlap
decodes source using HTML entities e.g. © -> ©
encodes source using HTML entities e.g. © -> ©
Encodes source in the escaped-unicode encoding used by Java .properties files
Encodes source in the escaped-unicode encoding used by Mozilla .properties files.
Decodes source from the escaped-unicode encoding used by .properties files.
Java uses Latin1 by default, and Mozilla uses UTF-8 by default.
Since the .decode(“unicode-escape”) routine decodes everything, and we don’t want to we reimplemented the algorithm from Python Objects/unicode.c in Python and modify it to retain escaped control characters.
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.
Intelligent parser error
this is a simple parser
apply a tokenizer to a set of text, flattening the result
apply a set of tokenizers to a set of text, flattening each time
finds the position of the given token in the text
finds the line and character position of the given character
checks whether a token is a string token
checks whether a token should be kept together
raises a ParserError
this removes whitespace but lets it separate things out into separate tokens
this separates out tokens in tokenlist from whitespace etc
makes strings in text into tokens...
tokenize the text string with the standard tokenizers
takes away repeated quotes (escapes) and returns the string represented by the text
escapes quotes as neccessary and returns a string representing the text
A wrapper for sys.stdout etc that provides tell() for current position
Text wrapping and filling.
Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you’ll probably have to override _wrap_chunks().
Reformat the single paragraph in ‘text’ to fit in lines of no more than ‘self.width’ columns, and return a new string containing the entire wrapped paragraph.
Reformat the single paragraph in ‘text’ so it fits in lines of no more than ‘self.width’ columns, and return a list of wrapped lines. Tabs in ‘text’ are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space.
Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in ‘text’ so it fits in lines of no more than ‘width’ columns, and return a list of wrapped lines. By default, tabs in ‘text’ are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour.
Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in ‘text’ to fit in lines of no more than ‘width’ columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour.
This module allows doctest to find typechecked functions.
Currently, doctest verifies functions to make sure that their globals() dict is the __dict__ of their module. In the case of decorated functions, the globals() dict is not the right one.
To enable support for doctest do:
import typecheck.doctest_support
This import must occur before any calls to doctest methods.
Wrapper to launch the bundled CherryPy server.
Use CherryPy’s WSGI server, a multithreaded scallable server.
A wrapper for cStringIO that provides more of the functions of StringIO at the speed of cStringIO
catches the output before it is closed and sends it to an onclose method
wrap the underlying close method, to pass the value to onclose before it goes
use this method to force the closing of the stream if it isn’t closed yet
Helper functions for working with XML.
Extracts the plain text content out of the given node.
This method checks the xml:space attribute of the given node, and takes an optional default to use in case nothing is specified in this node.
Gets the xml:lang attribute on node
Gets the xml:space attribute on node
Returns name in Clark notation within the given namespace.
This is needed throughout lxml.
Normalize the given text for implementation of xml:space="default".
normalize spaces following the nodes xml:space, or alternatively the given xml_space parameter.
Sets the xml:lang attribute on node
Sets the xml:space attribute on node
Return a non-normalized string in the node subtree
Return a (space) normalized string in the node subtree
All ancestors with xml:space=’preserve’
All xml:space attributes in the ancestors
simpler wrapper to the elementtree XML parser
simple wrapper for xml objects
gets an attribute of the tag
get a child with the given tag name
get all children with the given tag name
get some contained text
get some contained values...
writes the object as XML to a file...
Constructs an alternative fixtag procedure that will use appropriate names for namespaces.