desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Resets all state variables so that we can start with a new text.'
def reset(self):
self.htmlStash.reset() self.references.clear() for extension in self.registeredExtensions: extension.reset()
'Set the output format for the class instance.'
def set_output_format(self, format):
try: self.serializer = self.output_formats[format.lower()] except KeyError: message(CRITICAL, ('Invalid Output Format: "%s". Use one of %s.' % (format, self.output_formats.keys())))
'Convert markdown to serialized XHTML or HTML. Keyword arguments: * source: Source text as a Unicode string.'
def convert(self, source):
if (not source.strip()): return u'' try: source = unicode(source) except UnicodeDecodeError: message(CRITICAL, 'UnicodeDecodeError: Markdown only accepts unicode or ascii input.') return u'' source = source.replace(STX, '').replace(ETX, '') source...
'Converts a markdown file and returns the HTML as a unicode string. Decodes the file using the provided encoding (defaults to utf-8), passes the file content to markdown, and outputs the html to either the provided stream or the file with provided name, using the same encoding as the source file. **Note:** This is the ...
def convertFile(self, input=None, output=None, encoding=None):
encoding = (encoding or 'utf-8') input_file = codecs.open(input, mode='r', encoding=encoding) text = input_file.read() input_file.close() text = text.lstrip(u'\ufeff') html = self.convert(text) if isinstance(output, (str, unicode)): output_file = codecs.open(output, 'w', encoding=enc...
'Create an instance of an Extention. Keyword arguments: * configs: A dict of configuration setting used by an Extension.'
def __init__(self, configs={}):
self.config = configs
'Return a setting for the given key or an empty string.'
def getConfig(self, key):
if (key in self.config): return self.config[key][0] else: return ''
'Return all config settings as a list of tuples.'
def getConfigInfo(self):
return [(key, self.config[key][1]) for key in self.config.keys()]
'Set a config setting for `key` with the given `value`.'
def setConfig(self, key, value):
self.config[key][0] = value
'Add the various proccesors and patterns to the Markdown Instance. This method must be overriden by every extension. Keyword arguments: * md: The Markdown instance. * md_globals: Global variables in the markdown module namespace.'
def extendMarkdown(self, md, md_globals):
raise NotImplementedError, ('Extension "%s.%s" must define an "extendMarkdown"method.' % (self.__class__.__module__, self.__class__.__name__))
'Set a new state.'
def set(self, state):
self.append(state)
'Step back one step in nested state.'
def reset(self):
self.pop()
'Test that top (current) level is of given state.'
def isstate(self, state):
if len(self): return (self[(-1)] == state) else: return False
'Parse a markdown document into an ElementTree. Given a list of lines, an ElementTree object (not just a parent Element) is created and the root element is passed to the parser as the parent. The ElementTree object is returned. This should only be called on an entire document, not pieces.'
def parseDocument(self, lines):
self.root = markdown.etree.Element(markdown.DOC_TAG) self.parseChunk(self.root, '\n'.join(lines)) return markdown.etree.ElementTree(self.root)
'Parse a chunk of markdown text and attach to given etree node. While the ``text`` argument is generally assumed to contain multiple blocks which will be split on blank lines, it could contain only one block. Generally, this method would be called by extensions when block parsing is required. The ``parent`` etree Eleme...
def parseChunk(self, parent, text):
self.parseBlocks(parent, text.split('\n\n'))
'Process blocks of markdown text and attach to given etree node. Given a list of ``blocks``, each blockprocessor is stepped through until there are no blocks left. While an extension could potentially call this method directly, it\'s generally expected to be used internally. This is a public method as an extension may ...
def parseBlocks(self, parent, blocks):
while blocks: for processor in self.blockprocessors.values(): if processor.test(parent, blocks[0]): processor.run(parent, blocks) break
'Return the value of the item at the given zero-based index.'
def value_for_index(self, index):
return self[self.keyOrder[index]]
'Insert the key, value pair before the item with the given index.'
def insert(self, index, key, value):
if (key in self.keyOrder): n = self.keyOrder.index(key) del self.keyOrder[n] if (n < index): index -= 1 self.keyOrder.insert(index, key) super(OrderedDict, self).__setitem__(key, value)
'Return a copy of this object.'
def copy(self):
obj = self.__class__(self) obj.keyOrder = self.keyOrder[:] return obj
'Replace the normal dict.__repr__ with a version that returns the keys in their sorted order.'
def __repr__(self):
return ('{%s}' % ', '.join([('%r: %r' % (k, v)) for (k, v) in self.items()]))
'Return the index of a given key.'
def index(self, key):
return self.keyOrder.index(key)
'Return index or None for a given location.'
def index_for_location(self, location):
if (location == '_begin'): i = 0 elif (location == '_end'): i = None elif (location.startswith('<') or location.startswith('>')): i = self.index(location[1:]) if location.startswith('>'): if (i >= len(self)): i = None else: ...
'Insert by key location.'
def add(self, key, value, location):
i = self.index_for_location(location) if (i is not None): self.insert(i, key, value) else: self.__setitem__(key, value)
'Change location of an existing item.'
def link(self, key, location):
n = self.keyOrder.index(key) del self.keyOrder[n] i = self.index_for_location(location) try: if (i is not None): self.keyOrder.insert(i, key) else: self.keyOrder.append(key) except Error: self.keyOrder.insert(n, key) raise Error
'Create a new dd and parse the block with it as the parent.'
def create_item(parent, block):
dd = markdown.etree.SubElement(parent, 'dd') self.parser.parseBlocks(dd, [block])
'Add an instance of DefListProcessor to BlockParser.'
def extendMarkdown(self, md, md_globals):
md.parser.blockprocessors.add('defindent', DefListIndentProcessor(md.parser), '>indent') md.parser.blockprocessors.add('deflist', DefListProcessor(md.parser), '>ulist')
'Return meta data or config data.'
def _getMeta(self):
base_url = self.config['base_url'][0] end_url = self.config['end_url'][0] html_class = self.config['html_class'][0] if hasattr(self.md, 'Meta'): if self.md.Meta.has_key('wiki_base_url'): base_url = self.md.Meta['wiki_base_url'][0] if self.md.Meta.has_key('wiki_end_url'): ...
'Setup configs.'
def __init__(self, configs):
self.config = {'PLACE_MARKER': ['///Footnotes Go Here///', 'The text string that marks where the footnotes go'], 'UNIQUE_IDS': [False, 'Avoid name collisions across multiple calls to reset().']} for (key, value) in configs: self.config[key][0] = value ...
'Add pieces to Markdown.'
def extendMarkdown(self, md, md_globals):
md.registerExtension(self) self.parser = md.parser md.preprocessors.add('footnote', FootnotePreprocessor(self), '<reference') FOOTNOTE_RE = '\\[\\^([^\\]]*)\\]' md.inlinePatterns.add('footnote', FootnotePattern(FOOTNOTE_RE, self), '<reference') md.treeprocessors.add('footnote', FootnoteTreeproce...
'Clear the footnotes on reset, and prepare for a distinct document.'
def reset(self):
self.footnotes = markdown.odict.OrderedDict() self.unique_prefix += 1
'Return ElementTree Element that contains Footnote placeholder.'
def findFootnotesPlaceholder(self, root):
def finder(element): for child in element: if child.text: if (child.text.find(self.getConfig('PLACE_MARKER')) > (-1)): return (child, True) if child.tail: if (child.tail.find(self.getConfig('PLACE_MARKER')) > (-1)): ...
'Store a footnote for later retrieval.'
def setFootnote(self, id, text):
self.footnotes[id] = text
'Return footnote link id.'
def makeFootnoteId(self, id):
if self.getConfig('UNIQUE_IDS'): return ('fn:%d-%s' % (self.unique_prefix, id)) else: return ('fn:%s' % id)
'Return footnote back-link id.'
def makeFootnoteRefId(self, id):
if self.getConfig('UNIQUE_IDS'): return ('fnref:%d-%s' % (self.unique_prefix, id)) else: return ('fnref:%s' % id)
'Return div of footnotes as et Element.'
def makeFootnotesDiv(self, root):
if (not self.footnotes.keys()): return None div = etree.Element('div') div.set('class', 'footnote') hr = etree.SubElement(div, 'hr') ol = etree.SubElement(div, 'ol') for id in self.footnotes.keys(): li = etree.SubElement(ol, 'li') li.set('id', self.makeFootnoteId(id)) ...
'Recursively find all footnote definitions in lines. Keywords: * lines: A list of lines of text Return: A list of lines with footnote definitions removed.'
def _handleFootnoteDefinitions(self, lines):
(i, id, footnote) = self._findFootnoteDefinition(lines) if id: plain = lines[:i] (detabbed, theRest) = self.detectTabbed(lines[(i + 1):]) self.footnotes.setFootnote(id, ((footnote + '\n') + '\n'.join(detabbed))) more_plain = self._handleFootnoteDefinitions(theRest) return...
'Find the parts of a footnote definition. Keywords: * lines: A list of lines of text. Return: A three item tuple containing the index of the first line of a footnote definition, the id of the definition and the body of the definition.'
def _findFootnoteDefinition(self, lines):
counter = 0 for line in lines: m = DEF_RE.match(line) if m: return (counter, m.group(2), m.group(3)) counter += 1 return (counter, None, None)
'Find indented text and remove indent before further proccesing. Keyword arguments: * lines: an array of strings Returns: a list of post processed items and the unused remainder of the original list'
def detectTabbed(self, lines):
items = [] item = (-1) i = 0 def detab(line): match = TABBED_RE.match(line) if match: return match.group(4) for line in lines: if line.strip(): line = detab(line) if line: items.append(line) i += 1 ...
'Add MetaPreprocessor to Markdown instance.'
def extendMarkdown(self, md, md_globals):
md.preprocessors.add('meta', MetaPreprocessor(md), '_begin')
'Parse Meta-Data and store in Markdown.Meta.'
def run(self, lines):
meta = {} key = None while 1: line = lines.pop(0) if (line.strip() == ''): break m1 = META_RE.match(line) if m1: key = m1.group('key').lower().strip() meta[key] = [m1.group('value').strip()] else: m2 = META_MORE_RE.match...
'Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with optional line numbers. The output should then be styled with css to your liking. No styles are applied by default - only styling hooks (i.e.: <span class="k">). returns : A string of html.'
def hilite(self):
self.src = self.src.strip('\n') self._getLang() try: from pygments import highlight from pygments.lexers import get_lexer_by_name, guess_lexer, TextLexer from pygments.formatters import HtmlFormatter except ImportError: txt = self._escape(self.src) if self.linenos...
'basic html escaping'
def _escape(self, txt):
txt = txt.replace('&', '&amp;') txt = txt.replace('<', '&lt;') txt = txt.replace('>', '&gt;') txt = txt.replace('"', '&quot;') return txt
'Use <ol> for line numbering'
def _number(self, txt):
txt = txt.replace(' DCTB ', (' ' * TAB_LENGTH)) txt = txt.replace((' ' * 4), '&nbsp; &nbsp; ') txt = txt.replace((' ' * 3), '&nbsp; &nbsp;') txt = txt.replace((' ' * 2), '&nbsp; ') lines = txt.splitlines() txt = '<div class="codehilite"><pre><ol>\n' for line in lin...
'Determines language of a code block from shebang lines and whether said line should be removed or left in place. If the sheband line contains a path (even a single /) then it is assumed to be a real shebang lines and left alone. However, if no path is given (e.i.: #!python or :::python) then it is assumed to be a mock...
def _getLang(self):
import re lines = self.src.split('\n') fl = lines.pop(0) c = re.compile('\n (?:(?:::+)|(?P<shebang>[#]!)) DCTB # Shebang or 2 or more colons.\n (?P<path>(?:/\\w+)*[/ ])? ...
'Find code blocks and store in htmlStash.'
def run(self, root):
blocks = root.getiterator('pre') for block in blocks: children = block.getchildren() if ((len(children) == 1) and (children[0].tag == 'code')): code = CodeHilite(children[0].text, linenos=self.config['force_linenos'][0], css_class=self.config['css_class'][0]) placeholder ...
'Add HilitePostprocessor to Markdown instance.'
def extendMarkdown(self, md, md_globals):
hiliter = HiliteTreeprocessor(md) hiliter.config = self.config md.treeprocessors.add('hilite', hiliter, '_begin')
'Add FencedBlockPreprocessor to the Markdown instance.'
def extendMarkdown(self, md, md_globals):
md.preprocessors.add('fenced_code_block', FencedBlockPreprocessor(md), '_begin')
'Match and store Fenced Code Blocks in the HtmlStash.'
def run(self, lines):
text = '\n'.join(lines) while 1: m = FENCED_BLOCK_RE.search(text) if m: lang = '' if m.group('lang'): lang = (LANG_TAG % m.group('lang')) code = (CODE_WRAP % (lang, self._escape(m.group('code')))) placeholder = self.markdown.htmlSta...
'basic html escaping'
def _escape(self, txt):
txt = txt.replace('&', '&amp;') txt = txt.replace('<', '&lt;') txt = txt.replace('>', '&gt;') txt = txt.replace('"', '&quot;') return txt
'Slugify a string, to make it URL friendly.'
def slugify(self, value):
import unicodedata value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\\w\\s-]', '', value).strip().lower()) return re.sub('[-\\s]+', '-', value)
'Insert AbbrPreprocessor before ReferencePreprocessor.'
def extendMarkdown(self, md, md_globals):
md.preprocessors.add('abbr', AbbrPreprocessor(md), '<reference')
'Find and remove all Abbreviation references from the text. Each reference is set as a new AbbrPattern in the markdown instance.'
def run(self, lines):
new_text = [] for line in lines: m = ABBR_REF_RE.match(line) if m: abbr = m.group('abbr').strip() title = m.group('title').strip() self.markdown.inlinePatterns[('abbr-%s' % abbr)] = AbbrPattern(self._generate_pattern(abbr), title) else: new...
'Given a string, returns an regex pattern to match that string. \'HTML\' -> r\'(?P<abbr>[H][T][M][L])\' Note: we force each char as a literal match (in brackets) as we don\'t know what they will be beforehand.'
def _generate_pattern(self, text):
chars = list(text) for i in range(len(chars)): chars[i] = ('[%s]' % chars[i]) return ('(?P<abbr>\\b%s\\b)' % ''.join(chars))
'Parse a table block and build table.'
def run(self, parent, blocks):
block = blocks.pop(0).split('\n') header = block[:2] rows = block[2:] border = False if header[0].startswith('|'): border = True align = [] for c in self._split_row(header[1], border): if (c.startswith(':') and c.endswith(':')): align.append('center') elif...
'Given a row of text, build table cells.'
def _build_row(self, row, parent, align, border):
tr = etree.SubElement(parent, 'tr') tag = 'td' if (parent.tag == 'thead'): tag = 'th' cells = self._split_row(row, border) for (i, a) in enumerate(align): c = etree.SubElement(tr, tag) try: c.text = cells[i].strip() except IndexError: c.text = ...
'split a row of text into list of cells.'
def _split_row(self, row, border):
if border: if row.startswith('|'): row = row[1:] if row.endswith('|'): row = row[:(-1)] return row.split('|')
'Add an instance of TableProcessor to BlockParser.'
def extendMarkdown(self, md, md_globals):
md.parser.blockprocessors.add('table', TableProcessor(md.parser), '<hashheader')
'Register extension instances.'
def extendMarkdown(self, md, md_globals):
md.registerExtensions(extensions, self.config)
'Return meta data suported by this ext as a tuple'
def _get_meta(self):
level = (int(self.config['level'][0]) - 1) force = self._str2bool(self.config['forceid'][0]) if hasattr(self.md, 'Meta'): if self.md.Meta.has_key('header_level'): level = (int(self.md.Meta['header_level'][0]) - 1) if self.md.Meta.has_key('header_forceid'): force = sel...
'Convert a string to a booleen value.'
def _str2bool(self, s, default=False):
s = str(s) if (s.lower() in ['0', 'f', 'false', 'off', 'no', 'n']): return False elif (s.lower() in ['1', 't', 'true', 'on', 'yes', 'y']): return True return default
'Ensure ID is unique. Append \'_1\', \'_2\'... if not'
def _unique_id(self, id):
while (id in self.IDs): m = IDCOUNT_RE.match(id) if m: id = ('%s_%d' % (m.group(1), (int(m.group(2)) + 1))) else: id = ('%s_%d' % (id, 1)) self.IDs.append(id) return id
'Return ID from Header text.'
def _create_id(self, header):
h = '' for c in header.lower().replace(' ', '_'): if (c in ID_CHARS): h += c elif (c not in punctuation): h += '+' return self._unique_id(h)
'Return the last child of an etree element.'
def lastChild(self, parent):
if len(parent): return parent[(-1)] else: return None
'Remove a tab from the front of each line of the given text.'
def detab(self, text):
newtext = [] lines = text.split('\n') for line in lines: if line.startswith((' ' * markdown.TAB_LENGTH)): newtext.append(line[markdown.TAB_LENGTH:]) elif (not line.strip()): newtext.append('') else: break return ('\n'.join(newtext), '\n'.joi...
'Remove a tab from front of lines but allowing dedented lines.'
def looseDetab(self, text, level=1):
lines = text.split('\n') for i in range(len(lines)): if lines[i].startswith(((' ' * markdown.TAB_LENGTH) * level)): lines[i] = lines[i][(markdown.TAB_LENGTH * level):] return '\n'.join(lines)
'Test for block type. Must be overridden by subclasses. As the parser loops through processors, it will call the ``test`` method on each to determine if the given block of text is of that type. This method must return a boolean ``True`` or ``False``. The actual method of testing is left to the needs of that particular ...
def test(self, parent, block):
pass
'Run processor. Must be overridden by subclasses. When the parser determines the appropriate type of a block, the parser will call the corresponding processor\'s ``run`` method. This method should parse the individual lines of the block and append them to the etree. Note that both the ``parent`` and ``etree`` keywords ...
def run(self, parent, blocks):
pass
'Create a new li and parse the block with it as the parent.'
def create_item(self, parent, block):
li = markdown.etree.SubElement(parent, 'li') self.parser.parseBlocks(li, [block])
'Get level of indent based on list level.'
def get_level(self, parent, block):
m = self.INDENT_RE.match(block) if m: indent_level = (len(m.group(1)) / markdown.TAB_LENGTH) else: indent_level = 0 if self.parser.state.isstate('list'): level = 1 else: level = 0 while (indent_level > level): child = self.lastChild(parent) if (chi...
'Remove ``>`` from beginning of a line.'
def clean(self, line):
m = self.RE.match(line) if (line.strip() == '>'): return '' elif m: return m.group(2) else: return line
'Break a block into list items.'
def get_items(self, block):
items = [] for line in block.split('\n'): m = self.CHILD_RE.match(line) if m: items.append(m.group(3)) elif self.INDENT_RE.match(line): if items[(-1)].startswith((' ' * markdown.TAB_LENGTH)): items[(-1)] = ('%s\n%s' % (items[(-1)], line)) ...
'Subclasses of Postprocessor should implement a `run` method, which takes the html document as a single text string and returns a (possibly modified) string.'
def run(self, text):
pass
'Iterate over html stash and restore "safe" html.'
def run(self, text):
for i in range(self.markdown.htmlStash.html_counter): (html, safe) = self.markdown.htmlStash.rawHtmlBlocks[i] if (self.markdown.safeMode and (not safe)): if (str(self.markdown.safeMode).lower() == 'escape'): html = self.escape(html) elif (str(self.markdown.saf...
'Basic html escaping'
def escape(self, html):
html = html.replace('&', '&amp;') html = html.replace('<', '&lt;') html = html.replace('>', '&gt;') return html.replace('"', '&quot;')
'Transform the array from Ideone into a Python dictionary.'
@staticmethod def _transform_to_dict(result):
result_dict = {} property_list = result.item for item in property_list: result_dict[item.key[0]] = item.value[0] return result_dict
'Raise an exception if the Ideone gave us an error.'
@staticmethod def _handle_error(result_dict):
error = result_dict['error'] if (error == Ideone.ERROR_OK): return else: raise IdeoneError(error)
'Convert the Ideone language list into a Python dictionary.'
@staticmethod def _collapse_language_array(language_array):
language_dict = {} for language in language_array.item: key = language.key[0] value = language.value[0] language_dict[key] = value return language_dict
'Translate a human readable langauge name into its Ideone integer representation. Keyword Arguments * langauge_name: a string of the language (e.g. "c++") Returns An integer representation of the language. Notes We use a local cache of languages if available, else we grab the list of languages from Ideone. We test for...
def _translate_language_name(self, language_name):
languages = self.languages() language_id = None for (ideone_index, ideone_language) in languages.items(): if (ideone_language.lower() == language_name.lower()): return ideone_index simple_languages = dict(((k, v.split('(')[0].strip()) for (k, v) in languages.items())) for (ideone...
'Create a submission and upload it to Ideone. Keyword Arguments * source_code: a string of the programs source code * language_name: the human readable language string (e.g. \'python\') * language_id: the ID of the programming language * std_input: the string to pass to the program on stdin * run: a boolean flag to sig...
def create_submission(self, source_code, language_name=None, language_id=None, std_input='', run=True, private=False):
language_id = (language_id or self._translate_language_name(language_name)) result = self.client.service.createSubmission(self.user, self.password, source_code, language_id, std_input, run, private) result_dict = Ideone._transform_to_dict(result) Ideone._handle_error(result_dict) return result_dict
'Given the unique link of a submission, returns its current status. Keyword Arguments * link: the unique id string of a submission Returns A dictionary of the error, the result code and the status code. Notes Status specifies the stage of execution. * status < 0 means the program awaits compilation * status == 0 means ...
def submission_status(self, link):
result = self.client.service.getSubmissionStatus(self.user, self.password, link) result_dict = Ideone._transform_to_dict(result) Ideone._handle_error(result_dict) return result_dict
'Return a dictionary of requested details about a submission with the id of link. Keyword Arguments * link: the unique string ID of a submission * with_source: should we request the source code * with_input: request the program input * with_output: request the program output * with_stderr: request the error output * wi...
def submission_details(self, link, with_source=True, with_input=True, with_output=True, with_stderr=True, with_compilation_info=True):
result = self.client.service.getSubmissionDetails(self.user, self.password, link, with_source, with_input, with_output, with_stderr, with_compilation_info) result_dict = Ideone._transform_to_dict(result) Ideone._handle_error(result_dict) return result_dict
'Get a list of supported languages and cache it. Examples >>> ideone_object.languages() {\'error\': \'OK\', \'languages\': {1: "C++ (gcc-4.3.4)", 2: "Pascal (gpc) (gpc 20070904)", 125: "Falcon (falcon-0.9.6.6)"}}'
def languages(self):
if (self._language_dict is None): result = self.client.service.getLanguages(self.user, self.password) result_dict = Ideone._transform_to_dict(result) Ideone._handle_error(result_dict) languages = result_dict['languages'] result_dict['languages'] = Ideone._collapse_language_ar...
'A test function that always returns the same thing. >>> ideone_object = Ideone(\'username\', \'password\') >>> ideone_object.test_function() {\'answerToLifeAndEverything\': 42, \'error\': "OK", \'moreHelp\': "ideone.com", \'oOok\': True, \'pi\': 3.14}'
def test(self):
result = self.client.service.testFunction(self.user, self.password) result_dict = Ideone._transform_to_dict(result) Ideone._handle_error(result_dict) return result_dict
'@param url: The URL for the WSDL. @type url: str @param kwargs: keyword arguments. @keyword faults: Raise faults raised by server (default:True), else return tuple from service method invocation as (http code, object). @type faults: boolean @keyword proxy: An http proxy to be specified on requests (default:{}). The pr...
def __init__(self, url, **kwargs):
client = Client(url, **kwargs) self.__client__ = client
'Get an instance of a WSDL type by name @param name: The name of a type defined in the WSDL. @type name: str @return: An instance on success, else None @rtype: L{sudsobject.Object}'
def get_instance(self, name):
return self.__client__.factory.create(name)
'Get an instance of an enumeration defined in the WSDL by name. @param name: The name of a enumeration defined in the WSDL. @type name: str @return: An instance on success, else None @rtype: L{sudsobject.Object}'
def get_enum(self, name):
return self.__client__.factory.create(name)
'@param resolver: A schema object name resolver. @type resolver: L{resolver.Resolver}'
def __init__(self, resolver):
self.resolver = resolver
'build a an object for the specified typename as defined in the schema'
def build(self, name):
if isinstance(name, basestring): type = self.resolver.find(name) if (type is None): raise TypeNotFound(name) else: type = name cls = type.name if type.mixed(): data = Factory.property(cls) else: data = Factory.object(cls) resolved = type.resolv...
'process the specified type then process its children'
def process(self, data, type, history):
if (type in history): return if type.enum(): return history.append(type) resolved = type.resolve() value = None if type.unbounded(): value = [] elif (len(resolved) > 0): if resolved.mixed(): value = Factory.property(resolved.name) md = ...
'add required attributes'
def add_attributes(self, data, type):
for (attr, ancestry) in type.attributes(): name = ('_%s' % attr.name) value = attr.get_default() setattr(data, name, value)
'get whether or not to skip the specified child'
def skip_child(self, child, ancestry):
if child.any(): return True for x in ancestry: if x.choice(): return True return False
'get the ordering'
def ordering(self, type):
result = [] for (child, ancestry) in type.resolve(): name = child.name if (child.name is None): continue if child.isattr(): name = ('_%s' % child.name) result.append(name) return result
'Get whether string I{s} contains special characters. @param s: A string to check. @type s: str @return: True if needs encoding. @rtype: boolean'
def needsEncoding(self, s):
if isinstance(s, basestring): for c in self.special: if (c in s): return True return False
'Encode special characters found in string I{s}. @param s: A string to encode. @type s: str @return: The encoded string. @rtype: str'
def encode(self, s):
if (isinstance(s, basestring) and self.needsEncoding(s)): for x in self.encodings: s = re.sub(x[0], x[1], s) return s
'Decode special characters encodings found in string I{s}. @param s: A string to decode. @type s: str @return: The decoded string. @rtype: str'
def decode(self, s):
if (isinstance(s, basestring) and ('&' in s)): for x in self.decodings: s = s.replace(x[0], x[1]) return s
'SAX parse XML text. @param file: Parse a python I{file-like} object. @type file: I{file-like} object. @param string: Parse string XML. @type string: str'
def parse(self, file=None, string=None):
timer = metrics.Timer() timer.start() (sax, handler) = self.saxparser() if (file is not None): sax.parse(file) timer.stop() metrics.log.debug('sax (%s) duration: %s', file, timer) return handler.nodes[0] if (string is not None): source = InputSource(N...
'Encode (escape) special XML characters. @return: The text with XML special characters escaped. @rtype: L{Text}'
def escape(self):
if (not self.escaped): post = sax.encoder.encode(self) escaped = (post != self) return Text(post, lang=self.lang, escaped=escaped) return self
'Decode (unescape) special XML characters. @return: The text with escaped XML special characters decoded. @rtype: L{Text}'
def unescape(self):
if self.escaped: post = sax.encoder.decode(self) return Text(post, lang=self.lang) return self
'@param date: The value of the object. @type date: (date|str) @raise ValueError: When I{date} is invalid.'
def __init__(self, date):
if isinstance(date, dt.date): self.date = date return if isinstance(date, basestring): self.date = self.__parse(date) return raise ValueError, type(date)
'Get the I{year} component. @return: The year. @rtype: int'
def year(self):
return self.date.year
'Get the I{month} component. @return: The month. @rtype: int'
def month(self):
return self.date.month