repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
karyon/django
refs/heads/master
tests/test_exceptions/__init__.py
12133432
onshape/jenkins-job-builder
refs/heads/master
tests/wrappers/__init__.py
12133432
matthiasplappert/motion_classification
refs/heads/master
src/toolkit/__init__.py
12133432
citrix-openstack-build/sahara
refs/heads/master
sahara/tests/unit/db/migration/__init__.py
12133432
klausman/scion
refs/heads/master
python/test/lib/packet/pcb_test.py
1
# Copyright 2015 ETH Zurich # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """ :mod:`lib_packet_pcb_test` --- lib.packet.pcb unit tests ======================================================== """ # Stdlib from unittest.mock import patch # External packages import nose import nose.tools as ntools # SCION from lib.packet.pcb import ASMarking, PCBMarking, PathSegment from lib.types import ASMExtType, RoutingPolType from test.testcommon import create_mock_full _ISD_AS1 = 1 << 20 | 1 _ISD_AS2 = 1 << 20 | 2 _ISD_AS1_BYTES = _ISD_AS1.to_bytes(4, 'big') _ISD_AS2_BYTES = _ISD_AS2.to_bytes(4, 'big') def mk_pcbm_p(remoteInIF=22): return create_mock_full({ "inIA": _ISD_AS1, "remoteInIF": remoteInIF, "inMTU": 4000, "outIA": _ISD_AS2, "remoteOutIF": 33, "hof": b"hof"}, class_=PCBMarking) class TestASMarkingFromValues(object): """ Unit tests for lib.packet.pcb.ASMarking.from_values """ @patch("lib.packet.pcb.ASMarking.P_CLS", autospec=True) def test_full(self, p_cls): msg = p_cls.new_message.return_value pcbms = [] for i in range(3): pcbms.append(create_mock_full({"p": "pcbm %d" % i})) exts = [] exts.append(create_mock_full({"EXT_TYPE": ASMExtType.ROUTING_POLICY, "p": {"polType": RoutingPolType.ALLOW_AS, "itf": 0, "isdases": [_ISD_AS1]}})) # Call ASMarking.from_values(_ISD_AS1, 2, 3, pcbms, "mtu", exts, ifid_size=14) # Tests p_cls.new_message.assert_called_once_with( isdas=_ISD_AS1, trcVer=2, certVer=3, ifIDSize=14, mtu="mtu") msg.init.assert_called_once_with("hops", 3) for i, pcbm in enumerate(msg.pcbms): ntools.eq_("pcbm %d" % i, pcbm) class TestPathSegmentGetPath(object): """ Unit test for lib.packet.pcb.PathSegment.get_path """ def _setup(self): asms = [] for i in range(3): pcbm = create_mock_full({"hof()": "hof %d" % i}) asms.append(create_mock_full({"pcbm()": pcbm})) inst = PathSegment(None) inst.iter_asms = create_mock_full(return_value=asms) return inst @patch("lib.packet.pcb.SCIONPath", autospec=True) @patch("lib.packet.pcb.PathSegment.infoF", autospec=True) @patch("lib.packet.pcb.PathSegment._setup", autospec=True) def test_fwd(self, _, info, scion_path): inst = self._setup() info.return_value = create_mock_full({"cons_dir_flag": False}) # Call ntools.eq_(inst.get_path(), scion_path.from_values.return_value) # Tests ntools.eq_(info.return_value.cons_dir_flag, False) scion_path.from_values.assert_called_once_with( info.return_value, ["hof 0", "hof 1", "hof 2"]) @patch("lib.packet.pcb.SCIONPath", autospec=True) @patch("lib.packet.pcb.PathSegment.infoF", autospec=True) @patch("lib.packet.pcb.PathSegment._setup", autospec=True) def test_reverse(self, _, info, scion_path): inst = self._setup() info.return_value = create_mock_full({"cons_dir_flag": False}) # Call ntools.eq_(inst.get_path(True), scion_path.from_values.return_value) # Tests ntools.eq_(info.return_value.cons_dir_flag, True) scion_path.from_values.assert_called_once_with( info.return_value, ["hof 2", "hof 1", "hof 0"]) if __name__ == "__main__": nose.run(defaultTest=__name__)
rshkarin/afm-particle-analysis
refs/heads/master
nanoscope/parameter.py
1
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals import datetime import re import six __all__ = ['parse_parameter'] class CiaoParameter(object): """ Parent class for generic values from the header. """ type = 'P' def __init__(self, parameter, hard_value): self.parameter = parameter self.hard_value = self._parse_value(hard_value) def __str__(self): return '{0}: {1}'.format(self.parameter, self.hard_value) def _parse_value(self, value): """ Try to parse and return the value as the following values: * ``datetime.datetime`` * ``int`` * ``float`` * ``str`` * ``None`` Trailing whitespace is stripped and an empty string is returned as ``None``. """ try: return datetime.datetime.strptime(value, '%I:%M:%S %p %a %b %d %Y') except: try: split_value = value.strip().split(' ')[0] if split_value == '' or split_value == 'None': return None except AttributeError: return value try: return int(split_value) except ValueError: try: return float(split_value) except ValueError: return value class CiaoValue(CiaoParameter): """ Represents a Ciao value object. """ type = 'V' def __init__(self, parameter, soft_scale, hard_scale, hard_value): self.parameter = parameter self.soft_scale = self._parse_value(soft_scale) self.hard_scale = self._parse_value(hard_scale) self.hard_value = self._parse_value(hard_value) def __str__(self): return '{0}: [{1}] ({2}) {3}'.format(self.parameter, self.soft_scale, self.hard_scale, self.hard_value) class CiaoScale(CiaoParameter): """ Represents a Ciao scale object. """ type = 'C' def __init__(self, parameter, soft_scale, hard_value): self.parameter = parameter self.soft_scale = self._parse_value(soft_scale) self.hard_value = self._parse_value(hard_value) def __str__(self): return '{0}: [{1}] {2}'.format(self.parameter, self.soft_scale, self.hard_value) class CiaoSelect(CiaoParameter): """ Represents a Ciao select object. """ type = 'S' def __init__(self, parameter, internal, external): self.parameter = parameter self.internal = internal self.external = external def __str__(self): return '{0}: [{1}] "{2}"'.format(self.parameter, self.internal, self.external) class CiaoSectionHeader(CiaoParameter): """ Represents a Ciao section header. """ type = 'H' def __init__(self, header): self.header = header def __str__(self): return self.header def decode(string, encoding='utf-8'): """ Decodes the binary string with the specified encoding (or passes through a non-binary string) and strips newlines off the end. :param string: The string, may be binary or non-binary but should be text data. :param encoding: The encoding to use for a binary string. Defaults to utf-8. :returns: The decoded and stripped string. :raises TypeError: If the passed parameter is not a valid string. :raises UnicodeError: When decoding a binary string if there are encoding errors. """ if isinstance(string, six.text_type): return string.rstrip('\r\n') try: string = string.decode(encoding='iso-8859-1').rstrip('\r\n') except AttributeError: raise TypeError('Invalid type {} passed.'.format(type(string))) return string def parse_parameter(string, encoding='utf-8'): """ Factory function that parses the parameter string and creates the appropriate CiaoParameter object. :param string: The parameter string to parse. :returns: The CiaoParameter that corresponds with the parameter string. :raises ValueError: If the string is not a valid CiaoParameter. """ string = decode(string, encoding) header_match = re.match(r'\\\*(?P<header>.+)', string) if header_match is not None: return CiaoSectionHeader(header_match.group('header')) regex = re.compile(r'\\(?P<ciao>@?)(?:(?P<group>[0-9]+):)?' r'(?P<parameter>[^:]+): ' r'(?:(?P<type>[VCS]) )?(?P<value>.*)') m = regex.match(string) if m is None: raise ValueError('"{0}" is not a valid Ciao Parameter'.format(string)) parameter_type = m.group('type') value = m.group('value') if parameter_type == 'V': # value value_regex = (r'(?:\[(?P<soft_scale>[^\[\]]*)\] )?' r'(?:\((?P<hard_scale>[^\(\)]*)\) )?' r'(?P<hard_value>[^\[\]\(\)]*)') vm = re.match(value_regex, value) return CiaoValue(m.group('parameter'), vm.group('soft_scale'), vm.group('hard_scale'), vm.group('hard_value')) elif parameter_type == 'C': # scale scale_regex = (r'(?:\[(?P<soft_scale>[^\[\]]*)\] )?' r'(?P<hard_value>[^\[\]]*)') cm = re.match(scale_regex, value) return CiaoScale(m.group('parameter'), cm.group('soft_scale'), cm.group('hard_value')) elif parameter_type == 'S': # select select_regex = (r'(?:\[(?P<internal_designation>[^\[\]]*)\] )?' r'(?:\"(?P<external_designation>[^\"]*)\")?') sm = re.match(select_regex, value) return CiaoSelect(m.group('parameter'), sm.group('internal_designation'), sm.group('external_designation')) else: # simple value return CiaoParameter(m.group('parameter'), value)
UdK-VPT/Open_eQuarter
refs/heads/master
mole/stat_corr/rb_present_wall_uvalue_SDH_by_building_age_lookup.py
1
# coding: utf8 # OeQ autogenerated lookup function for 'U-Values of Walls in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the "Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013' import math import numpy as np import oeqLookuptable as oeq def get(*xin): l_lookup = oeq.lookuptable( [ 1849,1.7, 1850,1.7, 1851,1.7, 1852,1.7, 1853,1.7, 1854,1.7, 1855,1.7, 1856,1.7, 1857,1.7, 1858,1.7, 1859,1.7, 1860,1.7, 1861,1.7, 1862,1.7, 1863,1.7, 1864,1.7, 1865,1.7, 1866,1.7, 1867,1.7, 1868,1.7, 1869,1.7, 1870,1.7, 1871,1.7, 1872,1.7, 1873,1.7, 1874,1.7, 1875,1.7, 1876,1.7, 1877,1.7, 1878,1.7, 1879,1.7, 1880,1.7, 1881,1.7, 1882,1.7, 1883,1.7, 1884,1.7, 1885,1.7, 1886,1.7, 1887,1.7, 1888,1.7, 1889,1.7, 1890,1.7, 1891,1.7, 1892,1.7, 1893,1.7, 1894,1.7, 1895,1.7, 1896,1.7, 1897,1.7, 1898,1.7, 1899,1.7, 1900,1.7, 1901,1.7, 1902,1.7, 1903,1.7, 1904,1.7, 1905,1.7, 1906,1.7, 1907,1.7, 1908,1.7, 1909,1.7, 1910,1.7, 1911,1.7, 1912,1.7, 1913,1.7, 1914,1.7, 1915,1.7, 1916,1.7, 1917,1.7, 1918,1.7, 1919,1.7, 1920,1.7, 1921,1.7, 1922,1.7, 1923,1.7, 1924,1.7, 1925,1.7, 1926,1.7, 1927,1.7, 1928,1.7, 1929,1.7, 1930,1.7, 1931,1.7, 1932,1.7, 1933,1.7, 1934,1.7, 1935,1.7, 1936,1.699, 1937,1.699, 1938,1.699, 1939,1.7, 1940,1.7, 1941,1.7, 1942,1.7, 1943,1.7, 1944,1.688, 1945,1.666, 1946,1.635, 1947,1.591, 1948,1.533, 1949,1.462, 1950,1.385, 1951,1.309, 1952,1.245, 1953,1.2, 1954,1.18, 1955,1.18, 1956,1.19, 1957,1.2, 1958,1.204, 1959,1.204, 1960,1.201, 1961,1.2, 1962,1.202, 1963,1.206, 1964,1.206, 1965,1.2, 1966,1.185, 1967,1.161, 1968,1.133, 1969,1.1, 1970,1.067, 1971,1.036, 1972,1.012, 1973,1, 1974,1.001, 1975,1.007, 1976,1.01, 1977,1, 1978,0.97, 1979,0.922, 1980,0.864, 1981,0.8, 1982,0.737, 1983,0.679, 1984,0.632, 1985,0.6, 1986,0.586, 1987,0.586, 1988,0.593, 1989,0.6, 1990,0.602, 1991,0.601, 1992,0.599, 1993,0.6, 1994,0.605, 1995,0.61, 1996,0.61, 1997,0.6, 1998,0.576, 1999,0.54, 2000,0.497, 2001,0.45, 2002,0.403, 2003,0.36, 2004,0.324, 2005,0.3, 2006,0.3, 2007,0.3, 2008,0.3, 2009,0.3, 2010,0.303, 2011,0.303, 2012,0.302, 2013,0.3, 2014,0.3, 2015,0.3, 2016,0.3, 2017,0.3, 2018,0.3, 2019,0.3, 2020,0.3, 2021,0.3]) return(l_lookup.lookup(xin))
internetmosquito/flask-scheduler
refs/heads/master
project/api/views.py
1
__author__ = 'mosquito' from functools import wraps from flask import flash, redirect, jsonify, \ session, url_for, Blueprint, make_response from project import db from project.models import Appointment ################ #### config #### ################ api_blueprint = Blueprint('api', __name__) ########################## #### helper functions #### ########################## def login_required(test): @wraps(test) def wrap(*args, **kwargs): if 'logged_in' in session: return test(*args, **kwargs) else: flash('You need to login first.') return redirect(url_for('users.login')) return wrap def open_appointments(): return db.session.query(Appointment).filter_by(status='1')\ .order_by(Appointment.due_date.asc()) def closed_appointments(): return db.session.query(Appointment).filter_by(status='0')\ .order_by(Appointment.due_date.asc()) ################ #### routes #### ################ @api_blueprint.route('/api/v1/appointments/') def api_appointments(): results = db.session.query(Appointment).limit(10).offset(0).all() json_results = [] for result in results: data = { 'appointment_id': result.appointment_id, 'appointment name': result.name, 'due date': str(result.due_date), 'priority': result.priority, 'creation date': str(result.creation_date), 'user id': result.user_id } json_results.append(data) return jsonify(items=json_results) @api_blueprint.route('/api/v1/appointments/<int:appointment_id>') def appointment(appointment_id): result = db.session.query(Appointment).filter_by(appointment_id=appointment_id).first() if result: result = { 'appointment_id': result.appointment_id, 'appointment name': result.name, 'due date': str(result.due_date), 'priority': result.priority, 'posted date': str(result.creation_date), 'user id': result.user_id } code = 200 else: result = {'error': 'Specified appointment does not exist'} code = 404 return make_response(jsonify(result), code)
Maccimo/intellij-community
refs/heads/master
python/testData/refactoring/rename/renameImportSubModuleAs/before/p1/foo.py
415
def f(): pass
wangli1426/heron
refs/heads/master
heron/pyheron/tests/python/component_unittest.py
8
# Copyright 2016 Twitter. All rights reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # pylint: disable=missing-docstring # pylint: disable=protected-access import unittest from heron.pyheron.src.python.component import HeronComponentSpec, GlobalStreamId from heron.pyheron.src.python.stream import Grouping, Stream class ComponentSpecTest(unittest.TestCase): def test_sanitize_args(self): # good args spec = HeronComponentSpec(name="string", python_class_path="string.path", is_spout=True, par=1) self.assertIsNotNone(spec) name_none_spec = HeronComponentSpec(name=None, python_class_path="string.path", is_spout=True, par=1) self.assertIsNotNone(name_none_spec) # bad name with self.assertRaises(AssertionError): HeronComponentSpec(123, "classpath", True, 1) with self.assertRaises(AssertionError): HeronComponentSpec(False, "classpath", True, 1) # bad classpath with self.assertRaises(AssertionError): HeronComponentSpec("name", {}, True, 1) with self.assertRaises(AssertionError): HeronComponentSpec("name", None, True, 1) # bad is_spout with self.assertRaises(AssertionError): HeronComponentSpec("name", "classpath", 1, 1) with self.assertRaises(AssertionError): HeronComponentSpec("name", "classpath", None, 1) # bad par with self.assertRaises(AssertionError): HeronComponentSpec("name", "classpath", True, "1") with self.assertRaises(AssertionError): HeronComponentSpec("name", "classpath", True, 1.35) with self.assertRaises(AssertionError): HeronComponentSpec("name", "classpath", True, -21) with self.assertRaises(AssertionError): HeronComponentSpec("name", "classpath", True, None) def test_sanitize_config(self): # empty dict ret = HeronComponentSpec._sanitize_config({}) self.assertEqual(ret, {}) # non-dict given with self.assertRaises(TypeError): HeronComponentSpec._sanitize_config("{key: value}") with self.assertRaises(TypeError): HeronComponentSpec._sanitize_config(True) with self.assertRaises(TypeError): HeronComponentSpec._sanitize_config(None) # non-string key with self.assertRaises(TypeError): HeronComponentSpec._sanitize_config({['k', 'e', 'y']: "value"}) with self.assertRaises(TypeError): HeronComponentSpec._sanitize_config({None: "value"}) # convert boolean value ret = HeronComponentSpec._sanitize_config({"key": True}) self.assertEqual(ret["key"], "true") ret = HeronComponentSpec._sanitize_config({"key": False}) self.assertEqual(ret["key"], "false") # convert int and float ret = HeronComponentSpec._sanitize_config({"key": 10}) self.assertEqual(ret["key"], "10") ret = HeronComponentSpec._sanitize_config({"key": -2400000}) self.assertEqual(ret["key"], "-2400000") ret = HeronComponentSpec._sanitize_config({"key": 0.0000001}) self.assertEqual(ret["key"], "1e-07") ret = HeronComponentSpec._sanitize_config({"key": -15.33333}) self.assertEqual(ret["key"], "-15.33333") # non-string value -> should expect the same object ret = HeronComponentSpec._sanitize_config({"key": ['v', 'a', 'l', 'u', 'e']}) self.assertEqual(ret["key"], ['v', 'a', 'l', 'u', 'e']) ret = HeronComponentSpec._sanitize_config({"key": None}) self.assertEqual(ret["key"], None) def test_sanitize_inputs(self): # Note that _sanitize_inputs() should only be called after HeronComponentSpec's # name attribute is set # invalid inputs given as argument (valid ones are either dict, list, tuple or None) invalid_spec = HeronComponentSpec("name", "classpath", True, 1, inputs="string") with self.assertRaises(TypeError): invalid_spec._sanitize_inputs() invalid_spec = HeronComponentSpec("name", "classpath", True, 1, inputs=100) with self.assertRaises(TypeError): invalid_spec._sanitize_inputs() # dict <HeronComponentSpec -> Grouping> from_spec = HeronComponentSpec("spout", "sp_clspath", True, 1) to_spec = HeronComponentSpec("bolt", "bl_clspath", False, 1, inputs={from_spec: Grouping.SHUFFLE}) ret = to_spec._sanitize_inputs() self.assertEqual(ret, {GlobalStreamId("spout", "default"): Grouping.SHUFFLE}) from_spec = HeronComponentSpec("spout", "sp_clspath", True, 1) from_spec.outputs = [Stream(name='another_stream')] to_spec = HeronComponentSpec("bolt", "bl_clspath", False, 1, inputs={from_spec['another_stream']: Grouping.ALL}) ret = to_spec._sanitize_inputs() self.assertEqual(ret, {GlobalStreamId("spout", "another_stream"): Grouping.ALL}) # HeronComponentSpec's name attribute not set from_spec = HeronComponentSpec(None, "sp_clspath", True, 1) to_spec = HeronComponentSpec("bolt", "bl_clspath", False, 1, inputs={from_spec: Grouping.ALL}) with self.assertRaises(RuntimeError): to_spec._sanitize_inputs() # dict <GlobalStreamId -> Grouping> inputs_dict = {GlobalStreamId("some_spout", "some_stream"): Grouping.NONE, GlobalStreamId("another_spout", "default"): Grouping.fields(['word', 'count'])} spec = HeronComponentSpec("bolt", "classpath", False, 1, inputs=inputs_dict) ret = spec._sanitize_inputs() self.assertEqual(ret, inputs_dict) # list of HeronComponentSpec from_spec1 = HeronComponentSpec("spout1", "sp1_cls", True, 1) from_spec2 = HeronComponentSpec("spout2", "sp2_cls", True, 1) to_spec = HeronComponentSpec("bolt", "bl_cls", False, 1, inputs=[from_spec1, from_spec2]) ret = to_spec._sanitize_inputs() self.assertEqual(ret, {GlobalStreamId("spout1", "default"): Grouping.SHUFFLE, GlobalStreamId("spout2", "default"): Grouping.SHUFFLE}) # HeronComponentSpec's name attribute not set from_spec = HeronComponentSpec(None, "sp_clspath", True, 1) to_spec = HeronComponentSpec("bolt", "bl_clspath", False, 1, inputs=[from_spec]) with self.assertRaises(RuntimeError): to_spec._sanitize_inputs() # list of GlobalStreamId inputs_list = [GlobalStreamId("spout1", "default"), GlobalStreamId("spout2", "some_stream")] spec = HeronComponentSpec("bolt", "bl_cls", False, 1, inputs=inputs_list) ret = spec._sanitize_inputs() self.assertEqual(ret, dict(zip(inputs_list, [Grouping.SHUFFLE] * 2))) # list of neither GlobalStreamId nor HeronComponentSpec inputs_list = [None, 123, "string", [GlobalStreamId("sp", "default")]] spec = HeronComponentSpec("bolt", "bl_cls", False, 1, inputs=inputs_list) with self.assertRaises(ValueError): spec._sanitize_inputs() # pylint: disable=redefined-variable-type # pylint: disable=pointless-statement def test_sanitize_outputs(self): # outputs is None (no argument to outputs) spec = HeronComponentSpec("spout", "class", True, 1) ret = spec._sanitize_outputs() self.assertIsNone(ret) # outputs neither list nor tuple spec = HeronComponentSpec("spout", "class", True, 1) spec.outputs = "string" with self.assertRaises(TypeError): spec._sanitize_outputs() # output list contains a non-string and non-Stream object spec = HeronComponentSpec("spout", "class", True, 1) spec.outputs = ["string", False, 123] with self.assertRaises(TypeError): spec._sanitize_outputs() # output list is all string spec = HeronComponentSpec("spout", "class", True, 1) spec.outputs = ["string", "hello", "heron"] ret = spec._sanitize_outputs() self.assertEqual(ret, {"default": ["string", "hello", "heron"]}) # output list has mixed stream spec = HeronComponentSpec("spout", "class", True, 1) spec.outputs = ["string", "hello", Stream(fields=["abc", "def"], name="another_stream"), Stream(fields=["another", "default"], name="default")] ret = spec._sanitize_outputs() self.assertEqual(ret, {"default": ["string", "hello", "another", "default"], "another_stream": ["abc", "def"]}) def test_get_out_streamids(self): # outputs is none spec = HeronComponentSpec("spout", "class", True, 1) ret = spec.get_out_streamids() self.assertEqual(ret, set()) # outputs neither list nor tuple spec = HeronComponentSpec("spout", "class", True, 1) spec.outputs = "string" with self.assertRaises(TypeError): spec.get_out_streamids() # outputs sane spec = HeronComponentSpec("spout", "class", True, 1) spec.outputs = ["string", "hello", Stream(fields=["abc", "def"], name="another_stream"), Stream(fields=["another", "default"], name="default")] ret = spec.get_out_streamids() self.assertEqual(ret, {"default", "another_stream"}) def test_get_item(self): # HeronComponentSpec name set spec = HeronComponentSpec("spout", "class", True, 1) spec.outputs = ["string", "hello", Stream(fields=["abc", "def"], name="another_stream"), Stream(fields=["another", "default"], name="default")] ret = spec['another_stream'] self.assertEqual(ret, GlobalStreamId("spout", "another_stream")) # HeronComponentSpec name not set spec = HeronComponentSpec(None, "class", True, 1) spec.outputs = ["string", "hello", Stream(fields=["abc", "def"], name="another_stream"), Stream(fields=["another", "default"], name="default")] ret = spec['default'] self.assertEqual(ret, GlobalStreamId(spec, "default")) # stream id not registered spec = HeronComponentSpec(None, "class", True, 1) spec.outputs = ["string", "hello", Stream(fields=["abc", "def"], name="another_stream"), Stream(fields=["another", "default"], name="default")] with self.assertRaises(ValueError): spec['non_existent_stream'] class GlobalStreamIdTest(unittest.TestCase): def test_constructor(self): # component id not string nor HeronComponentSpec with self.assertRaises(TypeError): GlobalStreamId(componentId=123, streamId="default") # stream id not string with self.assertRaises(TypeError): GlobalStreamId(componentId="component", streamId=12345) def test_component_id_property(self): # component id is string gsi = GlobalStreamId(componentId="component", streamId="stream") self.assertEqual(gsi.component_id, "component") # component id is HeronComponentSpec with name spec = HeronComponentSpec("spout", "class", True, 1) gsi = GlobalStreamId(spec, "stream") self.assertEqual(gsi.component_id, "spout") # component id is HeronComponentSpec without name spec = HeronComponentSpec(None, "class", True, 1) gsi = GlobalStreamId(spec, "stream") # expecting "<No name available for HeronComponentSpec yet, uuid: %s>" self.assertIn(spec.uuid, gsi.component_id)
ski7777/fttxpy
refs/heads/master
fttxpy/__init__.py
1
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # class Debug(): PrintPackageRaw = False PrintUnknownPackageRaw = True PrintPackagePing = False PrintChecksumError = False PrintPackageSendError = False PrintPackageJSONRX = False PrintPackageJSONTX = False PrintSendRetriesWrongCC = False # import TX functionalities from .high_level import fttxpy
Metaswitch/calico-nova
refs/heads/calico-readme
nova/tests/functional/v3/test_extension_info.py
6
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. import re import mock from oslo.serialization import jsonutils from nova.api.openstack import extensions as api_extensions from nova.tests.functional.v3 import api_sample_base def fake_soft_extension_authorizer(api_name, extension_name): def authorize(context, action=None): return True return authorize class ExtensionInfoAllSamplesJsonTest(api_sample_base.ApiSampleTestBaseV3): all_extensions = True @mock.patch.object(api_extensions, 'soft_extension_authorizer') def test_list_extensions(self, soft_auth): soft_auth.side_effect = fake_soft_extension_authorizer response = self._do_get('extensions') subs = self._get_regexes() self._verify_response('extensions-list-resp', subs, response, 200) class ExtensionInfoSamplesJsonTest(api_sample_base.ApiSampleTestBaseV3): sample_dir = "extension-info" extra_extensions_to_load = ["os-create-backup"] @mock.patch.object(api_extensions, 'soft_extension_authorizer') def test_get_extensions(self, soft_auth): soft_auth.side_effect = fake_soft_extension_authorizer response = self._do_get('extensions/os-create-backup') subs = self._get_regexes() self._verify_response('extensions-get-resp', subs, response, 200) class ExtensionInfoFormatTest(api_sample_base.ApiSampleTestBaseV3): # NOTE: To check all extension formats, here makes authorize() return True # always instead of fake_policy.py because most extensions are not set as # "discoverable" in fake_policy.py. all_extensions = True def _test_list_extensions(self, key, pattern): with mock.patch.object(api_extensions, 'soft_extension_authorizer') as api_mock: def fake_soft_extension_authorizer(api_name, extension_name): def authorize(context, action=None): return True return authorize api_mock.side_effect = fake_soft_extension_authorizer response = self._do_get('extensions') response = jsonutils.loads(response.content) extensions = response['extensions'] pattern_comp = re.compile(pattern) for ext in extensions: self.assertIsNotNone(pattern_comp.match(ext[key]), '%s does not match with %s' % (ext[key], pattern)) def test_list_extensions_name_format(self): # name should be CamelCase. pattern = '^[A-Z]{1}[a-z]{1}[a-zA-Z]*$' self._test_list_extensions('name', pattern)
sandeepkbhat/pylearn2
refs/heads/master
pylearn2/datasets/hdf5_deprecated.py
30
""" Objects for datasets serialized in HDF5 format (.h5). """ __author__ = "Steven Kearnes" __copyright__ = "Copyright 2014, Stanford University" __license__ = "3-clause BSD" try: import h5py except ImportError: h5py = None import numpy as np from theano.compat.six.moves import xrange import warnings from pylearn2.datasets.dense_design_matrix import (DenseDesignMatrix, DefaultViewConverter) from pylearn2.space import CompositeSpace, VectorSpace, IndexSpace from pylearn2.utils.iteration import FiniteDatasetIterator, safe_izip from pylearn2.utils import contains_nan class HDF5DatasetDeprecated(DenseDesignMatrix): """ Dense dataset loaded from an HDF5 file. Parameters ---------- filename : str HDF5 file name. X : str, optional Key into HDF5 file for dataset design matrix. topo_view: str, optional Key into HDF5 file for topological view of dataset. y : str, optional Key into HDF5 file for dataset targets. load_all : bool, optional (default False) If true, datasets are loaded into memory instead of being left on disk. cache_size: int, optionally specify the size in bytes for the chunk cache of the HDF5 library. Useful when the HDF5 files has large chunks and when using a sequantial iterator. The chunk cache allows to only access the disk for the chunks and then copy the batches to the GPU from memory, which can result in a significant speed up. Sensible default values depend on the size of your data and the batch size you wish to use. A rule of thumb is to make a chunk contain 100 - 1000 batches and make sure they encompass complete samples. kwargs : dict, optional Keyword arguments passed to `DenseDesignMatrix`. """ def __init__(self, filename, X=None, topo_view=None, y=None, load_all=False, cache_size=None, **kwargs): self.load_all = load_all if h5py is None: raise RuntimeError("Could not import h5py.") if cache_size: propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS) settings = list(propfaid.get_cache()) settings[2] = cache_size propfaid.set_cache(*settings) fid = h5py.h5f.open(filename, fapl=propfaid) self._file = h5py.File(fid) else: self._file = h5py.File(filename) if X is not None: X = self.get_dataset(X, load_all) if topo_view is not None: topo_view = self.get_dataset(topo_view, load_all) if y is not None: y = self.get_dataset(y, load_all) super(HDF5DatasetDeprecated, self).__init__(X=X, topo_view=topo_view, y=y, **kwargs) def _check_labels(self): """ Sanity checks for X_labels and y_labels. Since the np.all test used for these labels does not work with HDF5 datasets, we issue a warning that those values are not checked. """ if self.X_labels is not None: assert self.X is not None assert self.view_converter is None assert self.X.ndim <= 2 if self.load_all: assert np.all(self.X < self.X_labels) else: warnings.warn("HDF5Dataset cannot perform test np.all(X < " + "X_labels). Use X_labels at your own risk.") if self.y_labels is not None: assert self.y is not None assert self.y.ndim <= 2 if self.load_all: assert np.all(self.y < self.y_labels) else: warnings.warn("HDF5Dataset cannot perform test np.all(y < " + "y_labels). Use y_labels at your own risk.") def get_dataset(self, dataset, load_all=False): """ Get a handle for an HDF5 dataset, or load the entire dataset into memory. Parameters ---------- dataset : str Name or path of HDF5 dataset. load_all : bool, optional (default False) If true, load dataset into memory. """ if load_all: data = self._file[dataset][:] else: data = self._file[dataset] data.ndim = len(data.shape) # hdf5 handle has no ndim return data def iterator(self, *args, **kwargs): """ Get an iterator for this dataset. The FiniteDatasetIterator uses indexing that is not supported by HDF5 datasets, so we change the class to HDF5DatasetIterator to override the iterator.next method used in dataset iteration. Parameters ---------- WRITEME """ iterator = super(HDF5DatasetDeprecated, self).iterator(*args, **kwargs) iterator.__class__ = HDF5DatasetIterator return iterator def set_topological_view(self, V, axes=('b', 0, 1, 'c')): """ Set up dataset topological view, without building an in-memory design matrix. This is mostly copied from DenseDesignMatrix, except: * HDF5ViewConverter is used instead of DefaultViewConverter * Data specs are derived from topo_view, not X * NaN checks have been moved to HDF5DatasetIterator.next Note that y may be loaded into memory for reshaping if y.ndim != 2. Parameters ---------- V : ndarray Topological view. axes : tuple, optional (default ('b', 0, 1, 'c')) Order of axes in topological view. """ shape = [V.shape[axes.index('b')], V.shape[axes.index(0)], V.shape[axes.index(1)], V.shape[axes.index('c')]] self.view_converter = HDF5ViewConverter(shape[1:], axes=axes) self.X = self.view_converter.topo_view_to_design_mat(V) # self.X_topo_space stores a "default" topological space that # will be used only when self.iterator is called without a # data_specs, and with "topo=True", which is deprecated. self.X_topo_space = self.view_converter.topo_space # Update data specs X_space = VectorSpace(dim=V.shape[axes.index('b')]) X_source = 'features' if self.y is None: space = X_space source = X_source else: if self.y.ndim == 1: dim = 1 else: dim = self.y.shape[-1] # check if y_labels has been specified if getattr(self, 'y_labels', None) is not None: y_space = IndexSpace(dim=dim, max_labels=self.y_labels) elif getattr(self, 'max_labels', None) is not None: y_space = IndexSpace(dim=dim, max_labels=self.max_labels) else: y_space = VectorSpace(dim=dim) y_source = 'targets' space = CompositeSpace((X_space, y_space)) source = (X_source, y_source) self.data_specs = (space, source) self.X_space = X_space self._iter_data_specs = (X_space, X_source) class HDF5DatasetIterator(FiniteDatasetIterator): """ Dataset iterator for HDF5 datasets. FiniteDatasetIterator expects a design matrix to be available, but this will not always be the case when using HDF5 datasets with topological views. Parameters ---------- dataset : Dataset Dataset over which to iterate. subset_iterator : object Iterator that returns slices of the dataset. data_specs : tuple, optional A (space, source) tuple. return_tuple : bool, optional (default False) Whether to return a tuple even if only one source is used. convert : list, optional A list of callables (in the same order as the sources in data_specs) that will be applied to each slice of the dataset. """ def next(self): """ Get the next subset of the dataset during dataset iteration. Converts index selections for batches to boolean selections that are supported by HDF5 datasets. """ next_index = self._subset_iterator.next() # convert to boolean selection sel = np.zeros(self.num_examples, dtype=bool) sel[next_index] = True next_index = sel rval = [] for data, fn in safe_izip(self._raw_data, self._convert): try: this_data = data[next_index] except TypeError: # FB: Why this try..except is there? I think this is useless. # Do not hide the original if we can't fall back. # FV: This is triggered if the shape of next_index is # incompatible with the shape of the dataset. See for an # example test_hdf5_topo_view(), where where i # next.index.shape = (10,) and data is 'data': <HDF5 # dataset "y": shape (10, 3), type "<f8"> # I think it would be better to explicitly check if # next_index.shape is incompatible with data.shape, for # instance checking if next_index.ndim == data.ndim if data.ndim > 1: this_data = data[next_index, :] else: raise # Check if the dataset data is a vector and transform it into a # one-column matrix. This is needed to automatically convert the # shape of the data later (in the format_as method of the # Space.) if fn: this_data = fn(this_data) assert not contains_nan(this_data) rval.append(this_data) rval = tuple(rval) if not self._return_tuple and len(rval) == 1: rval, = rval return rval class HDF5ViewConverter(DefaultViewConverter): """ View converter that doesn't have to transpose the data. In order to keep data on disk, does not generate a full design matrix. Instead, an instance of HDF5TopoViewConverter is returned, which transforms data from the topological view into the design view for each batch. Parameters ---------- shape : tuple Shape of this view. axes : tuple, optional (default ('b', 0, 1, 'c')) Order of axes in topological view. """ def topo_view_to_design_mat(self, V): """ Generate a design matrix from the topological view. This override of DefaultViewConverter.topo_view_to_design_mat does not attempt to transpose the topological view, since transposition is not supported by HDF5 datasets. Parameters ---------- WRITEME """ v_shape = (V.shape[self.axes.index('b')], V.shape[self.axes.index(0)], V.shape[self.axes.index(1)], V.shape[self.axes.index('c')]) if np.any(np.asarray(self.shape) != np.asarray(v_shape[1:])): raise ValueError('View converter for views of shape batch size ' 'followed by ' + str(self.shape) + ' given tensor of shape ' + str(v_shape)) rval = HDF5TopoViewConverter(V, self.axes) return rval class HDF5TopoViewConverter(object): """ Class for transforming batches from the topological view to the design matrix view. Parameters ---------- topo_view : HDF5 dataset On-disk topological view. axes : tuple, optional (default ('b', 0, 1, 'c')) Order of axes in topological view. """ def __init__(self, topo_view, axes=('b', 0, 1, 'c')): self.topo_view = topo_view self.axes = axes self.topo_view_shape = (topo_view.shape[axes.index('b')], topo_view.shape[axes.index(0)], topo_view.shape[axes.index(1)], topo_view.shape[axes.index('c')]) self.pixels_per_channel = (self.topo_view_shape[1] * self.topo_view_shape[2]) self.n_channels = self.topo_view_shape[3] self.shape = (self.topo_view_shape[0], np.product(self.topo_view_shape[1:])) self.ndim = len(self.shape) def __getitem__(self, item): """ Indexes the design matrix and transforms the requested batch from the topological view. Parameters ---------- item : slice or ndarray Batch selection. Either a slice or a boolean mask. """ sel = [slice(None)] * len(self.topo_view_shape) sel[self.axes.index('b')] = item sel = tuple(sel) V = self.topo_view[sel] batch_size = V.shape[self.axes.index('b')] rval = np.zeros((batch_size, self.pixels_per_channel * self.n_channels), dtype=V.dtype) for i in xrange(self.n_channels): ppc = self.pixels_per_channel sel = [slice(None)] * len(V.shape) sel[self.axes.index('c')] = i sel = tuple(sel) rval[:, i * ppc:(i + 1) * ppc] = V[sel].reshape(batch_size, ppc) return rval
egabancho/invenio
refs/heads/pu
invenio/modules/workflows/tasks/__init__.py
3
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from __future__ import absolute_import from ..workers.worker_celery import (celery_continue, celery_run, celery_restart) __all__ = ['celery_continue', 'celery_run', 'celery_restart']
unixer/SifBoX
refs/heads/master
packages/multimedia/kodi/defconfig/.kodi/.kodi/addons/script.module.simplejson/lib/simplejson/tool.py
262
r"""Command-line tool to validate and pretty-print JSON Usage:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 2 (char 2) """ from __future__ import with_statement import sys import simplejson as json def main(): if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'r') outfile = sys.stdout elif len(sys.argv) == 3: infile = open(sys.argv[1], 'r') outfile = open(sys.argv[2], 'w') else: raise SystemExit(sys.argv[0] + " [infile [outfile]]") with infile: try: obj = json.load(infile, object_pairs_hook=json.OrderedDict, use_decimal=True) except ValueError: raise SystemExit(sys.exc_info()[1]) with outfile: json.dump(obj, outfile, sort_keys=True, indent=' ', use_decimal=True) outfile.write('\n') if __name__ == '__main__': main()
dsdinter/learning-spark-examples
refs/heads/master
src/python/BasicMap.py
42
""" >>> from pyspark.context import SparkContext >>> sc = SparkContext('local', 'test') >>> b = sc.parallelize([1, 2, 3, 4]) >>> sorted(basicSquare(b).collect()) [1, 4, 9, 16] """ import sys from pyspark import SparkContext def basicSquare(nums): """Square the numbers""" return nums.map(lambda x: x * x) if __name__ == "__main__": master = "local" if len(sys.argv) == 2: master = sys.argv[1] sc = SparkContext(master, "BasicMap") nums = sc.parallelize([1, 2, 3, 4]) output = sorted(basicSquare(nums).collect()) for num in output: print "%i " % (num)
bakhtout/odoo-educ
refs/heads/8.0
setup/win32/win32_setup.py
363
# -*- coding: utf-8 -*- import os import glob import py2exe from distutils.core import setup execfile(os.path.join(os.path.dirname(__file__), '..', '..', 'openerp', 'release.py')) def generate_files(): actions = { 'start': ['stop', 'start'], 'stop': ['stop'], } files = [] if os.name == 'nt': files.append(("Microsoft.VC90.CRT", glob.glob('C:\Microsoft.VC90.CRT\*.*'))) for action, steps in actions.items(): fname = action + '.bat' files.append(fname) with open(fname, 'w') as fp: fp.write('@PATH=%WINDIR%\system32;%WINDIR%;%WINDIR%\System32\Wbem;.\n') for step in steps: fp.write('@net %s %s\n' % (step, nt_service_name)) return files setup( service=["win32_service"], version=version, license=license, url=url, author=author, author_email=author_email, data_files=generate_files(), options={ "py2exe": { "excludes": [ 'Tkconstants', 'Tkinter', 'tcl', '_imagingtk', 'PIL._imagingtk', 'ImageTk', 'PIL.ImageTk', 'FixTk' ], "skip_archive": 1, "optimize": 2, } }, )
evalsocket/tensorflow
refs/heads/master
object_detection/object_detection/builders/box_predictor_builder_test.py
21
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # ============================================================================== """Tests for box_predictor_builder.""" import mock import tensorflow as tf from google.protobuf import text_format from object_detection.builders import box_predictor_builder from object_detection.builders import hyperparams_builder from object_detection.protos import box_predictor_pb2 from object_detection.protos import hyperparams_pb2 class ConvolutionalBoxPredictorBuilderTest(tf.test.TestCase): def test_box_predictor_calls_conv_argscope_fn(self): conv_hyperparams_text_proto = """ regularizer { l1_regularizer { weight: 0.0003 } } initializer { truncated_normal_initializer { mean: 0.0 stddev: 0.3 } } activation: RELU_6 """ hyperparams_proto = hyperparams_pb2.Hyperparams() text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto) def mock_conv_argscope_builder(conv_hyperparams_arg, is_training): return (conv_hyperparams_arg, is_training) box_predictor_proto = box_predictor_pb2.BoxPredictor() box_predictor_proto.convolutional_box_predictor.conv_hyperparams.CopyFrom( hyperparams_proto) box_predictor = box_predictor_builder.build( argscope_fn=mock_conv_argscope_builder, box_predictor_config=box_predictor_proto, is_training=False, num_classes=10) (conv_hyperparams_actual, is_training) = box_predictor._conv_hyperparams self.assertAlmostEqual((hyperparams_proto.regularizer. l1_regularizer.weight), (conv_hyperparams_actual.regularizer.l1_regularizer. weight)) self.assertAlmostEqual((hyperparams_proto.initializer. truncated_normal_initializer.stddev), (conv_hyperparams_actual.initializer. truncated_normal_initializer.stddev)) self.assertAlmostEqual((hyperparams_proto.initializer. truncated_normal_initializer.mean), (conv_hyperparams_actual.initializer. truncated_normal_initializer.mean)) self.assertEqual(hyperparams_proto.activation, conv_hyperparams_actual.activation) self.assertFalse(is_training) def test_construct_non_default_conv_box_predictor(self): box_predictor_text_proto = """ convolutional_box_predictor { min_depth: 2 max_depth: 16 num_layers_before_predictor: 2 use_dropout: false dropout_keep_probability: 0.4 kernel_size: 3 box_code_size: 3 apply_sigmoid_to_scores: true } """ conv_hyperparams_text_proto = """ regularizer { l1_regularizer { } } initializer { truncated_normal_initializer { } } """ hyperparams_proto = hyperparams_pb2.Hyperparams() text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto) def mock_conv_argscope_builder(conv_hyperparams_arg, is_training): return (conv_hyperparams_arg, is_training) box_predictor_proto = box_predictor_pb2.BoxPredictor() text_format.Merge(box_predictor_text_proto, box_predictor_proto) box_predictor_proto.convolutional_box_predictor.conv_hyperparams.CopyFrom( hyperparams_proto) box_predictor = box_predictor_builder.build( argscope_fn=mock_conv_argscope_builder, box_predictor_config=box_predictor_proto, is_training=False, num_classes=10) self.assertEqual(box_predictor._min_depth, 2) self.assertEqual(box_predictor._max_depth, 16) self.assertEqual(box_predictor._num_layers_before_predictor, 2) self.assertFalse(box_predictor._use_dropout) self.assertAlmostEqual(box_predictor._dropout_keep_prob, 0.4) self.assertTrue(box_predictor._apply_sigmoid_to_scores) self.assertEqual(box_predictor.num_classes, 10) self.assertFalse(box_predictor._is_training) def test_construct_default_conv_box_predictor(self): box_predictor_text_proto = """ convolutional_box_predictor { conv_hyperparams { regularizer { l1_regularizer { } } initializer { truncated_normal_initializer { } } } }""" box_predictor_proto = box_predictor_pb2.BoxPredictor() text_format.Merge(box_predictor_text_proto, box_predictor_proto) box_predictor = box_predictor_builder.build( argscope_fn=hyperparams_builder.build, box_predictor_config=box_predictor_proto, is_training=True, num_classes=90) self.assertEqual(box_predictor._min_depth, 0) self.assertEqual(box_predictor._max_depth, 0) self.assertEqual(box_predictor._num_layers_before_predictor, 0) self.assertTrue(box_predictor._use_dropout) self.assertAlmostEqual(box_predictor._dropout_keep_prob, 0.8) self.assertFalse(box_predictor._apply_sigmoid_to_scores) self.assertEqual(box_predictor.num_classes, 90) self.assertTrue(box_predictor._is_training) class MaskRCNNBoxPredictorBuilderTest(tf.test.TestCase): def test_box_predictor_builder_calls_fc_argscope_fn(self): fc_hyperparams_text_proto = """ regularizer { l1_regularizer { weight: 0.0003 } } initializer { truncated_normal_initializer { mean: 0.0 stddev: 0.3 } } activation: RELU_6 op: FC """ hyperparams_proto = hyperparams_pb2.Hyperparams() text_format.Merge(fc_hyperparams_text_proto, hyperparams_proto) box_predictor_proto = box_predictor_pb2.BoxPredictor() box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.CopyFrom( hyperparams_proto) mock_argscope_fn = mock.Mock(return_value='arg_scope') box_predictor = box_predictor_builder.build( argscope_fn=mock_argscope_fn, box_predictor_config=box_predictor_proto, is_training=False, num_classes=10) mock_argscope_fn.assert_called_with(hyperparams_proto, False) self.assertEqual(box_predictor._fc_hyperparams, 'arg_scope') def test_non_default_mask_rcnn_box_predictor(self): fc_hyperparams_text_proto = """ regularizer { l1_regularizer { } } initializer { truncated_normal_initializer { } } activation: RELU_6 op: FC """ box_predictor_text_proto = """ mask_rcnn_box_predictor { use_dropout: true dropout_keep_probability: 0.8 box_code_size: 3 } """ hyperparams_proto = hyperparams_pb2.Hyperparams() text_format.Merge(fc_hyperparams_text_proto, hyperparams_proto) def mock_fc_argscope_builder(fc_hyperparams_arg, is_training): return (fc_hyperparams_arg, is_training) box_predictor_proto = box_predictor_pb2.BoxPredictor() text_format.Merge(box_predictor_text_proto, box_predictor_proto) box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.CopyFrom( hyperparams_proto) box_predictor = box_predictor_builder.build( argscope_fn=mock_fc_argscope_builder, box_predictor_config=box_predictor_proto, is_training=True, num_classes=90) self.assertTrue(box_predictor._use_dropout) self.assertAlmostEqual(box_predictor._dropout_keep_prob, 0.8) self.assertEqual(box_predictor.num_classes, 90) self.assertTrue(box_predictor._is_training) self.assertEqual(box_predictor._box_code_size, 3) def test_build_default_mask_rcnn_box_predictor(self): box_predictor_proto = box_predictor_pb2.BoxPredictor() box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.op = ( hyperparams_pb2.Hyperparams.FC) box_predictor = box_predictor_builder.build( argscope_fn=mock.Mock(return_value='arg_scope'), box_predictor_config=box_predictor_proto, is_training=True, num_classes=90) self.assertFalse(box_predictor._use_dropout) self.assertAlmostEqual(box_predictor._dropout_keep_prob, 0.5) self.assertEqual(box_predictor.num_classes, 90) self.assertTrue(box_predictor._is_training) self.assertEqual(box_predictor._box_code_size, 4) self.assertFalse(box_predictor._predict_instance_masks) self.assertFalse(box_predictor._predict_keypoints) def test_build_box_predictor_with_mask_branch(self): box_predictor_proto = box_predictor_pb2.BoxPredictor() box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.op = ( hyperparams_pb2.Hyperparams.FC) box_predictor_proto.mask_rcnn_box_predictor.conv_hyperparams.op = ( hyperparams_pb2.Hyperparams.CONV) box_predictor_proto.mask_rcnn_box_predictor.predict_instance_masks = True box_predictor_proto.mask_rcnn_box_predictor.mask_prediction_conv_depth = 512 mock_argscope_fn = mock.Mock(return_value='arg_scope') box_predictor = box_predictor_builder.build( argscope_fn=mock_argscope_fn, box_predictor_config=box_predictor_proto, is_training=True, num_classes=90) mock_argscope_fn.assert_has_calls( [mock.call(box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams, True), mock.call(box_predictor_proto.mask_rcnn_box_predictor.conv_hyperparams, True)], any_order=True) self.assertFalse(box_predictor._use_dropout) self.assertAlmostEqual(box_predictor._dropout_keep_prob, 0.5) self.assertEqual(box_predictor.num_classes, 90) self.assertTrue(box_predictor._is_training) self.assertEqual(box_predictor._box_code_size, 4) self.assertTrue(box_predictor._predict_instance_masks) self.assertEqual(box_predictor._mask_prediction_conv_depth, 512) self.assertFalse(box_predictor._predict_keypoints) class RfcnBoxPredictorBuilderTest(tf.test.TestCase): def test_box_predictor_calls_fc_argscope_fn(self): conv_hyperparams_text_proto = """ regularizer { l1_regularizer { weight: 0.0003 } } initializer { truncated_normal_initializer { mean: 0.0 stddev: 0.3 } } activation: RELU_6 """ hyperparams_proto = hyperparams_pb2.Hyperparams() text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto) def mock_conv_argscope_builder(conv_hyperparams_arg, is_training): return (conv_hyperparams_arg, is_training) box_predictor_proto = box_predictor_pb2.BoxPredictor() box_predictor_proto.rfcn_box_predictor.conv_hyperparams.CopyFrom( hyperparams_proto) box_predictor = box_predictor_builder.build( argscope_fn=mock_conv_argscope_builder, box_predictor_config=box_predictor_proto, is_training=False, num_classes=10) (conv_hyperparams_actual, is_training) = box_predictor._conv_hyperparams self.assertAlmostEqual((hyperparams_proto.regularizer. l1_regularizer.weight), (conv_hyperparams_actual.regularizer.l1_regularizer. weight)) self.assertAlmostEqual((hyperparams_proto.initializer. truncated_normal_initializer.stddev), (conv_hyperparams_actual.initializer. truncated_normal_initializer.stddev)) self.assertAlmostEqual((hyperparams_proto.initializer. truncated_normal_initializer.mean), (conv_hyperparams_actual.initializer. truncated_normal_initializer.mean)) self.assertEqual(hyperparams_proto.activation, conv_hyperparams_actual.activation) self.assertFalse(is_training) def test_non_default_rfcn_box_predictor(self): conv_hyperparams_text_proto = """ regularizer { l1_regularizer { } } initializer { truncated_normal_initializer { } } activation: RELU_6 """ box_predictor_text_proto = """ rfcn_box_predictor { num_spatial_bins_height: 4 num_spatial_bins_width: 4 depth: 4 box_code_size: 3 crop_height: 16 crop_width: 16 } """ hyperparams_proto = hyperparams_pb2.Hyperparams() text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto) def mock_conv_argscope_builder(conv_hyperparams_arg, is_training): return (conv_hyperparams_arg, is_training) box_predictor_proto = box_predictor_pb2.BoxPredictor() text_format.Merge(box_predictor_text_proto, box_predictor_proto) box_predictor_proto.rfcn_box_predictor.conv_hyperparams.CopyFrom( hyperparams_proto) box_predictor = box_predictor_builder.build( argscope_fn=mock_conv_argscope_builder, box_predictor_config=box_predictor_proto, is_training=True, num_classes=90) self.assertEqual(box_predictor.num_classes, 90) self.assertTrue(box_predictor._is_training) self.assertEqual(box_predictor._box_code_size, 3) self.assertEqual(box_predictor._num_spatial_bins, [4, 4]) self.assertEqual(box_predictor._crop_size, [16, 16]) def test_default_rfcn_box_predictor(self): conv_hyperparams_text_proto = """ regularizer { l1_regularizer { } } initializer { truncated_normal_initializer { } } activation: RELU_6 """ hyperparams_proto = hyperparams_pb2.Hyperparams() text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto) def mock_conv_argscope_builder(conv_hyperparams_arg, is_training): return (conv_hyperparams_arg, is_training) box_predictor_proto = box_predictor_pb2.BoxPredictor() box_predictor_proto.rfcn_box_predictor.conv_hyperparams.CopyFrom( hyperparams_proto) box_predictor = box_predictor_builder.build( argscope_fn=mock_conv_argscope_builder, box_predictor_config=box_predictor_proto, is_training=True, num_classes=90) self.assertEqual(box_predictor.num_classes, 90) self.assertTrue(box_predictor._is_training) self.assertEqual(box_predictor._box_code_size, 4) self.assertEqual(box_predictor._num_spatial_bins, [3, 3]) self.assertEqual(box_predictor._crop_size, [12, 12]) if __name__ == '__main__': tf.test.main()
ionutbalutoiu/ironic
refs/heads/master
ironic/api/controllers/v1/port.py
3
# Copyright 2013 UnitedStack Inc. # All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. import datetime from oslo_utils import uuidutils import pecan from pecan import rest from six.moves import http_client import wsme from wsme import types as wtypes from ironic.api.controllers import base from ironic.api.controllers import link from ironic.api.controllers.v1 import collection from ironic.api.controllers.v1 import types from ironic.api.controllers.v1 import utils as api_utils from ironic.api import expose from ironic.common import exception from ironic.common.i18n import _ from ironic import objects _DEFAULT_RETURN_FIELDS = ('uuid', 'address') class Port(base.APIBase): """API representation of a port. This class enforces type checking and value constraints, and converts between the internal object model and the API representation of a port. """ _node_uuid = None def _get_node_uuid(self): return self._node_uuid def _set_node_uuid(self, value): if value and self._node_uuid != value: try: # FIXME(comstud): One should only allow UUID here, but # there seems to be a bug in that tests are passing an # ID. See bug #1301046 for more details. node = objects.Node.get(pecan.request.context, value) self._node_uuid = node.uuid # NOTE(lucasagomes): Create the node_id attribute on-the-fly # to satisfy the api -> rpc object # conversion. self.node_id = node.id except exception.NodeNotFound as e: # Change error code because 404 (NotFound) is inappropriate # response for a POST request to create a Port e.code = http_client.BAD_REQUEST # BadRequest raise e elif value == wtypes.Unset: self._node_uuid = wtypes.Unset uuid = types.uuid """Unique UUID for this port""" address = wsme.wsattr(types.macaddress, mandatory=True) """MAC Address for this port""" extra = {wtypes.text: types.jsontype} """This port's meta data""" node_uuid = wsme.wsproperty(types.uuid, _get_node_uuid, _set_node_uuid, mandatory=True) """The UUID of the node this port belongs to""" links = wsme.wsattr([link.Link], readonly=True) """A list containing a self link and associated port links""" def __init__(self, **kwargs): self.fields = [] fields = list(objects.Port.fields) # NOTE(lucasagomes): node_uuid is not part of objects.Port.fields # because it's an API-only attribute fields.append('node_uuid') for field in fields: # Add fields we expose. if hasattr(self, field): self.fields.append(field) setattr(self, field, kwargs.get(field, wtypes.Unset)) # NOTE(lucasagomes): node_id is an attribute created on-the-fly # by _set_node_uuid(), it needs to be present in the fields so # that as_dict() will contain node_id field when converting it # before saving it in the database. self.fields.append('node_id') setattr(self, 'node_uuid', kwargs.get('node_id', wtypes.Unset)) @staticmethod def _convert_with_links(port, url, fields=None): # NOTE(lucasagomes): Since we are able to return a specified set of # fields the "uuid" can be unset, so we need to save it in another # variable to use when building the links port_uuid = port.uuid if fields is not None: port.unset_fields_except(fields) # never expose the node_id attribute port.node_id = wtypes.Unset port.links = [link.Link.make_link('self', url, 'ports', port_uuid), link.Link.make_link('bookmark', url, 'ports', port_uuid, bookmark=True) ] return port @classmethod def convert_with_links(cls, rpc_port, fields=None): port = Port(**rpc_port.as_dict()) if fields is not None: api_utils.check_for_invalid_fields(fields, port.as_dict()) return cls._convert_with_links(port, pecan.request.public_url, fields=fields) @classmethod def sample(cls, expand=True): sample = cls(uuid='27e3153e-d5bf-4b7e-b517-fb518e17f34c', address='fe:54:00:77:07:d9', extra={'foo': 'bar'}, created_at=datetime.datetime.utcnow(), updated_at=datetime.datetime.utcnow()) # NOTE(lucasagomes): node_uuid getter() method look at the # _node_uuid variable sample._node_uuid = '7ae81bb3-dec3-4289-8d6c-da80bd8001ae' fields = None if expand else _DEFAULT_RETURN_FIELDS return cls._convert_with_links(sample, 'http://localhost:6385', fields=fields) class PortPatchType(types.JsonPatchType): _api_base = Port class PortCollection(collection.Collection): """API representation of a collection of ports.""" ports = [Port] """A list containing ports objects""" def __init__(self, **kwargs): self._type = 'ports' @staticmethod def convert_with_links(rpc_ports, limit, url=None, fields=None, **kwargs): collection = PortCollection() collection.ports = [Port.convert_with_links(p, fields=fields) for p in rpc_ports] collection.next = collection.get_next(limit, url=url, **kwargs) return collection @classmethod def sample(cls): sample = cls() sample.ports = [Port.sample(expand=False)] return sample class PortsController(rest.RestController): """REST controller for Ports.""" from_nodes = False """A flag to indicate if the requests to this controller are coming from the top-level resource Nodes.""" _custom_actions = { 'detail': ['GET'], } invalid_sort_key_list = ['extra'] def _get_ports_collection(self, node_ident, address, marker, limit, sort_key, sort_dir, resource_url=None, fields=None): if self.from_nodes and not node_ident: raise exception.MissingParameterValue( _("Node identifier not specified.")) limit = api_utils.validate_limit(limit) sort_dir = api_utils.validate_sort_dir(sort_dir) marker_obj = None if marker: marker_obj = objects.Port.get_by_uuid(pecan.request.context, marker) if sort_key in self.invalid_sort_key_list: raise exception.InvalidParameterValue( _("The sort_key value %(key)s is an invalid field for " "sorting") % {'key': sort_key}) if node_ident: # FIXME(comstud): Since all we need is the node ID, we can # make this more efficient by only querying # for that column. This will get cleaned up # as we move to the object interface. node = api_utils.get_rpc_node(node_ident) ports = objects.Port.list_by_node_id(pecan.request.context, node.id, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) elif address: ports = self._get_ports_by_address(address) else: ports = objects.Port.list(pecan.request.context, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) return PortCollection.convert_with_links(ports, limit, url=resource_url, fields=fields, sort_key=sort_key, sort_dir=sort_dir) def _get_ports_by_address(self, address): """Retrieve a port by its address. :param address: MAC address of a port, to get the port which has this MAC address. :returns: a list with the port, or an empty list if no port is found. """ try: port = objects.Port.get_by_address(pecan.request.context, address) return [port] except exception.PortNotFound: return [] @expose.expose(PortCollection, types.uuid_or_name, types.uuid, types.macaddress, types.uuid, int, wtypes.text, wtypes.text, types.listtype) def get_all(self, node=None, node_uuid=None, address=None, marker=None, limit=None, sort_key='id', sort_dir='asc', fields=None): """Retrieve a list of ports. Note that the 'node_uuid' interface is deprecated in favour of the 'node' interface :param node: UUID or name of a node, to get only ports for that node. :param node_uuid: UUID of a node, to get only ports for that node. :param address: MAC address of a port, to get the port which has this MAC address. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. :param fields: Optional, a list with a specified set of fields of the resource to be returned. """ api_utils.check_allow_specify_fields(fields) if fields is None: fields = _DEFAULT_RETURN_FIELDS if not node_uuid and node: # We're invoking this interface using positional notation, or # explicitly using 'node'. Try and determine which one. # Make sure only one interface, node or node_uuid is used if (not api_utils.allow_node_logical_names() and not uuidutils.is_uuid_like(node)): raise exception.NotAcceptable() return self._get_ports_collection(node_uuid or node, address, marker, limit, sort_key, sort_dir, fields=fields) @expose.expose(PortCollection, types.uuid_or_name, types.uuid, types.macaddress, types.uuid, int, wtypes.text, wtypes.text) def detail(self, node=None, node_uuid=None, address=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): """Retrieve a list of ports with detail. Note that the 'node_uuid' interface is deprecated in favour of the 'node' interface :param node: UUID or name of a node, to get only ports for that node. :param node_uuid: UUID of a node, to get only ports for that node. :param address: MAC address of a port, to get the port which has this MAC address. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. """ if not node_uuid and node: # We're invoking this interface using positional notation, or # explicitly using 'node'. Try and determine which one. # Make sure only one interface, node or node_uuid is used if (not api_utils.allow_node_logical_names() and not uuidutils.is_uuid_like(node)): raise exception.NotAcceptable() # NOTE(lucasagomes): /detail should only work against collections parent = pecan.request.path.split('/')[:-1][-1] if parent != "ports": raise exception.HTTPNotFound resource_url = '/'.join(['ports', 'detail']) return self._get_ports_collection(node_uuid or node, address, marker, limit, sort_key, sort_dir, resource_url) @expose.expose(Port, types.uuid, types.listtype) def get_one(self, port_uuid, fields=None): """Retrieve information about the given port. :param port_uuid: UUID of a port. :param fields: Optional, a list with a specified set of fields of the resource to be returned. """ if self.from_nodes: raise exception.OperationNotPermitted api_utils.check_allow_specify_fields(fields) rpc_port = objects.Port.get_by_uuid(pecan.request.context, port_uuid) return Port.convert_with_links(rpc_port, fields=fields) @expose.expose(Port, body=Port, status_code=http_client.CREATED) def post(self, port): """Create a new port. :param port: a port within the request body. """ if self.from_nodes: raise exception.OperationNotPermitted new_port = objects.Port(pecan.request.context, **port.as_dict()) new_port.create() # Set the HTTP Location Header pecan.response.location = link.build_url('ports', new_port.uuid) return Port.convert_with_links(new_port) @wsme.validate(types.uuid, [PortPatchType]) @expose.expose(Port, types.uuid, body=[PortPatchType]) def patch(self, port_uuid, patch): """Update an existing port. :param port_uuid: UUID of a port. :param patch: a json PATCH document to apply to this port. """ if self.from_nodes: raise exception.OperationNotPermitted rpc_port = objects.Port.get_by_uuid(pecan.request.context, port_uuid) try: port_dict = rpc_port.as_dict() # NOTE(lucasagomes): # 1) Remove node_id because it's an internal value and # not present in the API object # 2) Add node_uuid port_dict['node_uuid'] = port_dict.pop('node_id', None) port = Port(**api_utils.apply_jsonpatch(port_dict, patch)) except api_utils.JSONPATCH_EXCEPTIONS as e: raise exception.PatchError(patch=patch, reason=e) # Update only the fields that have changed for field in objects.Port.fields: try: patch_val = getattr(port, field) except AttributeError: # Ignore fields that aren't exposed in the API continue if patch_val == wtypes.Unset: patch_val = None if rpc_port[field] != patch_val: rpc_port[field] = patch_val rpc_node = objects.Node.get_by_id(pecan.request.context, rpc_port.node_id) topic = pecan.request.rpcapi.get_topic_for(rpc_node) new_port = pecan.request.rpcapi.update_port( pecan.request.context, rpc_port, topic) return Port.convert_with_links(new_port) @expose.expose(None, types.uuid, status_code=http_client.NO_CONTENT) def delete(self, port_uuid): """Delete a port. :param port_uuid: UUID of a port. """ if self.from_nodes: raise exception.OperationNotPermitted rpc_port = objects.Port.get_by_uuid(pecan.request.context, port_uuid) rpc_node = objects.Node.get_by_id(pecan.request.context, rpc_port.node_id) topic = pecan.request.rpcapi.get_topic_for(rpc_node) pecan.request.rpcapi.destroy_port(pecan.request.context, rpc_port, topic)
v-iam/azure-sdk-for-python
refs/heads/master
azure-mgmt-network/azure/mgmt/network/v2016_09_01/models/application_gateway_request_routing_rule.py
2
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .sub_resource import SubResource class ApplicationGatewayRequestRoutingRule(SubResource): """Request routing rule of an application gateway. :param id: Resource ID. :type id: str :param rule_type: Rule type. Possible values are: 'Basic' and 'PathBasedRouting'. Possible values include: 'Basic', 'PathBasedRouting' :type rule_type: str or :class:`ApplicationGatewayRequestRoutingRuleType <azure.mgmt.network.v2016_09_01.models.ApplicationGatewayRequestRoutingRuleType>` :param backend_address_pool: Backend address pool resource of the application gateway. :type backend_address_pool: :class:`SubResource <azure.mgmt.network.v2016_09_01.models.SubResource>` :param backend_http_settings: Frontend port resource of the application gateway. :type backend_http_settings: :class:`SubResource <azure.mgmt.network.v2016_09_01.models.SubResource>` :param http_listener: Http listener resource of the application gateway. :type http_listener: :class:`SubResource <azure.mgmt.network.v2016_09_01.models.SubResource>` :param url_path_map: URL path map resource of the application gateway. :type url_path_map: :class:`SubResource <azure.mgmt.network.v2016_09_01.models.SubResource>` :param provisioning_state: Provisioning state of the request routing rule resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'rule_type': {'key': 'properties.ruleType', 'type': 'str'}, 'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'}, 'backend_http_settings': {'key': 'properties.backendHttpSettings', 'type': 'SubResource'}, 'http_listener': {'key': 'properties.httpListener', 'type': 'SubResource'}, 'url_path_map': {'key': 'properties.urlPathMap', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, id=None, rule_type=None, backend_address_pool=None, backend_http_settings=None, http_listener=None, url_path_map=None, provisioning_state=None, name=None, etag=None): super(ApplicationGatewayRequestRoutingRule, self).__init__(id=id) self.rule_type = rule_type self.backend_address_pool = backend_address_pool self.backend_http_settings = backend_http_settings self.http_listener = http_listener self.url_path_map = url_path_map self.provisioning_state = provisioning_state self.name = name self.etag = etag
kernsuite-debian/obit
refs/heads/master
python/scriptQuantize.py
2
# python/Obit script to quantize a FITS image # The output image is the input image written as 16 or 32 bit integers # with a quantization level a given fraction of the minimum RMS in any plane. # Arguments: # 1) Name of input FITS image to be quantized # 2) Name of output FITS image # 3) The fraction of the RMS for the quantization [def. 0.25] # All files in ./ # example: # Python scriptQuantize.py HGeomTestOut.fits \!QuantTestOut.fits 0.25 # import sys, Image, History, OSystem, OErr from Obit import Bomb # Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("Quantize", 1, 100, 1, ["../AIPSdata/"], 1, ["./"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # For debugging #print sys.argv #Bomb() # Get Filenames (FITS) inDisk = 1 outDisk = 1 inFile = sys.argv[1] outFile = sys.argv[2] # Fraction of RMS if given if (len(sys.argv)>=4): fract = float(sys.argv[3]) else: fract = 0.25 # Set data inImage = Image.newPFImage("Input image", inFile, inDisk, True, err) outImage = Image.newPFImage("Output image", outFile, outDisk, False, err) #Image.PClone(inImage, outImage, err) # Same structure etc. OErr.printErrMsg(err, "Error initializing") # Copy to quantized integer image with history print "Write quantized output image" Image.PCopyQuantizeFITS (inImage, outImage, err, fract=fract) # Copy History inHistory = History.History("inhistory", inImage.List, err) outHistory = History.History("outhistory", outImage.List, err) History.PCopyHeader(inHistory, outHistory, err) # Add this programs history outHistory.Open(History.READWRITE, err) outHistory.TimeStamp(" Start Obit "+ObitSys.pgmName,err) outHistory.WriteRec(-1,ObitSys.pgmName+" / Quantized at "+str(fract)+" RMS",err) outHistory.Close(err) # Copy back to header inHistory = History.History("inhistory", outImage.List, err) History.PCopy2Header (inHistory, outHistory, err) OErr.printErrMsg(err, "Error with history") # Say something print "Quantized",inFile,"to",outFile,"with fraction",fract # Shutdown Obit OErr.printErr(err) del ObitSys
zhouzhenghui/python-for-android
refs/heads/master
python-modules/twisted/twisted/mail/smtp.py
49
# -*- test-case-name: twisted.mail.test.test_smtp -*- # Copyright (c) 2001-2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Simple Mail Transfer Protocol implementation. """ import time, re, base64, types, socket, os, random, rfc822 import binascii from email.base64MIME import encode as encode_base64 from zope.interface import implements, Interface from twisted.copyright import longversion from twisted.protocols import basic from twisted.protocols import policies from twisted.internet import protocol from twisted.internet import defer from twisted.internet import error from twisted.internet import reactor from twisted.internet.interfaces import ITLSTransport from twisted.python import log from twisted.python import util from twisted import cred from twisted.python.runtime import platform try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # Cache the hostname (XXX Yes - this is broken) if platform.isMacOSX(): # On OS X, getfqdn() is ridiculously slow - use the # probably-identical-but-sometimes-not gethostname() there. DNSNAME = socket.gethostname() else: DNSNAME = socket.getfqdn() # Used for fast success code lookup SUCCESS = dict(map(None, range(200, 300), [])) class IMessageDelivery(Interface): def receivedHeader(helo, origin, recipients): """ Generate the Received header for a message @type helo: C{(str, str)} @param helo: The argument to the HELO command and the client's IP address. @type origin: C{Address} @param origin: The address the message is from @type recipients: C{list} of L{User} @param recipients: A list of the addresses for which this message is bound. @rtype: C{str} @return: The full \"Received\" header string. """ def validateTo(user): """ Validate the address for which the message is destined. @type user: C{User} @param user: The address to validate. @rtype: no-argument callable @return: A C{Deferred} which becomes, or a callable which takes no arguments and returns an object implementing C{IMessage}. This will be called and the returned object used to deliver the message when it arrives. @raise SMTPBadRcpt: Raised if messages to the address are not to be accepted. """ def validateFrom(helo, origin): """ Validate the address from which the message originates. @type helo: C{(str, str)} @param helo: The argument to the HELO command and the client's IP address. @type origin: C{Address} @param origin: The address the message is from @rtype: C{Deferred} or C{Address} @return: C{origin} or a C{Deferred} whose callback will be passed C{origin}. @raise SMTPBadSender: Raised of messages from this address are not to be accepted. """ class IMessageDeliveryFactory(Interface): """An alternate interface to implement for handling message delivery. It is useful to implement this interface instead of L{IMessageDelivery} directly because it allows the implementor to distinguish between different messages delivery over the same connection. This can be used to optimize delivery of a single message to multiple recipients, something which cannot be done by L{IMessageDelivery} implementors due to their lack of information. """ def getMessageDelivery(): """Return an L{IMessageDelivery} object. This will be called once per message. """ class SMTPError(Exception): pass class SMTPClientError(SMTPError): """Base class for SMTP client errors. """ def __init__(self, code, resp, log=None, addresses=None, isFatal=False, retry=False): """ @param code: The SMTP response code associated with this error. @param resp: The string response associated with this error. @param log: A string log of the exchange leading up to and including the error. @type log: L{str} @param isFatal: A boolean indicating whether this connection can proceed or not. If True, the connection will be dropped. @param retry: A boolean indicating whether the delivery should be retried. If True and the factory indicates further retries are desirable, they will be attempted, otherwise the delivery will be failed. """ self.code = code self.resp = resp self.log = log self.addresses = addresses self.isFatal = isFatal self.retry = retry def __str__(self): if self.code > 0: res = ["%.3d %s" % (self.code, self.resp)] else: res = [self.resp] if self.log: res.append(self.log) res.append('') return '\n'.join(res) class ESMTPClientError(SMTPClientError): """Base class for ESMTP client errors. """ class EHLORequiredError(ESMTPClientError): """The server does not support EHLO. This is considered a non-fatal error (the connection will not be dropped). """ class AUTHRequiredError(ESMTPClientError): """Authentication was required but the server does not support it. This is considered a non-fatal error (the connection will not be dropped). """ class TLSRequiredError(ESMTPClientError): """Transport security was required but the server does not support it. This is considered a non-fatal error (the connection will not be dropped). """ class AUTHDeclinedError(ESMTPClientError): """The server rejected our credentials. Either the username, password, or challenge response given to the server was rejected. This is considered a non-fatal error (the connection will not be dropped). """ class AuthenticationError(ESMTPClientError): """An error ocurred while authenticating. Either the server rejected our request for authentication or the challenge received was malformed. This is considered a non-fatal error (the connection will not be dropped). """ class TLSError(ESMTPClientError): """An error occurred while negiotiating for transport security. This is considered a non-fatal error (the connection will not be dropped). """ class SMTPConnectError(SMTPClientError): """Failed to connect to the mail exchange host. This is considered a fatal error. A retry will be made. """ def __init__(self, code, resp, log=None, addresses=None, isFatal=True, retry=True): SMTPClientError.__init__(self, code, resp, log, addresses, isFatal, retry) class SMTPTimeoutError(SMTPClientError): """Failed to receive a response from the server in the expected time period. This is considered a fatal error. A retry will be made. """ def __init__(self, code, resp, log=None, addresses=None, isFatal=True, retry=True): SMTPClientError.__init__(self, code, resp, log, addresses, isFatal, retry) class SMTPProtocolError(SMTPClientError): """The server sent a mangled response. This is considered a fatal error. A retry will not be made. """ def __init__(self, code, resp, log=None, addresses=None, isFatal=True, retry=False): SMTPClientError.__init__(self, code, resp, log, addresses, isFatal, retry) class SMTPDeliveryError(SMTPClientError): """Indicates that a delivery attempt has had an error. """ class SMTPServerError(SMTPError): def __init__(self, code, resp): self.code = code self.resp = resp def __str__(self): return "%.3d %s" % (self.code, self.resp) class SMTPAddressError(SMTPServerError): def __init__(self, addr, code, resp): SMTPServerError.__init__(self, code, resp) self.addr = Address(addr) def __str__(self): return "%.3d <%s>... %s" % (self.code, self.addr, self.resp) class SMTPBadRcpt(SMTPAddressError): def __init__(self, addr, code=550, resp='Cannot receive for specified address'): SMTPAddressError.__init__(self, addr, code, resp) class SMTPBadSender(SMTPAddressError): def __init__(self, addr, code=550, resp='Sender not acceptable'): SMTPAddressError.__init__(self, addr, code, resp) def rfc822date(timeinfo=None,local=1): """ Format an RFC-2822 compliant date string. @param timeinfo: (optional) A sequence as returned by C{time.localtime()} or C{time.gmtime()}. Default is now. @param local: (optional) Indicates if the supplied time is local or universal time, or if no time is given, whether now should be local or universal time. Default is local, as suggested (SHOULD) by rfc-2822. @returns: A string representing the time and date in RFC-2822 format. """ if not timeinfo: if local: timeinfo = time.localtime() else: timeinfo = time.gmtime() if local: if timeinfo[8]: # DST tz = -time.altzone else: tz = -time.timezone (tzhr, tzmin) = divmod(abs(tz), 3600) if tz: tzhr *= int(abs(tz)/tz) (tzmin, tzsec) = divmod(tzmin, 60) else: (tzhr, tzmin) = (0,0) return "%s, %02d %s %04d %02d:%02d:%02d %+03d%02d" % ( ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timeinfo[6]], timeinfo[2], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timeinfo[1] - 1], timeinfo[0], timeinfo[3], timeinfo[4], timeinfo[5], tzhr, tzmin) def idGenerator(): i = 0 while True: yield i i += 1 def messageid(uniq=None, N=idGenerator().next): """Return a globally unique random string in RFC 2822 Message-ID format <datetime.pid.random@host.dom.ain> Optional uniq string will be added to strenghten uniqueness if given. """ datetime = time.strftime('%Y%m%d%H%M%S', time.gmtime()) pid = os.getpid() rand = random.randrange(2**31L-1) if uniq is None: uniq = '' else: uniq = '.' + uniq return '<%s.%s.%s%s.%s@%s>' % (datetime, pid, rand, uniq, N(), DNSNAME) def quoteaddr(addr): """Turn an email address, possibly with realname part etc, into a form suitable for and SMTP envelope. """ if isinstance(addr, Address): return '<%s>' % str(addr) res = rfc822.parseaddr(addr) if res == (None, None): # It didn't parse, use it as-is return '<%s>' % str(addr) else: return '<%s>' % str(res[1]) COMMAND, DATA, AUTH = 'COMMAND', 'DATA', 'AUTH' class AddressError(SMTPError): "Parse error in address" # Character classes for parsing addresses atom = r"[-A-Za-z0-9!\#$%&'*+/=?^_`{|}~]" class Address: """Parse and hold an RFC 2821 address. Source routes are stipped and ignored, UUCP-style bang-paths and %-style routing are not parsed. @type domain: C{str} @ivar domain: The domain within which this address resides. @type local: C{str} @ivar local: The local (\"user\") portion of this address. """ tstring = re.compile(r'''( # A string of (?:"[^"]*" # quoted string |\\. # backslash-escaped characted |''' + atom + r''' # atom character )+|.) # or any single character''',re.X) atomre = re.compile(atom) # match any one atom character def __init__(self, addr, defaultDomain=None): if isinstance(addr, User): addr = addr.dest if isinstance(addr, Address): self.__dict__ = addr.__dict__.copy() return elif not isinstance(addr, types.StringTypes): addr = str(addr) self.addrstr = addr # Tokenize atl = filter(None,self.tstring.split(addr)) local = [] domain = [] while atl: if atl[0] == '<': if atl[-1] != '>': raise AddressError, "Unbalanced <>" atl = atl[1:-1] elif atl[0] == '@': atl = atl[1:] if not local: # Source route while atl and atl[0] != ':': # remove it atl = atl[1:] if not atl: raise AddressError, "Malformed source route" atl = atl[1:] # remove : elif domain: raise AddressError, "Too many @" else: # Now in domain domain = [''] elif len(atl[0]) == 1 and not self.atomre.match(atl[0]) and atl[0] != '.': raise AddressError, "Parse error at %r of %r" % (atl[0], (addr, atl)) else: if not domain: local.append(atl[0]) else: domain.append(atl[0]) atl = atl[1:] self.local = ''.join(local) self.domain = ''.join(domain) if self.local != '' and self.domain == '': if defaultDomain is None: defaultDomain = DNSNAME self.domain = defaultDomain dequotebs = re.compile(r'\\(.)') def dequote(self,addr): """Remove RFC-2821 quotes from address.""" res = [] atl = filter(None,self.tstring.split(str(addr))) for t in atl: if t[0] == '"' and t[-1] == '"': res.append(t[1:-1]) elif '\\' in t: res.append(self.dequotebs.sub(r'\1',t)) else: res.append(t) return ''.join(res) def __str__(self): if self.local or self.domain: return '@'.join((self.local, self.domain)) else: return '' def __repr__(self): return "%s.%s(%s)" % (self.__module__, self.__class__.__name__, repr(str(self))) class User: """Hold information about and SMTP message recipient, including information on where the message came from """ def __init__(self, destination, helo, protocol, orig): host = getattr(protocol, 'host', None) self.dest = Address(destination, host) self.helo = helo self.protocol = protocol if isinstance(orig, Address): self.orig = orig else: self.orig = Address(orig, host) def __getstate__(self): """Helper for pickle. protocol isn't picklabe, but we want User to be, so skip it in the pickle. """ return { 'dest' : self.dest, 'helo' : self.helo, 'protocol' : None, 'orig' : self.orig } def __str__(self): return str(self.dest) class IMessage(Interface): """Interface definition for messages that can be sent via SMTP.""" def lineReceived(line): """handle another line""" def eomReceived(): """handle end of message return a deferred. The deferred should be called with either: callback(string) or errback(error) """ def connectionLost(): """handle message truncated semantics should be to discard the message """ class SMTP(basic.LineOnlyReceiver, policies.TimeoutMixin): """SMTP server-side protocol.""" timeout = 600 host = DNSNAME portal = None # Control whether we log SMTP events noisy = True # A factory for IMessageDelivery objects. If an # avatar implementing IMessageDeliveryFactory can # be acquired from the portal, it will be used to # create a new IMessageDelivery object for each # message which is received. deliveryFactory = None # An IMessageDelivery object. A new instance is # used for each message received if we can get an # IMessageDeliveryFactory from the portal. Otherwise, # a single instance is used throughout the lifetime # of the connection. delivery = None # Cred cleanup function. _onLogout = None def __init__(self, delivery=None, deliveryFactory=None): self.mode = COMMAND self._from = None self._helo = None self._to = [] self.delivery = delivery self.deliveryFactory = deliveryFactory def timeoutConnection(self): msg = '%s Timeout. Try talking faster next time!' % (self.host,) self.sendCode(421, msg) self.transport.loseConnection() def greeting(self): return '%s NO UCE NO UBE NO RELAY PROBES' % (self.host,) def connectionMade(self): # Ensure user-code always gets something sane for _helo peer = self.transport.getPeer() try: host = peer.host except AttributeError: # not an IPv4Address host = str(peer) self._helo = (None, host) self.sendCode(220, self.greeting()) self.setTimeout(self.timeout) def sendCode(self, code, message=''): "Send an SMTP code with a message." lines = message.splitlines() lastline = lines[-1:] for line in lines[:-1]: self.sendLine('%3.3d-%s' % (code, line)) self.sendLine('%3.3d %s' % (code, lastline and lastline[0] or '')) def lineReceived(self, line): self.resetTimeout() return getattr(self, 'state_' + self.mode)(line) def state_COMMAND(self, line): # Ignore leading and trailing whitespace, as well as an arbitrary # amount of whitespace between the command and its argument, though # it is not required by the protocol, for it is a nice thing to do. line = line.strip() parts = line.split(None, 1) if parts: method = self.lookupMethod(parts[0]) or self.do_UNKNOWN if len(parts) == 2: method(parts[1]) else: method('') else: self.sendSyntaxError() def sendSyntaxError(self): self.sendCode(500, 'Error: bad syntax') def lookupMethod(self, command): return getattr(self, 'do_' + command.upper(), None) def lineLengthExceeded(self, line): if self.mode is DATA: for message in self.__messages: message.connectionLost() self.mode = COMMAND del self.__messages self.sendCode(500, 'Line too long') def do_UNKNOWN(self, rest): self.sendCode(500, 'Command not implemented') def do_HELO(self, rest): peer = self.transport.getPeer() try: host = peer.host except AttributeError: host = str(peer) self._helo = (rest, host) self._from = None self._to = [] self.sendCode(250, '%s Hello %s, nice to meet you' % (self.host, host)) def do_QUIT(self, rest): self.sendCode(221, 'See you later') self.transport.loseConnection() # A string of quoted strings, backslash-escaped character or # atom characters + '@.,:' qstring = r'("[^"]*"|\\.|' + atom + r'|[@.,:])+' mail_re = re.compile(r'''\s*FROM:\s*(?P<path><> # Empty <> |<''' + qstring + r'''> # <addr> |''' + qstring + r''' # addr )\s*(\s(?P<opts>.*))? # Optional WS + ESMTP options $''',re.I|re.X) rcpt_re = re.compile(r'\s*TO:\s*(?P<path><' + qstring + r'''> # <addr> |''' + qstring + r''' # addr )\s*(\s(?P<opts>.*))? # Optional WS + ESMTP options $''',re.I|re.X) def do_MAIL(self, rest): if self._from: self.sendCode(503,"Only one sender per message, please") return # Clear old recipient list self._to = [] m = self.mail_re.match(rest) if not m: self.sendCode(501, "Syntax error") return try: addr = Address(m.group('path'), self.host) except AddressError, e: self.sendCode(553, str(e)) return validated = defer.maybeDeferred(self.validateFrom, self._helo, addr) validated.addCallbacks(self._cbFromValidate, self._ebFromValidate) def _cbFromValidate(self, from_, code=250, msg='Sender address accepted'): self._from = from_ self.sendCode(code, msg) def _ebFromValidate(self, failure): if failure.check(SMTPBadSender): self.sendCode(failure.value.code, 'Cannot receive from specified address %s: %s' % (quoteaddr(failure.value.addr), failure.value.resp)) elif failure.check(SMTPServerError): self.sendCode(failure.value.code, failure.value.resp) else: log.err(failure, "SMTP sender validation failure") self.sendCode( 451, 'Requested action aborted: local error in processing') def do_RCPT(self, rest): if not self._from: self.sendCode(503, "Must have sender before recipient") return m = self.rcpt_re.match(rest) if not m: self.sendCode(501, "Syntax error") return try: user = User(m.group('path'), self._helo, self, self._from) except AddressError, e: self.sendCode(553, str(e)) return d = defer.maybeDeferred(self.validateTo, user) d.addCallbacks( self._cbToValidate, self._ebToValidate, callbackArgs=(user,) ) def _cbToValidate(self, to, user=None, code=250, msg='Recipient address accepted'): if user is None: user = to self._to.append((user, to)) self.sendCode(code, msg) def _ebToValidate(self, failure): if failure.check(SMTPBadRcpt, SMTPServerError): self.sendCode(failure.value.code, failure.value.resp) else: log.err(failure) self.sendCode( 451, 'Requested action aborted: local error in processing' ) def _disconnect(self, msgs): for msg in msgs: try: msg.connectionLost() except: log.msg("msg raised exception from connectionLost") log.err() def do_DATA(self, rest): if self._from is None or (not self._to): self.sendCode(503, 'Must have valid receiver and originator') return self.mode = DATA helo, origin = self._helo, self._from recipients = self._to self._from = None self._to = [] self.datafailed = None msgs = [] for (user, msgFunc) in recipients: try: msg = msgFunc() rcvdhdr = self.receivedHeader(helo, origin, [user]) if rcvdhdr: msg.lineReceived(rcvdhdr) msgs.append(msg) except SMTPServerError, e: self.sendCode(e.code, e.resp) self.mode = COMMAND self._disconnect(msgs) return except: log.err() self.sendCode(550, "Internal server error") self.mode = COMMAND self._disconnect(msgs) return self.__messages = msgs self.__inheader = self.__inbody = 0 self.sendCode(354, 'Continue') if self.noisy: fmt = 'Receiving message for delivery: from=%s to=%s' log.msg(fmt % (origin, [str(u) for (u, f) in recipients])) def connectionLost(self, reason): # self.sendCode(421, 'Dropping connection.') # This does nothing... # Ideally, if we (rather than the other side) lose the connection, # we should be able to tell the other side that we are going away. # RFC-2821 requires that we try. if self.mode is DATA: try: for message in self.__messages: try: message.connectionLost() except: log.err() del self.__messages except AttributeError: pass if self._onLogout: self._onLogout() self._onLogout = None self.setTimeout(None) def do_RSET(self, rest): self._from = None self._to = [] self.sendCode(250, 'I remember nothing.') def dataLineReceived(self, line): if line[:1] == '.': if line == '.': self.mode = COMMAND if self.datafailed: self.sendCode(self.datafailed.code, self.datafailed.resp) return if not self.__messages: self._messageHandled("thrown away") return defer.DeferredList([ m.eomReceived() for m in self.__messages ], consumeErrors=True).addCallback(self._messageHandled ) del self.__messages return line = line[1:] if self.datafailed: return try: # Add a blank line between the generated Received:-header # and the message body if the message comes in without any # headers if not self.__inheader and not self.__inbody: if ':' in line: self.__inheader = 1 elif line: for message in self.__messages: message.lineReceived('') self.__inbody = 1 if not line: self.__inbody = 1 for message in self.__messages: message.lineReceived(line) except SMTPServerError, e: self.datafailed = e for message in self.__messages: message.connectionLost() state_DATA = dataLineReceived def _messageHandled(self, resultList): failures = 0 for (success, result) in resultList: if not success: failures += 1 log.err(result) if failures: msg = 'Could not send e-mail' L = len(resultList) if L > 1: msg += ' (%d failures out of %d recipients)' % (failures, L) self.sendCode(550, msg) else: self.sendCode(250, 'Delivery in progress') def _cbAnonymousAuthentication(self, (iface, avatar, logout)): """ Save the state resulting from a successful anonymous cred login. """ if issubclass(iface, IMessageDeliveryFactory): self.deliveryFactory = avatar self.delivery = None elif issubclass(iface, IMessageDelivery): self.deliveryFactory = None self.delivery = avatar else: raise RuntimeError("%s is not a supported interface" % (iface.__name__,)) self._onLogout = logout self.challenger = None # overridable methods: def validateFrom(self, helo, origin): """ Validate the address from which the message originates. @type helo: C{(str, str)} @param helo: The argument to the HELO command and the client's IP address. @type origin: C{Address} @param origin: The address the message is from @rtype: C{Deferred} or C{Address} @return: C{origin} or a C{Deferred} whose callback will be passed C{origin}. @raise SMTPBadSender: Raised of messages from this address are not to be accepted. """ if self.deliveryFactory is not None: self.delivery = self.deliveryFactory.getMessageDelivery() if self.delivery is not None: return defer.maybeDeferred(self.delivery.validateFrom, helo, origin) # No login has been performed, no default delivery object has been # provided: try to perform an anonymous login and then invoke this # method again. if self.portal: result = self.portal.login( cred.credentials.Anonymous(), None, IMessageDeliveryFactory, IMessageDelivery) def ebAuthentication(err): """ Translate cred exceptions into SMTP exceptions so that the protocol code which invokes C{validateFrom} can properly report the failure. """ if err.check(cred.error.UnauthorizedLogin): exc = SMTPBadSender(origin) elif err.check(cred.error.UnhandledCredentials): exc = SMTPBadSender( origin, resp="Unauthenticated senders not allowed") else: return err return defer.fail(exc) result.addCallbacks( self._cbAnonymousAuthentication, ebAuthentication) def continueValidation(ignored): """ Re-attempt from address validation. """ return self.validateFrom(helo, origin) result.addCallback(continueValidation) return result raise SMTPBadSender(origin) def validateTo(self, user): """ Validate the address for which the message is destined. @type user: C{User} @param user: The address to validate. @rtype: no-argument callable @return: A C{Deferred} which becomes, or a callable which takes no arguments and returns an object implementing C{IMessage}. This will be called and the returned object used to deliver the message when it arrives. @raise SMTPBadRcpt: Raised if messages to the address are not to be accepted. """ if self.delivery is not None: return self.delivery.validateTo(user) raise SMTPBadRcpt(user) def receivedHeader(self, helo, origin, recipients): if self.delivery is not None: return self.delivery.receivedHeader(helo, origin, recipients) heloStr = "" if helo[0]: heloStr = " helo=%s" % (helo[0],) domain = self.transport.getHost().host from_ = "from %s ([%s]%s)" % (helo[0], helo[1], heloStr) by = "by %s with %s (%s)" % (domain, self.__class__.__name__, longversion) for_ = "for %s; %s" % (' '.join(map(str, recipients)), rfc822date()) return "Received: %s\n\t%s\n\t%s" % (from_, by, for_) def startMessage(self, recipients): if self.delivery: return self.delivery.startMessage(recipients) return [] class SMTPFactory(protocol.ServerFactory): """Factory for SMTP.""" # override in instances or subclasses domain = DNSNAME timeout = 600 protocol = SMTP portal = None def __init__(self, portal = None): self.portal = portal def buildProtocol(self, addr): p = protocol.ServerFactory.buildProtocol(self, addr) p.portal = self.portal p.host = self.domain return p class SMTPClient(basic.LineReceiver, policies.TimeoutMixin): """ SMTP client for sending emails. After the client has connected to the SMTP server, it repeatedly calls L{SMTPClient.getMailFrom}, L{SMTPClient.getMailTo} and L{SMTPClient.getMailData} and uses this information to send an email. It then calls L{SMTPClient.getMailFrom} again; if it returns C{None}, the client will disconnect, otherwise it will continue as normal i.e. call L{SMTPClient.getMailTo} and L{SMTPClient.getMailData} and send a new email. """ # If enabled then log SMTP client server communication debug = True # Number of seconds to wait before timing out a connection. If # None, perform no timeout checking. timeout = None def __init__(self, identity, logsize=10): self.identity = identity or '' self.toAddressesResult = [] self.successAddresses = [] self._from = None self.resp = [] self.code = -1 self.log = util.LineLog(logsize) def sendLine(self, line): # Log sendLine only if you are in debug mode for performance if self.debug: self.log.append('>>> ' + line) basic.LineReceiver.sendLine(self,line) def connectionMade(self): self.setTimeout(self.timeout) self._expected = [ 220 ] self._okresponse = self.smtpState_helo self._failresponse = self.smtpConnectionFailed def connectionLost(self, reason=protocol.connectionDone): """We are no longer connected""" self.setTimeout(None) self.mailFile = None def timeoutConnection(self): self.sendError( SMTPTimeoutError( -1, "Timeout waiting for SMTP server response", self.log.str())) def lineReceived(self, line): self.resetTimeout() # Log lineReceived only if you are in debug mode for performance if self.debug: self.log.append('<<< ' + line) why = None try: self.code = int(line[:3]) except ValueError: # This is a fatal error and will disconnect the transport lineReceived will not be called again self.sendError(SMTPProtocolError(-1, "Invalid response from SMTP server: %s" % line, self.log.str())) return if line[0] == '0': # Verbose informational message, ignore it return self.resp.append(line[4:]) if line[3:4] == '-': # continuation return if self.code in self._expected: why = self._okresponse(self.code,'\n'.join(self.resp)) else: why = self._failresponse(self.code,'\n'.join(self.resp)) self.code = -1 self.resp = [] return why def smtpConnectionFailed(self, code, resp): self.sendError(SMTPConnectError(code, resp, self.log.str())) def smtpTransferFailed(self, code, resp): if code < 0: self.sendError(SMTPProtocolError(code, resp, self.log.str())) else: self.smtpState_msgSent(code, resp) def smtpState_helo(self, code, resp): self.sendLine('HELO ' + self.identity) self._expected = SUCCESS self._okresponse = self.smtpState_from def smtpState_from(self, code, resp): self._from = self.getMailFrom() self._failresponse = self.smtpTransferFailed if self._from is not None: self.sendLine('MAIL FROM:%s' % quoteaddr(self._from)) self._expected = [250] self._okresponse = self.smtpState_to else: # All messages have been sent, disconnect self._disconnectFromServer() def smtpState_disconnect(self, code, resp): self.transport.loseConnection() def smtpState_to(self, code, resp): self.toAddresses = iter(self.getMailTo()) self.toAddressesResult = [] self.successAddresses = [] self._okresponse = self.smtpState_toOrData self._expected = xrange(0,1000) self.lastAddress = None return self.smtpState_toOrData(0, '') def smtpState_toOrData(self, code, resp): if self.lastAddress is not None: self.toAddressesResult.append((self.lastAddress, code, resp)) if code in SUCCESS: self.successAddresses.append(self.lastAddress) try: self.lastAddress = self.toAddresses.next() except StopIteration: if self.successAddresses: self.sendLine('DATA') self._expected = [ 354 ] self._okresponse = self.smtpState_data else: return self.smtpState_msgSent(code,'No recipients accepted') else: self.sendLine('RCPT TO:%s' % quoteaddr(self.lastAddress)) def smtpState_data(self, code, resp): s = basic.FileSender() d = s.beginFileTransfer( self.getMailData(), self.transport, self.transformChunk) def ebTransfer(err): self.sendError(err.value) d.addCallbacks(self.finishedFileTransfer, ebTransfer) self._expected = SUCCESS self._okresponse = self.smtpState_msgSent def smtpState_msgSent(self, code, resp): if self._from is not None: self.sentMail(code, resp, len(self.successAddresses), self.toAddressesResult, self.log) self.toAddressesResult = [] self._from = None self.sendLine('RSET') self._expected = SUCCESS self._okresponse = self.smtpState_from ## ## Helpers for FileSender ## def transformChunk(self, chunk): """ Perform the necessary local to network newline conversion and escape leading periods. This method also resets the idle timeout so that as long as process is being made sending the message body, the client will not time out. """ self.resetTimeout() return chunk.replace('\n', '\r\n').replace('\r\n.', '\r\n..') def finishedFileTransfer(self, lastsent): if lastsent != '\n': line = '\r\n.' else: line = '.' self.sendLine(line) ## # these methods should be overriden in subclasses def getMailFrom(self): """Return the email address the mail is from.""" raise NotImplementedError def getMailTo(self): """Return a list of emails to send to.""" raise NotImplementedError def getMailData(self): """Return file-like object containing data of message to be sent. Lines in the file should be delimited by '\\n'. """ raise NotImplementedError def sendError(self, exc): """ If an error occurs before a mail message is sent sendError will be called. This base class method sends a QUIT if the error is non-fatal and disconnects the connection. @param exc: The SMTPClientError (or child class) raised @type exc: C{SMTPClientError} """ if isinstance(exc, SMTPClientError) and not exc.isFatal: self._disconnectFromServer() else: # If the error was fatal then the communication channel with the # SMTP Server is broken so just close the transport connection self.smtpState_disconnect(-1, None) def sentMail(self, code, resp, numOk, addresses, log): """Called when an attempt to send an email is completed. If some addresses were accepted, code and resp are the response to the DATA command. If no addresses were accepted, code is -1 and resp is an informative message. @param code: the code returned by the SMTP Server @param resp: The string response returned from the SMTP Server @param numOK: the number of addresses accepted by the remote host. @param addresses: is a list of tuples (address, code, resp) listing the response to each RCPT command. @param log: is the SMTP session log """ raise NotImplementedError def _disconnectFromServer(self): self._expected = xrange(0, 1000) self._okresponse = self.smtpState_disconnect self.sendLine('QUIT') class ESMTPClient(SMTPClient): # Fall back to HELO if the server does not support EHLO heloFallback = True # Refuse to proceed if authentication cannot be performed requireAuthentication = False # Refuse to proceed if TLS is not available requireTransportSecurity = False # Indicate whether or not our transport can be considered secure. tlsMode = False # ClientContextFactory to use for STARTTLS context = None def __init__(self, secret, contextFactory=None, *args, **kw): SMTPClient.__init__(self, *args, **kw) self.authenticators = [] self.secret = secret self.context = contextFactory self.tlsMode = False def esmtpEHLORequired(self, code=-1, resp=None): self.sendError(EHLORequiredError(502, "Server does not support ESMTP Authentication", self.log.str())) def esmtpAUTHRequired(self, code=-1, resp=None): tmp = [] for a in self.authenticators: tmp.append(a.getName().upper()) auth = "[%s]" % ', '.join(tmp) self.sendError(AUTHRequiredError(502, "Server does not support Client Authentication schemes %s" % auth, self.log.str())) def esmtpTLSRequired(self, code=-1, resp=None): self.sendError(TLSRequiredError(502, "Server does not support secure communication via TLS / SSL", self.log.str())) def esmtpTLSFailed(self, code=-1, resp=None): self.sendError(TLSError(code, "Could not complete the SSL/TLS handshake", self.log.str())) def esmtpAUTHDeclined(self, code=-1, resp=None): self.sendError(AUTHDeclinedError(code, resp, self.log.str())) def esmtpAUTHMalformedChallenge(self, code=-1, resp=None): str = "Login failed because the SMTP Server returned a malformed Authentication Challenge" self.sendError(AuthenticationError(501, str, self.log.str())) def esmtpAUTHServerError(self, code=-1, resp=None): self.sendError(AuthenticationError(code, resp, self.log.str())) def registerAuthenticator(self, auth): """Registers an Authenticator with the ESMTPClient. The ESMTPClient will attempt to login to the SMTP Server in the order the Authenticators are registered. The most secure Authentication mechanism should be registered first. @param auth: The Authentication mechanism to register @type auth: class implementing C{IClientAuthentication} """ self.authenticators.append(auth) def connectionMade(self): SMTPClient.connectionMade(self) self._okresponse = self.esmtpState_ehlo def esmtpState_ehlo(self, code, resp): self._expected = SUCCESS self._okresponse = self.esmtpState_serverConfig self._failresponse = self.esmtpEHLORequired if self.heloFallback: self._failresponse = self.smtpState_helo self.sendLine('EHLO ' + self.identity) def esmtpState_serverConfig(self, code, resp): items = {} for line in resp.splitlines(): e = line.split(None, 1) if len(e) > 1: items[e[0]] = e[1] else: items[e[0]] = None if self.tlsMode: self.authenticate(code, resp, items) else: self.tryTLS(code, resp, items) def tryTLS(self, code, resp, items): if self.context and 'STARTTLS' in items: self._expected = [220] self._okresponse = self.esmtpState_starttls self._failresponse = self.esmtpTLSFailed self.sendLine('STARTTLS') elif self.requireTransportSecurity: self.tlsMode = False self.esmtpTLSRequired() else: self.tlsMode = False self.authenticate(code, resp, items) def esmtpState_starttls(self, code, resp): try: self.transport.startTLS(self.context) self.tlsMode = True except: log.err() self.esmtpTLSFailed(451) # Send another EHLO once TLS has been started to # get the TLS / AUTH schemes. Some servers only allow AUTH in TLS mode. self.esmtpState_ehlo(code, resp) def authenticate(self, code, resp, items): if self.secret and items.get('AUTH'): schemes = items['AUTH'].split() tmpSchemes = {} #XXX: May want to come up with a more efficient way to do this for s in schemes: tmpSchemes[s.upper()] = 1 for a in self.authenticators: auth = a.getName().upper() if auth in tmpSchemes: self._authinfo = a # Special condition handled if auth == "PLAIN": self._okresponse = self.smtpState_from self._failresponse = self._esmtpState_plainAuth self._expected = [235] challenge = encode_base64(self._authinfo.challengeResponse(self.secret, 1), eol="") self.sendLine('AUTH ' + auth + ' ' + challenge) else: self._expected = [334] self._okresponse = self.esmtpState_challenge # If some error occurs here, the server declined the AUTH # before the user / password phase. This would be # a very rare case self._failresponse = self.esmtpAUTHServerError self.sendLine('AUTH ' + auth) return if self.requireAuthentication: self.esmtpAUTHRequired() else: self.smtpState_from(code, resp) def _esmtpState_plainAuth(self, code, resp): self._okresponse = self.smtpState_from self._failresponse = self.esmtpAUTHDeclined self._expected = [235] challenge = encode_base64(self._authinfo.challengeResponse(self.secret, 2), eol="") self.sendLine('AUTH PLAIN ' + challenge) def esmtpState_challenge(self, code, resp): self._authResponse(self._authinfo, resp) def _authResponse(self, auth, challenge): self._failresponse = self.esmtpAUTHDeclined try: challenge = base64.decodestring(challenge) except binascii.Error: # Illegal challenge, give up, then quit self.sendLine('*') self._okresponse = self.esmtpAUTHMalformedChallenge self._failresponse = self.esmtpAUTHMalformedChallenge else: resp = auth.challengeResponse(self.secret, challenge) self._expected = [235, 334] self._okresponse = self.smtpState_maybeAuthenticated self.sendLine(encode_base64(resp, eol="")) def smtpState_maybeAuthenticated(self, code, resp): """ Called to handle the next message from the server after sending a response to a SASL challenge. The server response might be another challenge or it might indicate authentication has succeeded. """ if code == 235: # Yes, authenticated! del self._authinfo self.smtpState_from(code, resp) else: # No, not authenticated yet. Keep trying. self._authResponse(self._authinfo, resp) class ESMTP(SMTP): ctx = None canStartTLS = False startedTLS = False authenticated = False def __init__(self, chal = None, contextFactory = None): SMTP.__init__(self) if chal is None: chal = {} self.challengers = chal self.authenticated = False self.ctx = contextFactory def connectionMade(self): SMTP.connectionMade(self) self.canStartTLS = ITLSTransport.providedBy(self.transport) self.canStartTLS = self.canStartTLS and (self.ctx is not None) def greeting(self): return SMTP.greeting(self) + ' ESMTP' def extensions(self): ext = {'AUTH': self.challengers.keys()} if self.canStartTLS and not self.startedTLS: ext['STARTTLS'] = None return ext def lookupMethod(self, command): m = SMTP.lookupMethod(self, command) if m is None: m = getattr(self, 'ext_' + command.upper(), None) return m def listExtensions(self): r = [] for (c, v) in self.extensions().iteritems(): if v is not None: if v: # Intentionally omit extensions with empty argument lists r.append('%s %s' % (c, ' '.join(v))) else: r.append(c) return '\n'.join(r) def do_EHLO(self, rest): peer = self.transport.getPeer().host self._helo = (rest, peer) self._from = None self._to = [] self.sendCode( 250, '%s Hello %s, nice to meet you\n%s' % ( self.host, peer, self.listExtensions(), ) ) def ext_STARTTLS(self, rest): if self.startedTLS: self.sendCode(503, 'TLS already negotiated') elif self.ctx and self.canStartTLS: self.sendCode(220, 'Begin TLS negotiation now') self.transport.startTLS(self.ctx) self.startedTLS = True else: self.sendCode(454, 'TLS not available') def ext_AUTH(self, rest): if self.authenticated: self.sendCode(503, 'Already authenticated') return parts = rest.split(None, 1) chal = self.challengers.get(parts[0].upper(), lambda: None)() if not chal: self.sendCode(504, 'Unrecognized authentication type') return self.mode = AUTH self.challenger = chal if len(parts) > 1: chal.getChallenge() # Discard it, apparently the client does not # care about it. rest = parts[1] else: rest = None self.state_AUTH(rest) def _cbAuthenticated(self, loginInfo): """ Save the state resulting from a successful cred login and mark this connection as authenticated. """ result = SMTP._cbAnonymousAuthentication(self, loginInfo) self.authenticated = True return result def _ebAuthenticated(self, reason): """ Handle cred login errors by translating them to the SMTP authenticate failed. Translate all other errors into a generic SMTP error code and log the failure for inspection. Stop all errors from propagating. """ self.challenge = None if reason.check(cred.error.UnauthorizedLogin): self.sendCode(535, 'Authentication failed') else: log.err(reason, "SMTP authentication failure") self.sendCode( 451, 'Requested action aborted: local error in processing') def state_AUTH(self, response): """ Handle one step of challenge/response authentication. @param response: The text of a response. If None, this function has been called as a result of an AUTH command with no initial response. A response of '*' aborts authentication, as per RFC 2554. """ if self.portal is None: self.sendCode(454, 'Temporary authentication failure') self.mode = COMMAND return if response is None: challenge = self.challenger.getChallenge() encoded = challenge.encode('base64') self.sendCode(334, encoded) return if response == '*': self.sendCode(501, 'Authentication aborted') self.challenger = None self.mode = COMMAND return try: uncoded = response.decode('base64') except binascii.Error: self.sendCode(501, 'Syntax error in parameters or arguments') self.challenger = None self.mode = COMMAND return self.challenger.setResponse(uncoded) if self.challenger.moreChallenges(): challenge = self.challenger.getChallenge() coded = challenge.encode('base64')[:-1] self.sendCode(334, coded) return self.mode = COMMAND result = self.portal.login( self.challenger, None, IMessageDeliveryFactory, IMessageDelivery) result.addCallback(self._cbAuthenticated) result.addCallback(lambda ign: self.sendCode(235, 'Authentication successful.')) result.addErrback(self._ebAuthenticated) class SenderMixin: """Utility class for sending emails easily. Use with SMTPSenderFactory or ESMTPSenderFactory. """ done = 0 def getMailFrom(self): if not self.done: self.done = 1 return str(self.factory.fromEmail) else: return None def getMailTo(self): return self.factory.toEmail def getMailData(self): return self.factory.file def sendError(self, exc): # Call the base class to close the connection with the SMTP server SMTPClient.sendError(self, exc) # Do not retry to connect to SMTP Server if: # 1. No more retries left (This allows the correct error to be returned to the errorback) # 2. retry is false # 3. The error code is not in the 4xx range (Communication Errors) if (self.factory.retries >= 0 or (not exc.retry and not (exc.code >= 400 and exc.code < 500))): self.factory.sendFinished = 1 self.factory.result.errback(exc) def sentMail(self, code, resp, numOk, addresses, log): # Do not retry, the SMTP server acknowledged the request self.factory.sendFinished = 1 if code not in SUCCESS: errlog = [] for addr, acode, aresp in addresses: if acode not in SUCCESS: errlog.append("%s: %03d %s" % (addr, acode, aresp)) errlog.append(log.str()) exc = SMTPDeliveryError(code, resp, '\n'.join(errlog), addresses) self.factory.result.errback(exc) else: self.factory.result.callback((numOk, addresses)) class SMTPSender(SenderMixin, SMTPClient): """ SMTP protocol that sends a single email based on information it gets from its factory, a L{SMTPSenderFactory}. """ class SMTPSenderFactory(protocol.ClientFactory): """ Utility factory for sending emails easily. """ domain = DNSNAME protocol = SMTPSender def __init__(self, fromEmail, toEmail, file, deferred, retries=5, timeout=None): """ @param fromEmail: The RFC 2821 address from which to send this message. @param toEmail: A sequence of RFC 2821 addresses to which to send this message. @param file: A file-like object containing the message to send. @param deferred: A Deferred to callback or errback when sending of this message completes. @param retries: The number of times to retry delivery of this message. @param timeout: Period, in seconds, for which to wait for server responses, or None to wait forever. """ assert isinstance(retries, (int, long)) if isinstance(toEmail, types.StringTypes): toEmail = [toEmail] self.fromEmail = Address(fromEmail) self.nEmails = len(toEmail) self.toEmail = toEmail self.file = file self.result = deferred self.result.addBoth(self._removeDeferred) self.sendFinished = 0 self.retries = -retries self.timeout = timeout def _removeDeferred(self, argh): del self.result return argh def clientConnectionFailed(self, connector, err): self._processConnectionError(connector, err) def clientConnectionLost(self, connector, err): self._processConnectionError(connector, err) def _processConnectionError(self, connector, err): if self.retries < self.sendFinished <= 0: log.msg("SMTP Client retrying server. Retry: %s" % -self.retries) # Rewind the file in case part of it was read while attempting to # send the message. self.file.seek(0, 0) connector.connect() self.retries += 1 elif self.sendFinished <= 0: # If we were unable to communicate with the SMTP server a ConnectionDone will be # returned. We want a more clear error message for debugging if err.check(error.ConnectionDone): err.value = SMTPConnectError(-1, "Unable to connect to server.") self.result.errback(err.value) def buildProtocol(self, addr): p = self.protocol(self.domain, self.nEmails*2+2) p.factory = self p.timeout = self.timeout return p from twisted.mail.imap4 import IClientAuthentication from twisted.mail.imap4 import CramMD5ClientAuthenticator, LOGINAuthenticator class PLAINAuthenticator: implements(IClientAuthentication) def __init__(self, user): self.user = user def getName(self): return "PLAIN" def challengeResponse(self, secret, chal=1): if chal == 1: return "%s\0%s\0%s" % (self.user, self.user, secret) else: return "%s\0%s" % (self.user, secret) class ESMTPSender(SenderMixin, ESMTPClient): requireAuthentication = True requireTransportSecurity = True def __init__(self, username, secret, contextFactory=None, *args, **kw): self.heloFallback = 0 self.username = username if contextFactory is None: contextFactory = self._getContextFactory() ESMTPClient.__init__(self, secret, contextFactory, *args, **kw) self._registerAuthenticators() def _registerAuthenticators(self): # Register Authenticator in order from most secure to least secure self.registerAuthenticator(CramMD5ClientAuthenticator(self.username)) self.registerAuthenticator(LOGINAuthenticator(self.username)) self.registerAuthenticator(PLAINAuthenticator(self.username)) def _getContextFactory(self): if self.context is not None: return self.context try: from twisted.internet import ssl except ImportError: return None else: try: context = ssl.ClientContextFactory() context.method = ssl.SSL.TLSv1_METHOD return context except AttributeError: return None class ESMTPSenderFactory(SMTPSenderFactory): """ Utility factory for sending emails easily. """ protocol = ESMTPSender def __init__(self, username, password, fromEmail, toEmail, file, deferred, retries=5, timeout=None, contextFactory=None, heloFallback=False, requireAuthentication=True, requireTransportSecurity=True): SMTPSenderFactory.__init__(self, fromEmail, toEmail, file, deferred, retries, timeout) self.username = username self.password = password self._contextFactory = contextFactory self._heloFallback = heloFallback self._requireAuthentication = requireAuthentication self._requireTransportSecurity = requireTransportSecurity def buildProtocol(self, addr): p = self.protocol(self.username, self.password, self._contextFactory, self.domain, self.nEmails*2+2) p.heloFallback = self._heloFallback p.requireAuthentication = self._requireAuthentication p.requireTransportSecurity = self._requireTransportSecurity p.factory = self p.timeout = self.timeout return p def sendmail(smtphost, from_addr, to_addrs, msg, senderDomainName=None, port=25): """Send an email This interface is intended to be a direct replacement for smtplib.SMTP.sendmail() (with the obvious change that you specify the smtphost as well). Also, ESMTP options are not accepted, as we don't do ESMTP yet. I reserve the right to implement the ESMTP options differently. @param smtphost: The host the message should be sent to @param from_addr: The (envelope) address sending this mail. @param to_addrs: A list of addresses to send this mail to. A string will be treated as a list of one address @param msg: The message, including headers, either as a file or a string. File-like objects need to support read() and close(). Lines must be delimited by '\\n'. If you pass something that doesn't look like a file, we try to convert it to a string (so you should be able to pass an email.Message directly, but doing the conversion with email.Generator manually will give you more control over the process). @param senderDomainName: Name by which to identify. If None, try to pick something sane (but this depends on external configuration and may not succeed). @param port: Remote port to which to connect. @rtype: L{Deferred} @returns: A L{Deferred}, its callback will be called if a message is sent to ANY address, the errback if no message is sent. The callback will be called with a tuple (numOk, addresses) where numOk is the number of successful recipient addresses and addresses is a list of tuples (address, code, resp) giving the response to the RCPT command for each address. """ if not hasattr(msg,'read'): # It's not a file msg = StringIO(str(msg)) d = defer.Deferred() factory = SMTPSenderFactory(from_addr, to_addrs, msg, d) if senderDomainName is not None: factory.domain = senderDomainName reactor.connectTCP(smtphost, port, factory) return d ## ## Yerg. Codecs! ## import codecs def xtext_encode(s, errors=None): r = [] for ch in s: o = ord(ch) if ch == '+' or ch == '=' or o < 33 or o > 126: r.append('+%02X' % o) else: r.append(chr(o)) return (''.join(r), len(s)) def _slowXTextDecode(s, errors=None): """ Decode the xtext-encoded string C{s}. """ r = [] i = 0 while i < len(s): if s[i] == '+': try: r.append(chr(int(s[i + 1:i + 3], 16))) except ValueError: r.append(s[i:i + 3]) i += 3 else: r.append(s[i]) i += 1 return (''.join(r), len(s)) try: from twisted.protocols._c_urlarg import unquote as _helper_unquote except ImportError: xtext_decode = _slowXTextDecode else: def xtext_decode(s, errors=None): """ Decode the xtext-encoded string C{s} using a fast extension function. """ return (_helper_unquote(s, '+'), len(s)) class xtextStreamReader(codecs.StreamReader): def decode(self, s, errors='strict'): return xtext_decode(s) class xtextStreamWriter(codecs.StreamWriter): def decode(self, s, errors='strict'): return xtext_encode(s) def xtext_codec(name): if name == 'xtext': return (xtext_encode, xtext_decode, xtextStreamReader, xtextStreamWriter) codecs.register(xtext_codec)
wilsonkichoi/zipline
refs/heads/master
tests/risk/annotation_utils.py
50
# # Copyright 2013 Quantopian, Inc. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. import markdown # Inspired by: # http://catherinedevlin.blogspot.com/2013/06/\ # easy-html-output-in-ipython-notebook.html class Markdown(str): """ Markdown wrapper to allow dynamic Markdown cells. """ def _repr_html_(self): return markdown.markdown(self)
4rado/RepositoryForProject
refs/heads/master
Lib/xmllib.py
41
"""A parser for XML, using the derived class as static DTD.""" # Author: Sjoerd Mullender. import re import string version = '0.3' class Error(RuntimeError): pass # Regular expressions used for parsing _S = '[ \t\r\n]+' # white space _opS = '[ \t\r\n]*' # optional white space _Name = '[a-zA-Z_:][-a-zA-Z0-9._:]*' # valid XML name _QStr = "(?:'[^']*'|\"[^\"]*\")" # quoted XML string illegal = re.compile('[^\t\r\n -\176\240-\377]') # illegal chars in content interesting = re.compile('[]&<]') amp = re.compile('&') ref = re.compile('&(' + _Name + '|#[0-9]+|#x[0-9a-fA-F]+)[^-a-zA-Z0-9._:]') entityref = re.compile('&(?P<name>' + _Name + ')[^-a-zA-Z0-9._:]') charref = re.compile('&#(?P<char>[0-9]+[^0-9]|x[0-9a-fA-F]+[^0-9a-fA-F])') space = re.compile(_S + '$') newline = re.compile('\n') attrfind = re.compile( _S + '(?P<name>' + _Name + ')' '(' + _opS + '=' + _opS + '(?P<value>'+_QStr+'|[-a-zA-Z0-9.:+*%?!\(\)_#=~]+))?') starttagopen = re.compile('<' + _Name) starttagend = re.compile(_opS + '(?P<slash>/?)>') starttagmatch = re.compile('<(?P<tagname>'+_Name+')' '(?P<attrs>(?:'+attrfind.pattern+')*)'+ starttagend.pattern) endtagopen = re.compile('</') endbracket = re.compile(_opS + '>') endbracketfind = re.compile('(?:[^>\'"]|'+_QStr+')*>') tagfind = re.compile(_Name) cdataopen = re.compile(r'<!\[CDATA\[') cdataclose = re.compile(r'\]\]>') # this matches one of the following: # SYSTEM SystemLiteral # PUBLIC PubidLiteral SystemLiteral _SystemLiteral = '(?P<%s>'+_QStr+')' _PublicLiteral = '(?P<%s>"[-\'\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*"|' \ "'[-\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*')" _ExternalId = '(?:SYSTEM|' \ 'PUBLIC'+_S+_PublicLiteral%'pubid'+ \ ')'+_S+_SystemLiteral%'syslit' doctype = re.compile('<!DOCTYPE'+_S+'(?P<name>'+_Name+')' '(?:'+_S+_ExternalId+')?'+_opS) xmldecl = re.compile('<\?xml'+_S+ 'version'+_opS+'='+_opS+'(?P<version>'+_QStr+')'+ '(?:'+_S+'encoding'+_opS+'='+_opS+ "(?P<encoding>'[A-Za-z][-A-Za-z0-9._]*'|" '"[A-Za-z][-A-Za-z0-9._]*"))?' '(?:'+_S+'standalone'+_opS+'='+_opS+ '(?P<standalone>\'(?:yes|no)\'|"(?:yes|no)"))?'+ _opS+'\?>') procopen = re.compile(r'<\?(?P<proc>' + _Name + ')' + _opS) procclose = re.compile(_opS + r'\?>') commentopen = re.compile('<!--') commentclose = re.compile('-->') doubledash = re.compile('--') attrtrans = string.maketrans(' \r\n\t', ' ') # definitions for XML namespaces _NCName = '[a-zA-Z_][-a-zA-Z0-9._]*' # XML Name, minus the ":" ncname = re.compile(_NCName + '$') qname = re.compile('(?:(?P<prefix>' + _NCName + '):)?' # optional prefix '(?P<local>' + _NCName + ')$') xmlns = re.compile('xmlns(?::(?P<ncname>'+_NCName+'))?$') # XML parser base class -- find tags and call handler functions. # Usage: p = XMLParser(); p.feed(data); ...; p.close(). # The dtd is defined by deriving a class which defines methods with # special names to handle tags: start_foo and end_foo to handle <foo> # and </foo>, respectively. The data between tags is passed to the # parser by calling self.handle_data() with some data as argument (the # data may be split up in arbitrary chunks). class XMLParser: attributes = {} # default, to be overridden elements = {} # default, to be overridden # parsing options, settable using keyword args in __init__ __accept_unquoted_attributes = 0 __accept_missing_endtag_name = 0 __map_case = 0 __accept_utf8 = 0 __translate_attribute_references = 1 # Interface -- initialize and reset this instance def __init__(self, **kw): self.__fixed = 0 if 'accept_unquoted_attributes' in kw: self.__accept_unquoted_attributes = kw['accept_unquoted_attributes'] if 'accept_missing_endtag_name' in kw: self.__accept_missing_endtag_name = kw['accept_missing_endtag_name'] if 'map_case' in kw: self.__map_case = kw['map_case'] if 'accept_utf8' in kw: self.__accept_utf8 = kw['accept_utf8'] if 'translate_attribute_references' in kw: self.__translate_attribute_references = kw['translate_attribute_references'] self.reset() def __fixelements(self): self.__fixed = 1 self.elements = {} self.__fixdict(self.__dict__) self.__fixclass(self.__class__) def __fixclass(self, kl): self.__fixdict(kl.__dict__) for k in kl.__bases__: self.__fixclass(k) def __fixdict(self, dict): for key in dict.keys(): if key[:6] == 'start_': tag = key[6:] start, end = self.elements.get(tag, (None, None)) if start is None: self.elements[tag] = getattr(self, key), end elif key[:4] == 'end_': tag = key[4:] start, end = self.elements.get(tag, (None, None)) if end is None: self.elements[tag] = start, getattr(self, key) # Interface -- reset this instance. Loses all unprocessed data def reset(self): self.rawdata = '' self.stack = [] self.nomoretags = 0 self.literal = 0 self.lineno = 1 self.__at_start = 1 self.__seen_doctype = None self.__seen_starttag = 0 self.__use_namespaces = 0 self.__namespaces = {'xml':None} # xml is implicitly declared # backward compatibility hack: if elements not overridden, # fill it in ourselves if self.elements is XMLParser.elements: self.__fixelements() # For derived classes only -- enter literal mode (CDATA) till EOF def setnomoretags(self): self.nomoretags = self.literal = 1 # For derived classes only -- enter literal mode (CDATA) def setliteral(self, *args): self.literal = 1 # Interface -- feed some data to the parser. Call this as # often as you want, with as little or as much text as you # want (may include '\n'). (This just saves the text, all the # processing is done by goahead().) def feed(self, data): self.rawdata = self.rawdata + data self.goahead(0) # Interface -- handle the remaining data def close(self): self.goahead(1) if self.__fixed: self.__fixed = 0 # remove self.elements so that we don't leak del self.elements # Interface -- translate references def translate_references(self, data, all = 1): if not self.__translate_attribute_references: return data i = 0 while 1: res = amp.search(data, i) if res is None: return data s = res.start(0) res = ref.match(data, s) if res is None: self.syntax_error("bogus `&'") i = s+1 continue i = res.end(0) str = res.group(1) rescan = 0 if str[0] == '#': if str[1] == 'x': str = chr(int(str[2:], 16)) else: str = chr(int(str[1:])) if data[i - 1] != ';': self.syntax_error("`;' missing after char reference") i = i-1 elif all: if str in self.entitydefs: str = self.entitydefs[str] rescan = 1 elif data[i - 1] != ';': self.syntax_error("bogus `&'") i = s + 1 # just past the & continue else: self.syntax_error("reference to unknown entity `&%s;'" % str) str = '&' + str + ';' elif data[i - 1] != ';': self.syntax_error("bogus `&'") i = s + 1 # just past the & continue # when we get here, str contains the translated text and i points # to the end of the string that is to be replaced data = data[:s] + str + data[i:] if rescan: i = s else: i = s + len(str) # Interface - return a dictionary of all namespaces currently valid def getnamespace(self): nsdict = {} for t, d, nst in self.stack: nsdict.update(d) return nsdict # Internal -- handle data as far as reasonable. May leave state # and data to be processed by a subsequent call. If 'end' is # true, force handling all data as if followed by EOF marker. def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: data = rawdata[i:j] if self.__at_start and space.match(data) is None: self.syntax_error('illegal data at start of file') self.__at_start = 0 if not self.stack and space.match(data) is None: self.syntax_error('data not in content') if not self.__accept_utf8 and illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise Error('only XML version 1.0 supported') if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') if self.__map_case: self.__seen_doctype = self.__seen_doctype.lower() self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue elif rawdata[i] == '&': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + res.group(0).count('\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.__map_case: name = name.lower() if name in self.entitydefs: self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.unknown_entityref(name) self.lineno = self.lineno + res.group(0).count('\n') continue elif rawdata[i] == ']': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise Error('neither < nor & ??') # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if not self.__accept_utf8 and illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + data.count('\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1][0]) # Internal -- parse comment, return length or -1 if not terminated def parse_comment(self, i): rawdata = self.rawdata if rawdata[i:i+4] != '<!--': raise Error('unexpected call to handle_comment') res = commentclose.search(rawdata, i+4) if res is None: return -1 if doubledash.search(rawdata, i+4, res.start(0)): self.syntax_error("`--' inside comment") if rawdata[res.start(0)-1] == '-': self.syntax_error('comment cannot end in three dashes') if not self.__accept_utf8 and \ illegal.search(rawdata, i+4, res.start(0)): self.syntax_error('illegal character in comment') self.handle_comment(rawdata[i+4: res.start(0)]) return res.end(0) # Internal -- handle DOCTYPE tag, return length or -1 if not terminated def parse_doctype(self, res): rawdata = self.rawdata n = len(rawdata) name = res.group('name') if self.__map_case: name = name.lower() pubid, syslit = res.group('pubid', 'syslit') if pubid is not None: pubid = pubid[1:-1] # remove quotes pubid = ' '.join(pubid.split()) # normalize if syslit is not None: syslit = syslit[1:-1] # remove quotes j = k = res.end(0) if k >= n: return -1 if rawdata[k] == '[': level = 0 k = k+1 dq = sq = 0 while k < n: c = rawdata[k] if not sq and c == '"': dq = not dq elif not dq and c == "'": sq = not sq elif sq or dq: pass elif level <= 0 and c == ']': res = endbracket.match(rawdata, k+1) if res is None: return -1 self.handle_doctype(name, pubid, syslit, rawdata[j+1:k]) return res.end(0) elif c == '<': level = level + 1 elif c == '>': level = level - 1 if level < 0: self.syntax_error("bogus `>' in DOCTYPE") k = k+1 res = endbracketfind.match(rawdata, k) if res is None: return -1 if endbracket.match(rawdata, k) is None: self.syntax_error('garbage in DOCTYPE') self.handle_doctype(name, pubid, syslit, None) return res.end(0) # Internal -- handle CDATA tag, return length or -1 if not terminated def parse_cdata(self, i): rawdata = self.rawdata if rawdata[i:i+9] != '<![CDATA[': raise Error('unexpected call to parse_cdata') res = cdataclose.search(rawdata, i+9) if res is None: return -1 if not self.__accept_utf8 and \ illegal.search(rawdata, i+9, res.start(0)): self.syntax_error('illegal character in CDATA') if not self.stack: self.syntax_error('CDATA not in content') self.handle_cdata(rawdata[i+9:res.start(0)]) return res.end(0) __xml_namespace_attributes = {'ns':None, 'src':None, 'prefix':None} # Internal -- handle a processing instruction tag def parse_proc(self, i): rawdata = self.rawdata end = procclose.search(rawdata, i) if end is None: return -1 j = end.start(0) if not self.__accept_utf8 and illegal.search(rawdata, i+2, j): self.syntax_error('illegal character in processing instruction') res = tagfind.match(rawdata, i+2) if res is None: raise Error('unexpected call to parse_proc') k = res.end(0) name = res.group(0) if self.__map_case: name = name.lower() if name == 'xml:namespace': self.syntax_error('old-fashioned namespace declaration') self.__use_namespaces = -1 # namespace declaration # this must come after the <?xml?> declaration (if any) # and before the <!DOCTYPE> (if any). if self.__seen_doctype or self.__seen_starttag: self.syntax_error('xml:namespace declaration too late in document') attrdict, namespace, k = self.parse_attributes(name, k, j) if namespace: self.syntax_error('namespace declaration inside namespace declaration') for attrname in attrdict.keys(): if not attrname in self.__xml_namespace_attributes: self.syntax_error("unknown attribute `%s' in xml:namespace tag" % attrname) if not 'ns' in attrdict or not 'prefix' in attrdict: self.syntax_error('xml:namespace without required attributes') prefix = attrdict.get('prefix') if ncname.match(prefix) is None: self.syntax_error('xml:namespace illegal prefix value') return end.end(0) if prefix in self.__namespaces: self.syntax_error('xml:namespace prefix not unique') self.__namespaces[prefix] = attrdict['ns'] else: if name.lower() == 'xml': self.syntax_error('illegal processing instruction target name') self.handle_proc(name, rawdata[k:j]) return end.end(0) # Internal -- parse attributes between i and j def parse_attributes(self, tag, i, j): rawdata = self.rawdata attrdict = {} namespace = {} while i < j: res = attrfind.match(rawdata, i) if res is None: break attrname, attrvalue = res.group('name', 'value') if self.__map_case: attrname = attrname.lower() i = res.end(0) if attrvalue is None: self.syntax_error("no value specified for attribute `%s'" % attrname) attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] elif not self.__accept_unquoted_attributes: self.syntax_error("attribute `%s' value not quoted" % attrname) res = xmlns.match(attrname) if res is not None: # namespace declaration ncname = res.group('ncname') namespace[ncname or ''] = attrvalue or None if not self.__use_namespaces: self.__use_namespaces = len(self.stack)+1 continue if '<' in attrvalue: self.syntax_error("`<' illegal in attribute value") if attrname in attrdict: self.syntax_error("attribute `%s' specified twice" % attrname) attrvalue = attrvalue.translate(attrtrans) attrdict[attrname] = self.translate_references(attrvalue) return attrdict, namespace, i # Internal -- handle starttag, return length or -1 if not terminated def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracketfind.match(rawdata, i+1) if end is None: return -1 tag = starttagmatch.match(rawdata, i) if tag is None or tag.end(0) != end.end(0): self.syntax_error('garbage in starttag') return end.end(0) nstag = tagname = tag.group('tagname') if self.__map_case: nstag = tagname = nstag.lower() if not self.__seen_starttag and self.__seen_doctype and \ tagname != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE') if self.__seen_starttag and not self.stack: self.syntax_error('multiple elements on top level') k, j = tag.span('attrs') attrdict, nsdict, k = self.parse_attributes(tagname, k, j) self.stack.append((tagname, nsdict, nstag)) if self.__use_namespaces: res = qname.match(tagname) else: res = None if res is not None: prefix, nstag = res.group('prefix', 'local') if prefix is None: prefix = '' ns = None for t, d, nst in self.stack: if prefix in d: ns = d[prefix] if ns is None and prefix != '': ns = self.__namespaces.get(prefix) if ns is not None: nstag = ns + ' ' + nstag elif prefix != '': nstag = prefix + ':' + nstag # undo split self.stack[-1] = tagname, nsdict, nstag # translate namespace of attributes attrnamemap = {} # map from new name to old name (used for error reporting) for key in attrdict.keys(): attrnamemap[key] = key if self.__use_namespaces: nattrdict = {} for key, val in attrdict.items(): okey = key res = qname.match(key) if res is not None: aprefix, key = res.group('prefix', 'local') if self.__map_case: key = key.lower() if aprefix is not None: ans = None for t, d, nst in self.stack: if aprefix in d: ans = d[aprefix] if ans is None: ans = self.__namespaces.get(aprefix) if ans is not None: key = ans + ' ' + key else: key = aprefix + ':' + key nattrdict[key] = val attrnamemap[key] = okey attrdict = nattrdict attributes = self.attributes.get(nstag) if attributes is not None: for key in attrdict.keys(): if not key in attributes: self.syntax_error("unknown attribute `%s' in tag `%s'" % (attrnamemap[key], tagname)) for key, val in attributes.items(): if val is not None and not key in attrdict: attrdict[key] = val method = self.elements.get(nstag, (None, None))[0] self.finish_starttag(nstag, attrdict, method) if tag.group('slash') == '/': self.finish_endtag(tagname) return tag.end(0) # Internal -- parse endtag def parse_endtag(self, i): rawdata = self.rawdata end = endbracketfind.match(rawdata, i+1) if end is None: return -1 res = tagfind.match(rawdata, i+2) if res is None: if self.literal: self.handle_data(rawdata[i]) return i+1 if not self.__accept_missing_endtag_name: self.syntax_error('no name specified in end tag') tag = self.stack[-1][0] k = i+2 else: tag = res.group(0) if self.__map_case: tag = tag.lower() if self.literal: if not self.stack or tag != self.stack[-1][0]: self.handle_data(rawdata[i]) return i+1 k = res.end(0) if endbracket.match(rawdata, k) is None: self.syntax_error('garbage in end tag') self.finish_endtag(tag) return end.end(0) # Internal -- finish processing of start tag def finish_starttag(self, tagname, attrdict, method): if method is not None: self.handle_starttag(tagname, method, attrdict) else: self.unknown_starttag(tagname, attrdict) # Internal -- finish processing of end tag def finish_endtag(self, tag): self.literal = 0 if not tag: self.syntax_error('name-less end tag') found = len(self.stack) - 1 if found < 0: self.unknown_endtag(tag) return else: found = -1 for i in range(len(self.stack)): if tag == self.stack[i][0]: found = i if found == -1: self.syntax_error('unopened end tag') return while len(self.stack) > found: if found < len(self.stack) - 1: self.syntax_error('missing close tag for %s' % self.stack[-1][2]) nstag = self.stack[-1][2] method = self.elements.get(nstag, (None, None))[1] if method is not None: self.handle_endtag(nstag, method) else: self.unknown_endtag(nstag) if self.__use_namespaces == len(self.stack): self.__use_namespaces = 0 del self.stack[-1] # Overridable -- handle xml processing instruction def handle_xml(self, encoding, standalone): pass # Overridable -- handle DOCTYPE def handle_doctype(self, tag, pubid, syslit, data): pass # Overridable -- handle start tag def handle_starttag(self, tag, method, attrs): method(attrs) # Overridable -- handle end tag def handle_endtag(self, tag, method): method() # Example -- handle character reference, no need to override def handle_charref(self, name): try: if name[0] == 'x': n = int(name[1:], 16) else: n = int(name) except ValueError: self.unknown_charref(name) return if not 0 <= n <= 255: self.unknown_charref(name) return self.handle_data(chr(n)) # Definition of entities -- derived classes may override entitydefs = {'lt': '&#60;', # must use charref 'gt': '&#62;', 'amp': '&#38;', # must use charref 'quot': '&#34;', 'apos': '&#39;', } # Example -- handle data, should be overridden def handle_data(self, data): pass # Example -- handle cdata, could be overridden def handle_cdata(self, data): pass # Example -- handle comment, could be overridden def handle_comment(self, data): pass # Example -- handle processing instructions, could be overridden def handle_proc(self, name, data): pass # Example -- handle relatively harmless syntax errors, could be overridden def syntax_error(self, message): raise Error('Syntax error at line %d: %s' % (self.lineno, message)) # To be overridden -- handlers for unknown objects def unknown_starttag(self, tag, attrs): pass def unknown_endtag(self, tag): pass def unknown_charref(self, ref): pass def unknown_entityref(self, name): self.syntax_error("reference to unknown entity `&%s;'" % name) class TestXMLParser(XMLParser): def __init__(self, **kw): self.testdata = "" XMLParser.__init__(self, **kw) def handle_xml(self, encoding, standalone): self.flush() print 'xml: encoding =',encoding,'standalone =',standalone def handle_doctype(self, tag, pubid, syslit, data): self.flush() print 'DOCTYPE:',tag, repr(data) def handle_data(self, data): self.testdata = self.testdata + data if len(repr(self.testdata)) >= 70: self.flush() def flush(self): data = self.testdata if data: self.testdata = "" print 'data:', repr(data) def handle_cdata(self, data): self.flush() print 'cdata:', repr(data) def handle_proc(self, name, data): self.flush() print 'processing:',name,repr(data) def handle_comment(self, data): self.flush() r = repr(data) if len(r) > 68: r = r[:32] + '...' + r[-32:] print 'comment:', r def syntax_error(self, message): print 'error at line %d:' % self.lineno, message def unknown_starttag(self, tag, attrs): self.flush() if not attrs: print 'start tag: <' + tag + '>' else: print 'start tag: <' + tag, for name, value in attrs.items(): print name + '=' + '"' + value + '"', print '>' def unknown_endtag(self, tag): self.flush() print 'end tag: </' + tag + '>' def unknown_entityref(self, ref): self.flush() print '*** unknown entity ref: &' + ref + ';' def unknown_charref(self, ref): self.flush() print '*** unknown char ref: &#' + ref + ';' def close(self): XMLParser.close(self) self.flush() def test(args = None): import sys, getopt from time import time if not args: args = sys.argv[1:] opts, args = getopt.getopt(args, 'st') klass = TestXMLParser do_time = 0 for o, a in opts: if o == '-s': klass = XMLParser elif o == '-t': do_time = 1 if args: file = args[0] else: file = 'test.xml' if file == '-': f = sys.stdin else: try: f = open(file, 'r') except IOError, msg: print file, ":", msg sys.exit(1) data = f.read() if f is not sys.stdin: f.close() x = klass() t0 = time() try: if do_time: x.feed(data) x.close() else: for c in data: x.feed(c) x.close() except Error, msg: t1 = time() print msg if do_time: print 'total time: %g' % (t1-t0) sys.exit(1) t1 = time() if do_time: print 'total time: %g' % (t1-t0) if __name__ == '__main__': test()
doantranhoang/namebench
refs/heads/master
libnamebench/data_sources.py
173
#!/usr/bin/env python # Copyright 2009 Google Inc. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Provides data sources to use for benchmarking.""" import ConfigParser import glob import os import os.path import random import re import subprocess import sys import time # relative import addr_util import selectors import util # Pick the most accurate timer for a platform. Stolen from timeit.py: if sys.platform[:3] == 'win': DEFAULT_TIMER = time.clock else: DEFAULT_TIMER = time.time GLOBAL_DATA_CACHE = {} DEFAULT_CONFIG_PATH = 'config/data_sources.cfg' MAX_NON_UNIQUE_RECORD_COUNT = 500000 MAX_FILE_MTIME_AGE_DAYS = 45 MIN_FILE_SIZE = 10000 MIN_RECOMMENDED_RECORD_COUNT = 200 MAX_FQDN_SYNTHESIZE_PERCENT = 4 class DataSources(object): """A collection of methods related to available hostname data sources.""" def __init__(self, config_path=DEFAULT_CONFIG_PATH, status_callback=None): self.source_cache = GLOBAL_DATA_CACHE self.source_config = {} self.status_callback = status_callback self._LoadConfigFromPath(config_path) def msg(self, msg, **kwargs): if self.status_callback: self.status_callback(msg, **kwargs) else: print '- %s' % msg def _LoadConfigFromPath(self, path): """Load a configuration file describing data sources that may be available.""" conf_file = util.FindDataFile(path) config = ConfigParser.ConfigParser() config.read(conf_file) for section in config.sections(): if section not in self.source_config: self.source_config[section] = { 'name': None, 'search_paths': set(), 'full_hostnames': True, # Store whether or not this data source contains personal data 'synthetic': False, 'include_duplicates': False, 'max_mtime_days': MAX_FILE_MTIME_AGE_DAYS } for (key, value) in config.items(section): if key == 'name': self.source_config[section]['name'] = value elif key == 'full_hostnames' and int(value) == 0: self.source_config[section]['full_hostnames'] = False elif key == 'max_mtime_days': self.source_config[section]['max_mtime_days'] = int(value) elif key == 'include_duplicates': self.source_config[section]['include_duplicates'] = bool(value) elif key == 'synthetic': self.source_config[section]['synthetic'] = bool(value) else: self.source_config[section]['search_paths'].add(value) def ListSourceTypes(self): """Get a list of all data sources we know about.""" return sorted(self.source_config.keys()) def ListSourcesWithDetails(self): """Get a list of all data sources found with total counts. Returns: List of tuples in form of (short_name, full_name, full_hosts, # of entries) """ for source in self.ListSourceTypes(): max_mtime = self.source_config[source]['max_mtime_days'] self._GetHostsFromSource(source, min_file_size=MIN_FILE_SIZE, max_mtime_age_days=max_mtime) details = [] for source in self.source_cache: details.append((source, self.source_config[source]['name'], self.source_config[source]['synthetic'], len(self.source_cache[source]))) return sorted(details, key=lambda x: (x[2], x[3] * -1)) def ListSourceTitles(self): """Return a list of sources in title + count format.""" titles = [] seen_synthetic = False seen_organic = False for (unused_type, name, is_synthetic, count) in self.ListSourcesWithDetails(): if not is_synthetic: seen_organic = True if is_synthetic and seen_organic and not seen_synthetic: titles.append('-' * 36) seen_synthetic = True titles.append('%s (%s)' % (name, count)) return titles def ConvertSourceTitleToType(self, detail): """Convert a detail name to a source type.""" for source_type in self.source_config: if detail.startswith(self.source_config[source_type]['name']): return source_type def GetBestSourceDetails(self): return self.ListSourcesWithDetails()[0] def GetNameForSource(self, source): if source in self.source_config: return self.source_config[source]['name'] else: # Most likely a custom file path return source def GetCachedRecordCountForSource(self, source): return len(self.source_cache[source]) def _CreateRecordsFromHostEntries(self, entries, include_duplicates=False): """Create records from hosts, removing duplicate entries and IP's. Args: entries: A list of test-data entries. include_duplicates: Whether or not to filter duplicates (optional: False) Returns: A tuple of (filtered records, full_host_names (Boolean) Raises: ValueError: If no records could be grokked from the input. """ last_entry = None records = [] full_host_count = 0 for entry in entries: if entry == last_entry and not include_duplicates: continue else: last_entry = entry if ' ' in entry: (record_type, host) = entry.split(' ') else: record_type = 'A' host = entry if not addr_util.IP_RE.match(host) and not addr_util.INTERNAL_RE.search(host): if not host.endswith('.'): host += '.' records.append((record_type, host)) if addr_util.FQDN_RE.match(host): full_host_count += 1 if not records: raise ValueError('No records could be created from: %s' % entries) # Now that we've read everything, are we dealing with domains or full hostnames? full_host_percent = full_host_count / float(len(records)) * 100 if full_host_percent < MAX_FQDN_SYNTHESIZE_PERCENT: full_host_names = True else: full_host_names = False return (records, full_host_names) def GetTestsFromSource(self, source, count=50, select_mode=None): """Parse records from source, and return tuples to use for testing. Args: source: A source name (str) that has been configured. count: Number of tests to generate from the source (int) select_mode: automatic, weighted, random, chunk (str) Returns: A list of record tuples in the form of (req_type, hostname) Raises: ValueError: If no usable records are found from the data source. This is tricky because we support 3 types of input data: - List of domains - List of hosts - List of record_type + hosts """ records = [] if source in self.source_config: include_duplicates = self.source_config[source].get('include_duplicates', False) else: include_duplicates = False records = self._GetHostsFromSource(source) if not records: raise ValueError('Unable to generate records from %s (nothing found)' % source) self.msg('Generating tests from %s (%s records, selecting %s %s)' % (self.GetNameForSource(source), len(records), count, select_mode)) (records, are_records_fqdn) = self._CreateRecordsFromHostEntries(records, include_duplicates=include_duplicates) # First try to resolve whether to use weighted or random. if select_mode in ('weighted', 'automatic', None): # If we are in include_duplicates mode (cachemiss, cachehit, etc.), we have different rules. if include_duplicates: if count > len(records): select_mode = 'random' else: select_mode = 'chunk' elif len(records) != len(set(records)): if select_mode == 'weighted': self.msg('%s data contains duplicates, switching select_mode to random' % source) select_mode = 'random' else: select_mode = 'weighted' self.msg('Selecting %s out of %s sanitized records (%s mode).' % (count, len(records), select_mode)) if select_mode == 'weighted': records = selectors.WeightedDistribution(records, count) elif select_mode == 'chunk': records = selectors.ChunkSelect(records, count) elif select_mode == 'random': records = selectors.RandomSelect(records, count, include_duplicates=include_duplicates) else: raise ValueError('No such final selection mode: %s' % select_mode) # For custom filenames if source not in self.source_config: self.source_config[source] = {'synthetic': True} if are_records_fqdn: self.source_config[source]['full_hostnames'] = False self.msg('%s input appears to be predominantly domain names. Synthesizing FQDNs' % source) synthesized = [] for (req_type, hostname) in records: if not addr_util.FQDN_RE.match(hostname): hostname = self._GenerateRandomHostname(hostname) synthesized.append((req_type, hostname)) return synthesized else: return records def _GenerateRandomHostname(self, domain): """Generate a random hostname f or a given domain.""" oracle = random.randint(0, 100) if oracle < 70: return 'www.%s' % domain elif oracle < 95: return domain elif oracle < 98: return 'static.%s' % domain else: return 'cache-%s.%s' % (random.randint(0, 10), domain) def _GetHostsFromSource(self, source, min_file_size=None, max_mtime_age_days=None): """Get data for a particular source. This needs to be fast. Args: source: A configured source type (str) min_file_size: What the minimum allowable file size is for this source (int) max_mtime_age_days: Maximum days old the file can be for this source (int) Returns: list of hostnames gathered from data source. The results of this function are cached by source type. """ if source in self.source_cache: return self.source_cache[source] filename = self._FindBestFileForSource(source, min_file_size=min_file_size, max_mtime_age_days=max_mtime_age_days) if not filename: return None size_mb = os.path.getsize(filename) / 1024.0 / 1024.0 # Minimize our output if not self.source_config[source]['synthetic']: self.msg('Reading %s: %s (%0.1fMB)' % (self.GetNameForSource(source), filename, size_mb)) start_clock = DEFAULT_TIMER() if filename.endswith('.pcap') or filename.endswith('.tcp'): hosts = self._ExtractHostsFromPcapFile(filename) else: hosts = self._ExtractHostsFromHistoryFile(filename) if not hosts: hosts = self._ReadDataFile(filename) duration = DEFAULT_TIMER() - start_clock if duration > 5: self.msg('%s data took %1.1fs to read!' % (self.GetNameForSource(source), duration)) self.source_cache[source] = hosts return hosts def _ExtractHostsFromHistoryFile(self, path): """Get a list of sanitized records from a history file containing URLs.""" # This regexp is fairly general (no ip filtering), since we need speed more # than precision at this stage. parse_re = re.compile('https*://([\-\w]+\.[\-\w\.]+)') return parse_re.findall(open(path, 'rb').read()) def _ExtractHostsFromPcapFile(self, path): """Get a list of requests out of a pcap file - requires tcpdump.""" self.msg('Extracting requests from pcap file using tcpdump') cmd = 'tcpdump -r %s -n port 53' % path pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout parse_re = re.compile(' ([A-Z]+)\? ([\-\w\.]+)') requests = [] for line in pipe: if '?' not in line: continue match = parse_re.search(line) if match: requests.append(' '.join(match.groups())) return requests def _ReadDataFile(self, path): """Read a line-based datafile.""" records = [] domains_re = re.compile('^\w[\w\.-]+[a-zA-Z]$') requests_re = re.compile('^[A-Z]{1,4} \w[\w\.-]+\.$') for line in open(path): if domains_re.match(line) or requests_re.match(line): records.append(line.rstrip()) return records def _GetSourceSearchPaths(self, source): """Get a list of possible search paths (globs) for a given source.""" # This is likely a custom file path if source not in self.source_config: return [source] search_paths = [] environment_re = re.compile('%(\w+)%') # First get through resolving environment variables for path in self.source_config[source]['search_paths']: env_vars = set(environment_re.findall(path)) if env_vars: for variable in env_vars: env_var = os.getenv(variable, False) if env_var: path = path.replace('%%%s%%' % variable, env_var) else: path = None # If everything is good, replace all '/' chars with the os path variable. if path: path = path.replace('/', os.sep) search_paths.append(path) # This moment of weirdness brought to you by Windows XP(tm). If we find # a Local or Roaming keyword in path, add the other forms to the search # path. if sys.platform[:3] == 'win': keywords = ['Local', 'Roaming'] for keyword in keywords: if keyword in path: replacement = keywords[keywords.index(keyword)-1] search_paths.append(path.replace('\\%s' % keyword, '\\%s' % replacement)) search_paths.append(path.replace('\\%s' % keyword, '')) return search_paths def _FindBestFileForSource(self, source, min_file_size=None, max_mtime_age_days=None): """Find the best file (newest over X size) to use for a given source type. Args: source: source type min_file_size: What the minimum allowable file size is for this source (int) max_mtime_age_days: Maximum days old the file can be for this source (int) Returns: A file path. """ found = [] for path in self._GetSourceSearchPaths(source): if not os.path.isabs(path): path = util.FindDataFile(path) for filename in glob.glob(path): if min_file_size and os.path.getsize(filename) < min_file_size: self.msg('Skipping %s (only %sb)' % (filename, os.path.getsize(filename))) else: try: fp = open(filename, 'rb') fp.close() found.append(filename) except IOError: self.msg('Skipping %s (could not open)' % filename) if found: newest = sorted(found, key=os.path.getmtime)[-1] age_days = (time.time() - os.path.getmtime(newest)) / 86400 if max_mtime_age_days and age_days > max_mtime_age_days: pass # self.msg('Skipping %s (%2.0fd old)' % (newest, age_days)) else: return newest else: return None if __name__ == '__main__': parser = DataSources() print parser.ListSourceTypes() print parser.ListSourcesWithDetails() best = parser.ListSourcesWithDetails()[0][0] print len(parser.GetRecordsFromSource(best))
Darkmoth/python-django-4
refs/heads/master
Thing/env/Lib/encodings/cp857.py
593
""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP857.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp857', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x0131, # LATIN SMALL LETTER DOTLESS I 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x009e: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x009f: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x00a7: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x00ae, # REGISTERED SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x00b8: 0x00a9, # COPYRIGHT SIGN 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x00a2, # CENT SIGN 0x00be: 0x00a5, # YEN SIGN 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x00c7: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00d1: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00d2: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x00d5: None, # UNDEFINED 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x00a6, # BROKEN BAR 0x00de: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00e4: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00e5: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: None, # UNDEFINED 0x00e8: 0x00d7, # MULTIPLICATION SIGN 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00eb: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00ed: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x00ee: 0x00af, # MACRON 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: None, # UNDEFINED 0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00f4: 0x00b6, # PILCROW SIGN 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x00b9, # SUPERSCRIPT ONE 0x00fc: 0x00b3, # SUPERSCRIPT THREE 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Decoding Table decoding_table = ( u'\x00' # 0x0000 -> NULL u'\x01' # 0x0001 -> START OF HEADING u'\x02' # 0x0002 -> START OF TEXT u'\x03' # 0x0003 -> END OF TEXT u'\x04' # 0x0004 -> END OF TRANSMISSION u'\x05' # 0x0005 -> ENQUIRY u'\x06' # 0x0006 -> ACKNOWLEDGE u'\x07' # 0x0007 -> BELL u'\x08' # 0x0008 -> BACKSPACE u'\t' # 0x0009 -> HORIZONTAL TABULATION u'\n' # 0x000a -> LINE FEED u'\x0b' # 0x000b -> VERTICAL TABULATION u'\x0c' # 0x000c -> FORM FEED u'\r' # 0x000d -> CARRIAGE RETURN u'\x0e' # 0x000e -> SHIFT OUT u'\x0f' # 0x000f -> SHIFT IN u'\x10' # 0x0010 -> DATA LINK ESCAPE u'\x11' # 0x0011 -> DEVICE CONTROL ONE u'\x12' # 0x0012 -> DEVICE CONTROL TWO u'\x13' # 0x0013 -> DEVICE CONTROL THREE u'\x14' # 0x0014 -> DEVICE CONTROL FOUR u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x0016 -> SYNCHRONOUS IDLE u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK u'\x18' # 0x0018 -> CANCEL u'\x19' # 0x0019 -> END OF MEDIUM u'\x1a' # 0x001a -> SUBSTITUTE u'\x1b' # 0x001b -> ESCAPE u'\x1c' # 0x001c -> FILE SEPARATOR u'\x1d' # 0x001d -> GROUP SEPARATOR u'\x1e' # 0x001e -> RECORD SEPARATOR u'\x1f' # 0x001f -> UNIT SEPARATOR u' ' # 0x0020 -> SPACE u'!' # 0x0021 -> EXCLAMATION MARK u'"' # 0x0022 -> QUOTATION MARK u'#' # 0x0023 -> NUMBER SIGN u'$' # 0x0024 -> DOLLAR SIGN u'%' # 0x0025 -> PERCENT SIGN u'&' # 0x0026 -> AMPERSAND u"'" # 0x0027 -> APOSTROPHE u'(' # 0x0028 -> LEFT PARENTHESIS u')' # 0x0029 -> RIGHT PARENTHESIS u'*' # 0x002a -> ASTERISK u'+' # 0x002b -> PLUS SIGN u',' # 0x002c -> COMMA u'-' # 0x002d -> HYPHEN-MINUS u'.' # 0x002e -> FULL STOP u'/' # 0x002f -> SOLIDUS u'0' # 0x0030 -> DIGIT ZERO u'1' # 0x0031 -> DIGIT ONE u'2' # 0x0032 -> DIGIT TWO u'3' # 0x0033 -> DIGIT THREE u'4' # 0x0034 -> DIGIT FOUR u'5' # 0x0035 -> DIGIT FIVE u'6' # 0x0036 -> DIGIT SIX u'7' # 0x0037 -> DIGIT SEVEN u'8' # 0x0038 -> DIGIT EIGHT u'9' # 0x0039 -> DIGIT NINE u':' # 0x003a -> COLON u';' # 0x003b -> SEMICOLON u'<' # 0x003c -> LESS-THAN SIGN u'=' # 0x003d -> EQUALS SIGN u'>' # 0x003e -> GREATER-THAN SIGN u'?' # 0x003f -> QUESTION MARK u'@' # 0x0040 -> COMMERCIAL AT u'A' # 0x0041 -> LATIN CAPITAL LETTER A u'B' # 0x0042 -> LATIN CAPITAL LETTER B u'C' # 0x0043 -> LATIN CAPITAL LETTER C u'D' # 0x0044 -> LATIN CAPITAL LETTER D u'E' # 0x0045 -> LATIN CAPITAL LETTER E u'F' # 0x0046 -> LATIN CAPITAL LETTER F u'G' # 0x0047 -> LATIN CAPITAL LETTER G u'H' # 0x0048 -> LATIN CAPITAL LETTER H u'I' # 0x0049 -> LATIN CAPITAL LETTER I u'J' # 0x004a -> LATIN CAPITAL LETTER J u'K' # 0x004b -> LATIN CAPITAL LETTER K u'L' # 0x004c -> LATIN CAPITAL LETTER L u'M' # 0x004d -> LATIN CAPITAL LETTER M u'N' # 0x004e -> LATIN CAPITAL LETTER N u'O' # 0x004f -> LATIN CAPITAL LETTER O u'P' # 0x0050 -> LATIN CAPITAL LETTER P u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q u'R' # 0x0052 -> LATIN CAPITAL LETTER R u'S' # 0x0053 -> LATIN CAPITAL LETTER S u'T' # 0x0054 -> LATIN CAPITAL LETTER T u'U' # 0x0055 -> LATIN CAPITAL LETTER U u'V' # 0x0056 -> LATIN CAPITAL LETTER V u'W' # 0x0057 -> LATIN CAPITAL LETTER W u'X' # 0x0058 -> LATIN CAPITAL LETTER X u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y u'Z' # 0x005a -> LATIN CAPITAL LETTER Z u'[' # 0x005b -> LEFT SQUARE BRACKET u'\\' # 0x005c -> REVERSE SOLIDUS u']' # 0x005d -> RIGHT SQUARE BRACKET u'^' # 0x005e -> CIRCUMFLEX ACCENT u'_' # 0x005f -> LOW LINE u'`' # 0x0060 -> GRAVE ACCENT u'a' # 0x0061 -> LATIN SMALL LETTER A u'b' # 0x0062 -> LATIN SMALL LETTER B u'c' # 0x0063 -> LATIN SMALL LETTER C u'd' # 0x0064 -> LATIN SMALL LETTER D u'e' # 0x0065 -> LATIN SMALL LETTER E u'f' # 0x0066 -> LATIN SMALL LETTER F u'g' # 0x0067 -> LATIN SMALL LETTER G u'h' # 0x0068 -> LATIN SMALL LETTER H u'i' # 0x0069 -> LATIN SMALL LETTER I u'j' # 0x006a -> LATIN SMALL LETTER J u'k' # 0x006b -> LATIN SMALL LETTER K u'l' # 0x006c -> LATIN SMALL LETTER L u'm' # 0x006d -> LATIN SMALL LETTER M u'n' # 0x006e -> LATIN SMALL LETTER N u'o' # 0x006f -> LATIN SMALL LETTER O u'p' # 0x0070 -> LATIN SMALL LETTER P u'q' # 0x0071 -> LATIN SMALL LETTER Q u'r' # 0x0072 -> LATIN SMALL LETTER R u's' # 0x0073 -> LATIN SMALL LETTER S u't' # 0x0074 -> LATIN SMALL LETTER T u'u' # 0x0075 -> LATIN SMALL LETTER U u'v' # 0x0076 -> LATIN SMALL LETTER V u'w' # 0x0077 -> LATIN SMALL LETTER W u'x' # 0x0078 -> LATIN SMALL LETTER X u'y' # 0x0079 -> LATIN SMALL LETTER Y u'z' # 0x007a -> LATIN SMALL LETTER Z u'{' # 0x007b -> LEFT CURLY BRACKET u'|' # 0x007c -> VERTICAL LINE u'}' # 0x007d -> RIGHT CURLY BRACKET u'~' # 0x007e -> TILDE u'\x7f' # 0x007f -> DELETE u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS u'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE u'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA u'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX u'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS u'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE u'\xef' # 0x008b -> LATIN SMALL LETTER I WITH DIAERESIS u'\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\u0131' # 0x008d -> LATIN SMALL LETTER DOTLESS I u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE u'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE u'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS u'\xf2' # 0x0095 -> LATIN SMALL LETTER O WITH GRAVE u'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX u'\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE u'\u0130' # 0x0098 -> LATIN CAPITAL LETTER I WITH DOT ABOVE u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\xf8' # 0x009b -> LATIN SMALL LETTER O WITH STROKE u'\xa3' # 0x009c -> POUND SIGN u'\xd8' # 0x009d -> LATIN CAPITAL LETTER O WITH STROKE u'\u015e' # 0x009e -> LATIN CAPITAL LETTER S WITH CEDILLA u'\u015f' # 0x009f -> LATIN SMALL LETTER S WITH CEDILLA u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE u'\xf1' # 0x00a4 -> LATIN SMALL LETTER N WITH TILDE u'\xd1' # 0x00a5 -> LATIN CAPITAL LETTER N WITH TILDE u'\u011e' # 0x00a6 -> LATIN CAPITAL LETTER G WITH BREVE u'\u011f' # 0x00a7 -> LATIN SMALL LETTER G WITH BREVE u'\xbf' # 0x00a8 -> INVERTED QUESTION MARK u'\xae' # 0x00a9 -> REGISTERED SIGN u'\xac' # 0x00aa -> NOT SIGN u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER u'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\u2591' # 0x00b0 -> LIGHT SHADE u'\u2592' # 0x00b1 -> MEDIUM SHADE u'\u2593' # 0x00b2 -> DARK SHADE u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT u'\xc1' # 0x00b5 -> LATIN CAPITAL LETTER A WITH ACUTE u'\xc2' # 0x00b6 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX u'\xc0' # 0x00b7 -> LATIN CAPITAL LETTER A WITH GRAVE u'\xa9' # 0x00b8 -> COPYRIGHT SIGN u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT u'\xa2' # 0x00bd -> CENT SIGN u'\xa5' # 0x00be -> YEN SIGN u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL u'\xe3' # 0x00c6 -> LATIN SMALL LETTER A WITH TILDE u'\xc3' # 0x00c7 -> LATIN CAPITAL LETTER A WITH TILDE u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL u'\xa4' # 0x00cf -> CURRENCY SIGN u'\xba' # 0x00d0 -> MASCULINE ORDINAL INDICATOR u'\xaa' # 0x00d1 -> FEMININE ORDINAL INDICATOR u'\xca' # 0x00d2 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX u'\xcb' # 0x00d3 -> LATIN CAPITAL LETTER E WITH DIAERESIS u'\xc8' # 0x00d4 -> LATIN CAPITAL LETTER E WITH GRAVE u'\ufffe' # 0x00d5 -> UNDEFINED u'\xcd' # 0x00d6 -> LATIN CAPITAL LETTER I WITH ACUTE u'\xce' # 0x00d7 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX u'\xcf' # 0x00d8 -> LATIN CAPITAL LETTER I WITH DIAERESIS u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT u'\u2588' # 0x00db -> FULL BLOCK u'\u2584' # 0x00dc -> LOWER HALF BLOCK u'\xa6' # 0x00dd -> BROKEN BAR u'\xcc' # 0x00de -> LATIN CAPITAL LETTER I WITH GRAVE u'\u2580' # 0x00df -> UPPER HALF BLOCK u'\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S u'\xd4' # 0x00e2 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX u'\xd2' # 0x00e3 -> LATIN CAPITAL LETTER O WITH GRAVE u'\xf5' # 0x00e4 -> LATIN SMALL LETTER O WITH TILDE u'\xd5' # 0x00e5 -> LATIN CAPITAL LETTER O WITH TILDE u'\xb5' # 0x00e6 -> MICRO SIGN u'\ufffe' # 0x00e7 -> UNDEFINED u'\xd7' # 0x00e8 -> MULTIPLICATION SIGN u'\xda' # 0x00e9 -> LATIN CAPITAL LETTER U WITH ACUTE u'\xdb' # 0x00ea -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX u'\xd9' # 0x00eb -> LATIN CAPITAL LETTER U WITH GRAVE u'\xec' # 0x00ec -> LATIN SMALL LETTER I WITH GRAVE u'\xff' # 0x00ed -> LATIN SMALL LETTER Y WITH DIAERESIS u'\xaf' # 0x00ee -> MACRON u'\xb4' # 0x00ef -> ACUTE ACCENT u'\xad' # 0x00f0 -> SOFT HYPHEN u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN u'\ufffe' # 0x00f2 -> UNDEFINED u'\xbe' # 0x00f3 -> VULGAR FRACTION THREE QUARTERS u'\xb6' # 0x00f4 -> PILCROW SIGN u'\xa7' # 0x00f5 -> SECTION SIGN u'\xf7' # 0x00f6 -> DIVISION SIGN u'\xb8' # 0x00f7 -> CEDILLA u'\xb0' # 0x00f8 -> DEGREE SIGN u'\xa8' # 0x00f9 -> DIAERESIS u'\xb7' # 0x00fa -> MIDDLE DOT u'\xb9' # 0x00fb -> SUPERSCRIPT ONE u'\xb3' # 0x00fc -> SUPERSCRIPT THREE u'\xb2' # 0x00fd -> SUPERSCRIPT TWO u'\u25a0' # 0x00fe -> BLACK SQUARE u'\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK 0x00a2: 0x00bd, # CENT SIGN 0x00a3: 0x009c, # POUND SIGN 0x00a4: 0x00cf, # CURRENCY SIGN 0x00a5: 0x00be, # YEN SIGN 0x00a6: 0x00dd, # BROKEN BAR 0x00a7: 0x00f5, # SECTION SIGN 0x00a8: 0x00f9, # DIAERESIS 0x00a9: 0x00b8, # COPYRIGHT SIGN 0x00aa: 0x00d1, # FEMININE ORDINAL INDICATOR 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x00aa, # NOT SIGN 0x00ad: 0x00f0, # SOFT HYPHEN 0x00ae: 0x00a9, # REGISTERED SIGN 0x00af: 0x00ee, # MACRON 0x00b0: 0x00f8, # DEGREE SIGN 0x00b1: 0x00f1, # PLUS-MINUS SIGN 0x00b2: 0x00fd, # SUPERSCRIPT TWO 0x00b3: 0x00fc, # SUPERSCRIPT THREE 0x00b4: 0x00ef, # ACUTE ACCENT 0x00b5: 0x00e6, # MICRO SIGN 0x00b6: 0x00f4, # PILCROW SIGN 0x00b7: 0x00fa, # MIDDLE DOT 0x00b8: 0x00f7, # CEDILLA 0x00b9: 0x00fb, # SUPERSCRIPT ONE 0x00ba: 0x00d0, # MASCULINE ORDINAL INDICATOR 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER 0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF 0x00be: 0x00f3, # VULGAR FRACTION THREE QUARTERS 0x00bf: 0x00a8, # INVERTED QUESTION MARK 0x00c0: 0x00b7, # LATIN CAPITAL LETTER A WITH GRAVE 0x00c1: 0x00b5, # LATIN CAPITAL LETTER A WITH ACUTE 0x00c2: 0x00b6, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00c3: 0x00c7, # LATIN CAPITAL LETTER A WITH TILDE 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c8: 0x00d4, # LATIN CAPITAL LETTER E WITH GRAVE 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE 0x00ca: 0x00d2, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00cb: 0x00d3, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00cc: 0x00de, # LATIN CAPITAL LETTER I WITH GRAVE 0x00cd: 0x00d6, # LATIN CAPITAL LETTER I WITH ACUTE 0x00ce: 0x00d7, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00cf: 0x00d8, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00d1: 0x00a5, # LATIN CAPITAL LETTER N WITH TILDE 0x00d2: 0x00e3, # LATIN CAPITAL LETTER O WITH GRAVE 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE 0x00d4: 0x00e2, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00d5: 0x00e5, # LATIN CAPITAL LETTER O WITH TILDE 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00d7: 0x00e8, # MULTIPLICATION SIGN 0x00d8: 0x009d, # LATIN CAPITAL LETTER O WITH STROKE 0x00d9: 0x00eb, # LATIN CAPITAL LETTER U WITH GRAVE 0x00da: 0x00e9, # LATIN CAPITAL LETTER U WITH ACUTE 0x00db: 0x00ea, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S 0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e3: 0x00c6, # LATIN SMALL LETTER A WITH TILDE 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE 0x00e6: 0x0091, # LATIN SMALL LIGATURE AE 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA 0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE 0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ec: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00ef: 0x008b, # LATIN SMALL LETTER I WITH DIAERESIS 0x00f1: 0x00a4, # LATIN SMALL LETTER N WITH TILDE 0x00f2: 0x0095, # LATIN SMALL LETTER O WITH GRAVE 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f5: 0x00e4, # LATIN SMALL LETTER O WITH TILDE 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x00f6, # DIVISION SIGN 0x00f8: 0x009b, # LATIN SMALL LETTER O WITH STROKE 0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE 0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS 0x00ff: 0x00ed, # LATIN SMALL LETTER Y WITH DIAERESIS 0x011e: 0x00a6, # LATIN CAPITAL LETTER G WITH BREVE 0x011f: 0x00a7, # LATIN SMALL LETTER G WITH BREVE 0x0130: 0x0098, # LATIN CAPITAL LETTER I WITH DOT ABOVE 0x0131: 0x008d, # LATIN SMALL LETTER DOTLESS I 0x015e: 0x009e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x015f: 0x009f, # LATIN SMALL LETTER S WITH CEDILLA 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE }
etuna-SBF-kog/Stadsparken
refs/heads/master
env/lib/python2.7/site-packages/setuptools/command/__init__.py
210
__all__ = [ 'alias', 'bdist_egg', 'bdist_rpm', 'build_ext', 'build_py', 'develop', 'easy_install', 'egg_info', 'install', 'install_lib', 'rotate', 'saveopts', 'sdist', 'setopt', 'test', 'upload', 'install_egg_info', 'install_scripts', 'register', 'bdist_wininst', 'upload_docs', ] from setuptools.command import install_scripts import sys if sys.version>='2.5': # In Python 2.5 and above, distutils includes its own upload command __all__.remove('upload') from distutils.command.bdist import bdist if 'egg' not in bdist.format_commands: bdist.format_command['egg'] = ('bdist_egg', "Python .egg file") bdist.format_commands.append('egg') del bdist, sys
hehongliang/tensorflow
refs/heads/master
tensorflow/contrib/data/python/kernel_tests/slide_dataset_op_test.py
9
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # ============================================================================== """Tests for the experimental input pipeline ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.contrib.data.python.ops import sliding from tensorflow.python.data.kernel_tests import test_base from tensorflow.python.data.ops import dataset_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class SlideDatasetTest(test_base.DatasetTestBase, parameterized.TestCase): @parameterized.named_parameters( ("1", 20, 14, 7, 1), ("2", 20, 17, 9, 1), ("3", 20, 14, 14, 1), ("4", 20, 10, 14, 1), ("5", 20, 14, 19, 1), ("6", 20, 4, 1, 2), ("7", 20, 2, 1, 6), ("8", 20, 4, 7, 2), ("9", 20, 2, 7, 6), ("10", 1, 10, 4, 1), ("11", 0, 10, 4, 1), ) def testSlideDataset(self, count, window_size, window_shift, window_stride): """Tests a dataset that slides a window its input elements.""" components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) count_t = array_ops.placeholder(dtypes.int64, shape=[]) window_size_t = array_ops.placeholder(dtypes.int64, shape=[]) window_shift_t = array_ops.placeholder(dtypes.int64, shape=[]) window_stride_t = array_ops.placeholder(dtypes.int64, shape=[]) def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) # The pipeline is TensorSliceDataset -> MapDataset(square_3) -> # RepeatDataset(count) -> # _SlideDataset(window_size, window_shift, window_stride). iterator = ( dataset_ops.Dataset.from_tensor_slices(components).map(_map_fn) .repeat(count).apply( sliding.sliding_window_batch( window_size=window_size_t, window_shift=window_shift_t, window_stride=window_stride_t)).make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([[None] + list(c.shape[1:]) for c in components], [t.shape.as_list() for t in get_next]) with self.cached_session() as sess: sess.run( init_op, feed_dict={ count_t: count, window_size_t: window_size, window_shift_t: window_shift, window_stride_t: window_stride }) num_batches = (count * 7 - ( (window_size - 1) * window_stride + 1)) // window_shift + 1 for i in range(num_batches): result = sess.run(get_next) for component, result_component in zip(components, result): for j in range(window_size): self.assertAllEqual( component[(i * window_shift + j * window_stride) % 7]**2, result_component[j]) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) @parameterized.named_parameters( ("1", 20, 14, 7, 1), ("2", 20, 17, 9, 1), ("3", 20, 14, 14, 1), ("4", 20, 10, 14, 1), ("5", 20, 14, 19, 1), ("6", 20, 4, 1, 2), ("7", 20, 2, 1, 6), ("8", 20, 4, 7, 2), ("9", 20, 2, 7, 6), ("10", 1, 10, 4, 1), ("11", 0, 10, 4, 1), ) def testSlideDatasetDeprecated(self, count, window_size, stride, window_stride): """Tests a dataset that slides a window its input elements.""" components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) count_t = array_ops.placeholder(dtypes.int64, shape=[]) window_size_t = array_ops.placeholder(dtypes.int64, shape=[]) stride_t = array_ops.placeholder(dtypes.int64, shape=[]) window_stride_t = array_ops.placeholder(dtypes.int64, shape=[]) def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) # The pipeline is TensorSliceDataset -> MapDataset(square_3) -> # RepeatDataset(count) -> _SlideDataset(window_size, stride, window_stride). iterator = ( dataset_ops.Dataset.from_tensor_slices(components).map(_map_fn) .repeat(count).apply( sliding.sliding_window_batch( window_size=window_size_t, stride=stride_t, window_stride=window_stride_t)).make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([[None] + list(c.shape[1:]) for c in components], [t.shape.as_list() for t in get_next]) with self.cached_session() as sess: sess.run( init_op, feed_dict={ count_t: count, window_size_t: window_size, stride_t: stride, window_stride_t: window_stride }) num_batches = (count * 7 - ( (window_size - 1) * window_stride + 1)) // stride + 1 for i in range(num_batches): result = sess.run(get_next) for component, result_component in zip(components, result): for j in range(window_size): self.assertAllEqual( component[(i * stride + j * window_stride) % 7]**2, result_component[j]) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) @parameterized.named_parameters( ("1", 14, 0, 3, 1), ("2", 14, 3, 0, 1), ("3", 14, 3, 3, 0), ) def testSlideDatasetInvalid(self, count, window_size, window_shift, window_stride): count_t = array_ops.placeholder(dtypes.int64, shape=[]) window_size_t = array_ops.placeholder(dtypes.int64, shape=[]) window_shift_t = array_ops.placeholder(dtypes.int64, shape=[]) window_stride_t = array_ops.placeholder(dtypes.int64, shape=[]) iterator = ( dataset_ops.Dataset.range(10).map(lambda x: x).repeat(count_t).apply( sliding.sliding_window_batch( window_size=window_size_t, window_shift=window_shift_t, window_stride=window_stride_t)).make_initializable_iterator()) init_op = iterator.initializer with self.cached_session() as sess: with self.assertRaises(errors.InvalidArgumentError): sess.run( init_op, feed_dict={ count_t: count, window_size_t: window_size, window_shift_t: window_shift, window_stride_t: window_stride }) def testSlideDatasetValueError(self): with self.assertRaises(ValueError): dataset_ops.Dataset.range(10).map(lambda x: x).apply( sliding.sliding_window_batch( window_size=1, stride=1, window_shift=1, window_stride=1)) def testSlideSparse(self): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=[[0]], values=(i * [1]), dense_shape=[1]) iterator = dataset_ops.Dataset.range(10).map(_sparse).apply( sliding.sliding_window_batch( window_size=5, window_shift=3)).make_initializable_iterator() init_op = iterator.initializer get_next = iterator.get_next() with self.cached_session() as sess: sess.run(init_op) num_batches = (10 - 5) // 3 + 1 for i in range(num_batches): actual = sess.run(get_next) expected = sparse_tensor.SparseTensorValue( indices=[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]], values=[i * 3, i * 3 + 1, i * 3 + 2, i * 3 + 3, i * 3 + 4], dense_shape=[5, 1]) self.assertTrue(sparse_tensor.is_sparse(actual)) self.assertSparseValuesEqual(actual, expected) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testSlideSparseWithDifferentDenseShapes(self): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=array_ops.expand_dims( math_ops.range(i, dtype=dtypes.int64), 1), values=array_ops.fill([math_ops.to_int32(i)], i), dense_shape=[i]) iterator = dataset_ops.Dataset.range(10).map(_sparse).apply( sliding.sliding_window_batch( window_size=5, window_shift=3)).make_initializable_iterator() init_op = iterator.initializer get_next = iterator.get_next() with self.cached_session() as sess: sess.run(init_op) num_batches = (10 - 5) // 3 + 1 for i in range(num_batches): actual = sess.run(get_next) expected_indices = [] expected_values = [] for j in range(5): for k in range(i * 3 + j): expected_indices.append([j, k]) expected_values.append(i * 3 + j) expected = sparse_tensor.SparseTensorValue( indices=expected_indices, values=expected_values, dense_shape=[5, i * 3 + 5 - 1]) self.assertTrue(sparse_tensor.is_sparse(actual)) self.assertSparseValuesEqual(actual, expected) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testNestedSlideSparse(self): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=[[0]], values=(i * [1]), dense_shape=[1]) iterator = ( dataset_ops.Dataset.range(10).map(_sparse).apply( sliding.sliding_window_batch(window_size=4, window_shift=2)).apply( sliding.sliding_window_batch(window_size=3, window_shift=1)) .make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() with self.cached_session() as sess: sess.run(init_op) # Slide: 1st batch. actual = sess.run(get_next) expected = sparse_tensor.SparseTensorValue( indices=[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [1, 0, 0], [1, 1, 0], [1, 2, 0], [1, 3, 0], [2, 0, 0], [2, 1, 0], [2, 2, 0], [2, 3, 0]], values=[0, 1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 7], dense_shape=[3, 4, 1]) self.assertTrue(sparse_tensor.is_sparse(actual)) self.assertSparseValuesEqual(actual, expected) # Slide: 2nd batch. actual = sess.run(get_next) expected = sparse_tensor.SparseTensorValue( indices=[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [1, 0, 0], [1, 1, 0], [1, 2, 0], [1, 3, 0], [2, 0, 0], [2, 1, 0], [2, 2, 0], [2, 3, 0]], values=[2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, 9], dense_shape=[3, 4, 1]) self.assertTrue(sparse_tensor.is_sparse(actual)) self.assertSparseValuesEqual(actual, expected) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testSlideShapeError(self): def generator(): yield [1.0, 2.0, 3.0] yield [4.0, 5.0, 6.0] yield [7.0, 8.0, 9.0, 10.0] iterator = ( dataset_ops.Dataset.from_generator( generator, dtypes.float32, output_shapes=[None]).apply( sliding.sliding_window_batch(window_size=3, window_shift=1)) .make_initializable_iterator()) next_element = iterator.get_next() with self.cached_session() as sess: sess.run(iterator.initializer) with self.assertRaisesRegexp( errors.InvalidArgumentError, r"Cannot batch tensors with different shapes in component 0. " r"First element had shape \[3\] and element 2 had shape \[4\]."): sess.run(next_element) if __name__ == "__main__": test.main()
menegon/geonode
refs/heads/master
geonode/upload/templatetags/upload_tags.py
35
from django import template register = template.Library() @register.simple_tag def upload_js(): return """ <!-- The template to display files available for upload --> <script id="template-upload" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-upload fade"> <td class="preview"><span class="fade"></span></td> <td class="name"><span>{%=file.name%}</span></td> <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td> {% if (file.error) { %} <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%} \ </span> {%=locale.fileupload.errors[file.error] || file.error%}</td> {% } else if (o.files.valid && !i) { %} <td> <div class="progress progress-success progress-striped active"><div class="bar" style="width:0%;">\ </div></div> </td> <td class="start">{% if (!o.options.autoUpload) { %} <button class="btn btn-success"> <i class="icon-upload icon-white"></i> <span>{%=locale.fileupload.start%}</span> </button> {% } %}</td> {% } else { %} <td colspan="2"></td> {% } %} <td class="cancel">{% if (!i) { %} <button class="btn btn-warning"> <i class="icon-ban-circle icon-white"></i> <span>{%=locale.fileupload.cancel%}</span> </button> {% } %}</td> </tr> {% } %} </script> <!-- The template to display files available for download --> <script id="template-download" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-download fade"> {% if (file.error) { %} <td></td> <td class="name"><span>{%=file.name%}</span></td> <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td> <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}\ </span> {%=locale.fileupload.errors[file.error] || file.error%}</td> {% } else { %} <td class="preview">{% if (file.thumbnail_url) { %} <a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}">\ <img src="{%=file.thumbnail_url%}"></a> {% } %}</td> <td class="name"> <a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" \ download="{%=file.name%}">{%=file.name%}</a> </td> <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td> <td colspan="2"></td> {% } %} <td class="delete"> <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}"> <i class="icon-trash icon-white"></i> <span>{%=locale.fileupload.destroy%}</span> </button> <input type="checkbox" name="delete" value="1"> </td> </tr> {% } %} </script> """
datacats/datacats
refs/heads/master
datacats/cli/main.py
5
# Copyright 2014-2015 Boxkite Inc. # This file is part of the DataCats package and is released under # the terms of the GNU Affero General Public License version 3.0. # See LICENSE.txt or http://www.fsf.org/licensing/licenses/agpl-3.0.html """datacats command line interface Usage: datacats COMMAND [ARGUMENTS...] datacats --help [COMMAND] datacats --version The datacats commands available are: create Create a new environment info Display information about environment and running containers init Initialize a purged environment or copied environment directory install Install or reinstall Python packages within this environment less Recompile less files in an environment list List all environments for this user logs Display or follow container logs migrate Migrates an environment to the newest datadir format open Open web browser window to this environment paster Run a paster command from the current directory pull Download or update required datacats docker images purge Purge environment database and uploaded files reload Reload environment source and configuration reset Resets a site to the default state shell Run a command or interactive shell within this environment start Create containers and start serving environment stop Stop serving environment and remove all its containers tweak Commands operating on environment data See 'datacats help COMMAND' for information about options and arguments available to each command. """ import sys import traceback from docopt import docopt from datacats.cli import (create, manage, install, pull, purge, shell, deploy, migrate, less) from datacats.environment import Environment from datacats.error import DatacatsError, UndocumentedError from datacats.userprofile import UserProfile from datacats.version import __version__ COMMANDS = { 'create': create.create, 'deploy': deploy.deploy, 'info': manage.info, 'init': create.init, 'install': install.install, 'list': manage.list_, 'logs': manage.logs, 'open': manage.open_, 'paster': shell.paster, 'pull': pull.pull, 'purge': purge.purge, 'reload': manage.reload_, 'shell': shell.shell, 'start': manage.start, 'stop': manage.stop, 'migrate': migrate.migrate, 'less': less.less, 'reset': create.reset, 'tweak': manage.tweak, } COMMANDS_THAT_USE_SSH = [ deploy.deploy ] def main(): """ The main entry point for datacats cli tool (as defined in setup.py's entry_points) It parses the cli arguments for corresponding options and runs the corresponding command """ # pylint: disable=bare-except try: command_fn, opts = _parse_arguments(sys.argv[1:]) # purge handles loading differently # 1 - Bail and just call the command if it doesn't have ENVIRONMENT. if command_fn == purge.purge or 'ENVIRONMENT' not in opts: return command_fn(opts) environment = Environment.load( opts['ENVIRONMENT'] or '.', opts['--site'] if '--site' in opts else 'primary') if command_fn not in COMMANDS_THAT_USE_SSH: return command_fn(environment, opts) # for commands that communicate with a remote server # we load UserProfile and test our communication user_profile = UserProfile() user_profile.test_ssh_key(environment) return command_fn(environment, opts, user_profile) except DatacatsError as e: _error_exit(e) except SystemExit: raise except: exc_info = "\n".join([line.rstrip() for line in traceback.format_exception(*sys.exc_info())]) user_message = ("Something that should not" " have happened happened when attempting" " to run this command:\n" " datacats {args}\n\n" "It is seems to be a bug.\n" "Please report this issue to us by" " creating an issue ticket at\n\n" " https://github.com/datacats/datacats/issues\n\n" "so that we would be able to look into that " "and fix the issue." ).format(args=" ".join(sys.argv[1:])) _error_exit(DatacatsError(user_message, parent_exception=UndocumentedError(exc_info))) def _error_exit(exception): if sys.stdout.isatty(): # error message to have colors if stdout goes to shell exception.pretty_print() else: print exception sys.exit(1) def _parse_arguments(args): command, args = _subcommand_arguments(args) if not command: # allow --version opts = docopt(__doc__, args, version=__version__) # if above didn't exit, this certainly will return docopt(__doc__, ['--help']) command_fn = COMMANDS[command] opts = docopt(command_fn.__doc__, args, version=__version__) return command_fn, opts def _subcommand_arguments(args): """ Return (subcommand, (possibly adjusted) arguments for that subcommand) Returns (None, args) when no subcommand is found Parsing our arguments is hard. Each subcommand has its own docopt validation, and some subcommands (paster and shell) have positional options (some options passed to datacats and others passed to commands run inside the container) """ skip_site = False # Find subcommand without docopt so that subcommand options may appear # anywhere for i, a in enumerate(args): if skip_site: skip_site = False continue if a.startswith('-'): if a == '-s' or a == '--site': skip_site = True continue if a == 'help': return _subcommand_arguments(args[:i] + ['--help'] + args[i + 1:]) if a not in COMMANDS: raise DatacatsError("\'{0}\' command is not recognized. \n" "See \'datacats help\' for the list of available commands".format(a)) command = a break else: return None, args if command != 'shell' and command != 'paster': return command, args # shell requires the environment name, paster does not remaining_positional = 2 if command == 'shell' else 1 # i is where the subcommand starts. # shell, paster are special: options might belong to the command being # find where the the inner command starts and insert a '--' before # so that we can separate inner options from ones we need to parse while i < len(args): a = args[i] if a.startswith('-'): if a == '-s' or a == '--site': # site name is coming i += 2 continue i += 1 continue if remaining_positional: remaining_positional -= 1 i += 1 continue return command, args[:i] + ['--'] + args[i:] return command, args if __name__ == '__main__': main()
livioferrante/my-final-project
refs/heads/master
.mywaflib/waflib/extras/lru_cache.py
10
#! /usr/bin/env python # encoding: utf-8 # Thomas Nagy 2011 import os, shutil, re from waflib import Options, Build, Logs """ Apply a least recently used policy to the Waf cache. For performance reasons, it is called after the build is complete. We assume that the the folders are written atomically Do export WAFCACHE=/tmp/foo_xyz where xyz represents the cache size in bytes If missing, the default cache size will be set to 10GB """ re_num = re.compile('[a-zA-Z_-]+(\d+)') CACHESIZE = 10*1024*1024*1024 # in bytes CLEANRATIO = 0.8 DIRSIZE = 4096 def compile(self): if Options.cache_global and not Options.options.nocache: try: os.makedirs(Options.cache_global) except: pass try: self.raw_compile() finally: if Options.cache_global and not Options.options.nocache: self.sweep() def sweep(self): global CACHESIZE CACHEDIR = Options.cache_global # get the cache max size from the WAFCACHE filename re_num = re.compile('[a-zA-Z_]+(\d+)') val = re_num.sub('\\1', os.path.basename(Options.cache_global)) try: CACHESIZE = int(val) except: pass # map folder names to timestamps flist = {} for x in os.listdir(CACHEDIR): j = os.path.join(CACHEDIR, x) if os.path.isdir(j) and len(x) == 64: # dir names are md5 hexdigests flist[x] = [os.stat(j).st_mtime, 0] for (x, v) in flist.items(): cnt = DIRSIZE # each entry takes 4kB d = os.path.join(CACHEDIR, x) for k in os.listdir(d): cnt += os.stat(os.path.join(d, k)).st_size flist[x][1] = cnt total = sum([x[1] for x in flist.values()]) Logs.debug('lru: Cache size is %r' % total) if total >= CACHESIZE: Logs.debug('lru: Trimming the cache since %r > %r' % (total, CACHESIZE)) # make a list to sort the folders by timestamp lst = [(p, v[0], v[1]) for (p, v) in flist.items()] lst.sort(key=lambda x: x[1]) # sort by timestamp lst.reverse() while total >= CACHESIZE * CLEANRATIO: (k, t, s) = lst.pop() p = os.path.join(CACHEDIR, k) v = p + '.del' try: os.rename(p, v) except: # someone already did it pass else: try: shutil.rmtree(v) except: # this should not happen, but who knows? Logs.warn('If you ever see this message, report it (%r)' % v) total -= s del flist[k] Logs.debug('lru: Total at the end %r' % total) Build.BuildContext.raw_compile = Build.BuildContext.compile Build.BuildContext.compile = compile Build.BuildContext.sweep = sweep
gilbertw/PTVS
refs/heads/master
Python/Tests/TestData/VirtualEnv/env/Lib/encodings/iso8859_3.py
93
""" Python Character Mapping Codec iso8859_3 generated from 'MAPPINGS/ISO8859/8859-3.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='iso8859-3', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x04' # 0x04 -> END OF TRANSMISSION u'\x05' # 0x05 -> ENQUIRY u'\x06' # 0x06 -> ACKNOWLEDGE u'\x07' # 0x07 -> BELL u'\x08' # 0x08 -> BACKSPACE u'\t' # 0x09 -> HORIZONTAL TABULATION u'\n' # 0x0A -> LINE FEED u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x14' # 0x14 -> DEVICE CONTROL FOUR u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x16 -> SYNCHRONOUS IDLE u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x1a' # 0x1A -> SUBSTITUTE u'\x1b' # 0x1B -> ESCAPE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> DELETE u'\x80' # 0x80 -> <control> u'\x81' # 0x81 -> <control> u'\x82' # 0x82 -> <control> u'\x83' # 0x83 -> <control> u'\x84' # 0x84 -> <control> u'\x85' # 0x85 -> <control> u'\x86' # 0x86 -> <control> u'\x87' # 0x87 -> <control> u'\x88' # 0x88 -> <control> u'\x89' # 0x89 -> <control> u'\x8a' # 0x8A -> <control> u'\x8b' # 0x8B -> <control> u'\x8c' # 0x8C -> <control> u'\x8d' # 0x8D -> <control> u'\x8e' # 0x8E -> <control> u'\x8f' # 0x8F -> <control> u'\x90' # 0x90 -> <control> u'\x91' # 0x91 -> <control> u'\x92' # 0x92 -> <control> u'\x93' # 0x93 -> <control> u'\x94' # 0x94 -> <control> u'\x95' # 0x95 -> <control> u'\x96' # 0x96 -> <control> u'\x97' # 0x97 -> <control> u'\x98' # 0x98 -> <control> u'\x99' # 0x99 -> <control> u'\x9a' # 0x9A -> <control> u'\x9b' # 0x9B -> <control> u'\x9c' # 0x9C -> <control> u'\x9d' # 0x9D -> <control> u'\x9e' # 0x9E -> <control> u'\x9f' # 0x9F -> <control> u'\xa0' # 0xA0 -> NO-BREAK SPACE u'\u0126' # 0xA1 -> LATIN CAPITAL LETTER H WITH STROKE u'\u02d8' # 0xA2 -> BREVE u'\xa3' # 0xA3 -> POUND SIGN u'\xa4' # 0xA4 -> CURRENCY SIGN u'\ufffe' u'\u0124' # 0xA6 -> LATIN CAPITAL LETTER H WITH CIRCUMFLEX u'\xa7' # 0xA7 -> SECTION SIGN u'\xa8' # 0xA8 -> DIAERESIS u'\u0130' # 0xA9 -> LATIN CAPITAL LETTER I WITH DOT ABOVE u'\u015e' # 0xAA -> LATIN CAPITAL LETTER S WITH CEDILLA u'\u011e' # 0xAB -> LATIN CAPITAL LETTER G WITH BREVE u'\u0134' # 0xAC -> LATIN CAPITAL LETTER J WITH CIRCUMFLEX u'\xad' # 0xAD -> SOFT HYPHEN u'\ufffe' u'\u017b' # 0xAF -> LATIN CAPITAL LETTER Z WITH DOT ABOVE u'\xb0' # 0xB0 -> DEGREE SIGN u'\u0127' # 0xB1 -> LATIN SMALL LETTER H WITH STROKE u'\xb2' # 0xB2 -> SUPERSCRIPT TWO u'\xb3' # 0xB3 -> SUPERSCRIPT THREE u'\xb4' # 0xB4 -> ACUTE ACCENT u'\xb5' # 0xB5 -> MICRO SIGN u'\u0125' # 0xB6 -> LATIN SMALL LETTER H WITH CIRCUMFLEX u'\xb7' # 0xB7 -> MIDDLE DOT u'\xb8' # 0xB8 -> CEDILLA u'\u0131' # 0xB9 -> LATIN SMALL LETTER DOTLESS I u'\u015f' # 0xBA -> LATIN SMALL LETTER S WITH CEDILLA u'\u011f' # 0xBB -> LATIN SMALL LETTER G WITH BREVE u'\u0135' # 0xBC -> LATIN SMALL LETTER J WITH CIRCUMFLEX u'\xbd' # 0xBD -> VULGAR FRACTION ONE HALF u'\ufffe' u'\u017c' # 0xBF -> LATIN SMALL LETTER Z WITH DOT ABOVE u'\xc0' # 0xC0 -> LATIN CAPITAL LETTER A WITH GRAVE u'\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE u'\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX u'\ufffe' u'\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\u010a' # 0xC5 -> LATIN CAPITAL LETTER C WITH DOT ABOVE u'\u0108' # 0xC6 -> LATIN CAPITAL LETTER C WITH CIRCUMFLEX u'\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA u'\xc8' # 0xC8 -> LATIN CAPITAL LETTER E WITH GRAVE u'\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE u'\xca' # 0xCA -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX u'\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS u'\xcc' # 0xCC -> LATIN CAPITAL LETTER I WITH GRAVE u'\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE u'\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX u'\xcf' # 0xCF -> LATIN CAPITAL LETTER I WITH DIAERESIS u'\ufffe' u'\xd1' # 0xD1 -> LATIN CAPITAL LETTER N WITH TILDE u'\xd2' # 0xD2 -> LATIN CAPITAL LETTER O WITH GRAVE u'\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE u'\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX u'\u0120' # 0xD5 -> LATIN CAPITAL LETTER G WITH DOT ABOVE u'\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xd7' # 0xD7 -> MULTIPLICATION SIGN u'\u011c' # 0xD8 -> LATIN CAPITAL LETTER G WITH CIRCUMFLEX u'\xd9' # 0xD9 -> LATIN CAPITAL LETTER U WITH GRAVE u'\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE u'\xdb' # 0xDB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX u'\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\u016c' # 0xDD -> LATIN CAPITAL LETTER U WITH BREVE u'\u015c' # 0xDE -> LATIN CAPITAL LETTER S WITH CIRCUMFLEX u'\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S u'\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE u'\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE u'\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\ufffe' u'\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS u'\u010b' # 0xE5 -> LATIN SMALL LETTER C WITH DOT ABOVE u'\u0109' # 0xE6 -> LATIN SMALL LETTER C WITH CIRCUMFLEX u'\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA u'\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE u'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE u'\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX u'\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS u'\xec' # 0xEC -> LATIN SMALL LETTER I WITH GRAVE u'\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE u'\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS u'\ufffe' u'\xf1' # 0xF1 -> LATIN SMALL LETTER N WITH TILDE u'\xf2' # 0xF2 -> LATIN SMALL LETTER O WITH GRAVE u'\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE u'\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\u0121' # 0xF5 -> LATIN SMALL LETTER G WITH DOT ABOVE u'\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS u'\xf7' # 0xF7 -> DIVISION SIGN u'\u011d' # 0xF8 -> LATIN SMALL LETTER G WITH CIRCUMFLEX u'\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE u'\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE u'\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX u'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS u'\u016d' # 0xFD -> LATIN SMALL LETTER U WITH BREVE u'\u015d' # 0xFE -> LATIN SMALL LETTER S WITH CIRCUMFLEX u'\u02d9' # 0xFF -> DOT ABOVE ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
slightlynybbled/tk_tools
refs/heads/master
tests/test_SmartOptionMenu.py
1
import tkinter as tk import pytest from tk_tools import SmartOptionMenu from tests.test_basic import root @pytest.fixture def som(root): som_widget = SmartOptionMenu(root, ['1', '2', '3']) som_widget.grid() yield som_widget def test_creation(root): SmartOptionMenu(root, ['1', '2', '3']) def test_creation_with_initial_value(root): som = SmartOptionMenu(root, ['1', '2', '3'], initial_value='2') assert som.get() == '2' def test_callback_no_param(root): item_value = 0 def callback(): nonlocal item_value item_value += 1 som = SmartOptionMenu(root, ['1', '2', '3'], callback=callback) som.grid() som.set('1') som.set('3') som.set('2') assert item_value == 3 def test_callback_with_param(root): item_value = 0 def callback(value): nonlocal item_value item_value += int(value) som = SmartOptionMenu(root, ['1', '2', '3'], callback=callback) som.grid() som.set('2') som.set('2') som.set('2') assert item_value == 6 def test_add_callback_no_param(som): item_value = 0 def callback(): nonlocal item_value item_value += 1 som.add_callback(callback) som.set('1') som.set('3') som.set('2') assert item_value == 3 def test_add_callback_with_param(som): item_value = 0 def callback(value): nonlocal item_value item_value += int(value) som.add_callback(callback) som.set('2') som.set('2') som.set('2') assert item_value == 6
VitalPet/partner-contact
refs/heads/8.0
portal_partner_merge/__openerp__.py
15
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Vaucher # Copyright 2013 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Portal Partner Merge', 'version': '1.0', 'category': 'Hidden', 'description': """ Link module for base_partner_merge which extract portal dependency """, 'author': "Camptocamp,Odoo Community Association (OCA)", 'maintainer': 'Camptocamp', 'website': 'http://www.camptocamp.com/', 'depends': ['portal', 'base_partner_merge'], 'data': [], 'test': [], 'installable': True, 'auto_install': True, 'application': False, }
jalexvig/tensorflow
refs/heads/master
tensorflow/python/training/optimizer.py
3
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # ============================================================================== """Base class for optimizers.""" # pylint: disable=g-bad-name from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc from tensorflow.python.eager import backprop from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gradients from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.training import distribute as distribute_lib from tensorflow.python.training import slot_creator from tensorflow.python.training.checkpointable import base as checkpointable from tensorflow.python.util import nest from tensorflow.python.util.tf_export import tf_export def get_filtered_grad_fn(grad_fn): # `distributed_context.join()` requires that its arguments are parallel # across threads, and in particular that `grads_and_vars` has the same # variables in the same order. # When computing gradients in eager mode with multiple threads, you # can get extra variables with a gradient of `None`. This happens when # those variables are accessed in another thread during the gradient # computation. To get a consistent set of variables, we filter out # those with `None` gradients. def filtered_grad_fn(x=None): return [(g, v) for g, v in grad_fn(x) if g is not None] return filtered_grad_fn def _deduplicate_indexed_slices(values, indices): """Sums `values` associated with any non-unique `indices`. Args: values: A `Tensor` with rank >= 1. indices: A one-dimensional integer `Tensor`, indexing into the first dimension of `values` (as in an IndexedSlices object). Returns: A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a de-duplicated version of `indices` and `summed_values` contains the sum of `values` slices associated with each unique index. """ unique_indices, new_index_positions = array_ops.unique(indices) summed_values = math_ops.unsorted_segment_sum( values, new_index_positions, array_ops.shape(unique_indices)[0]) return (summed_values, unique_indices) def _var_key(var): # TODO(ashankar): Consolidate handling for eager and graph if hasattr(var, "op"): return (var.op.graph, var.op.name) return var._unique_id # pylint: disable=protected-access class _OptimizableVariable(object): """Interface for abstracting over variables in the optimizers.""" @abc.abstractmethod def target(self): """Returns the optimization target for this variable.""" raise NotImplementedError("Calling an abstract method.") @abc.abstractmethod def update_op(self, optimizer, g): """Returns the update ops for updating the variable.""" raise NotImplementedError("Calling an abstract method.") class _RefVariableProcessor(_OptimizableVariable): """Processor for Variable.""" def __init__(self, v): self._v = v def __str__(self): return "<_RefVariableProcessor(%s)>" % self._v def target(self): return self._v._ref() # pylint: disable=protected-access def update_op(self, optimizer, g): if isinstance(g, ops.Tensor): update_op = optimizer._apply_dense(g, self._v) # pylint: disable=protected-access if self._v.constraint is not None: with ops.control_dependencies([update_op]): return self._v.assign(self._v.constraint(self._v)) else: return update_op else: assert isinstance(g, ops.IndexedSlices), ("Gradient ", g, " is neither a " "tensor nor IndexedSlices.") if self._v.constraint is not None: raise RuntimeError( "Cannot use a constraint function on a sparse variable.") # pylint: disable=protected-access return optimizer._apply_sparse_duplicate_indices(g, self._v) class _DenseReadResourceVariableProcessor(_OptimizableVariable): """Processor for dense ResourceVariables.""" def __init__(self, v): self._v = v def target(self): return self._v def update_op(self, optimizer, g): # pylint: disable=protected-access update_op = optimizer._resource_apply_dense(g, self._v.op.inputs[0]) if self._v.constraint is not None: with ops.control_dependencies([update_op]): return self._v.assign(self._v.constraint(self._v)) else: return update_op class _DenseResourceVariableProcessor(_OptimizableVariable): """Processor for dense ResourceVariables.""" def __init__(self, v): self._v = v def target(self): return self._v def update_op(self, optimizer, g): # pylint: disable=protected-access if isinstance(g, ops.IndexedSlices): if self._v.constraint is not None: raise RuntimeError( "Cannot use a constraint function on a sparse variable.") return optimizer._resource_apply_sparse_duplicate_indices( g.values, self._v, g.indices) update_op = optimizer._resource_apply_dense(g, self._v) if self._v.constraint is not None: with ops.control_dependencies([update_op]): return self._v.assign(self._v.constraint(self._v)) else: return update_op class _TensorProcessor(_OptimizableVariable): """Processor for ordinary Tensors. Even though a Tensor can't really be updated, sometimes it is useful to compute the gradients with respect to a Tensor using the optimizer. Updating the Tensor is, of course, unsupported. """ def __init__(self, v): self._v = v def target(self): return self._v def update_op(self, optimizer, g): raise NotImplementedError("Trying to update a Tensor ", self._v) def _get_processor(v): """The processor of v.""" if context.executing_eagerly(): if isinstance(v, ops.Tensor): return _TensorProcessor(v) else: return _DenseResourceVariableProcessor(v) if isinstance( v, resource_variable_ops.ResourceVariable) and not v._in_graph_mode: # pylint: disable=protected-access # True if and only if `v` was initialized eagerly. return _DenseResourceVariableProcessor(v) if v.op.type == "VarHandleOp": return _DenseResourceVariableProcessor(v) if isinstance(v, variables.Variable): return _RefVariableProcessor(v) if isinstance(v, ops.Tensor): return _TensorProcessor(v) raise NotImplementedError("Trying to optimize unsupported type ", v) @tf_export("train.Optimizer") class Optimizer( # Optimizers inherit from CheckpointableBase rather than Checkpointable # since they do most of their dependency management themselves (slot # variables are special-cased, and non-slot variables are keyed to graphs). checkpointable.CheckpointableBase): """Base class for optimizers. This class defines the API to add Ops to train a model. You never use this class directly, but instead instantiate one of its subclasses such as `GradientDescentOptimizer`, `AdagradOptimizer`, or `MomentumOptimizer`. ### Usage ```python # Create an optimizer with the desired parameters. opt = GradientDescentOptimizer(learning_rate=0.1) # Add Ops to the graph to minimize a cost by updating a list of variables. # "cost" is a Tensor, and the list of variables contains tf.Variable # objects. opt_op = opt.minimize(cost, var_list=<list of variables>) ``` In the training program you will just have to run the returned Op. ```python # Execute opt_op to do one step of training: opt_op.run() ``` ### Processing gradients before applying them. Calling `minimize()` takes care of both computing the gradients and applying them to the variables. If you want to process the gradients before applying them you can instead use the optimizer in three steps: 1. Compute the gradients with `compute_gradients()`. 2. Process the gradients as you wish. 3. Apply the processed gradients with `apply_gradients()`. Example: ```python # Create an optimizer. opt = GradientDescentOptimizer(learning_rate=0.1) # Compute the gradients for a list of variables. grads_and_vars = opt.compute_gradients(loss, <list of variables>) # grads_and_vars is a list of tuples (gradient, variable). Do whatever you # need to the 'gradient' part, for example cap them, etc. capped_grads_and_vars = [(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars] # Ask the optimizer to apply the capped gradients. opt.apply_gradients(capped_grads_and_vars) ``` ### Gating Gradients Both `minimize()` and `compute_gradients()` accept a `gate_gradients` argument that controls the degree of parallelism during the application of the gradients. The possible values are: `GATE_NONE`, `GATE_OP`, and `GATE_GRAPH`. <b>`GATE_NONE`</b>: Compute and apply gradients in parallel. This provides the maximum parallelism in execution, at the cost of some non-reproducibility in the results. For example the two gradients of `matmul` depend on the input values: With `GATE_NONE` one of the gradients could be applied to one of the inputs _before_ the other gradient is computed resulting in non-reproducible results. <b>`GATE_OP`</b>: For each Op, make sure all gradients are computed before they are used. This prevents race conditions for Ops that generate gradients for multiple inputs where the gradients depend on the inputs. <b>`GATE_GRAPH`</b>: Make sure all gradients for all variables are computed before any one of them is used. This provides the least parallelism but can be useful if you want to process all gradients before applying any of them. ### Slots Some optimizer subclasses, such as `MomentumOptimizer` and `AdagradOptimizer` allocate and manage additional variables associated with the variables to train. These are called <i>Slots</i>. Slots have names and you can ask the optimizer for the names of the slots that it uses. Once you have a slot name you can ask the optimizer for the variable it created to hold the slot value. This can be useful if you want to log debug a training algorithm, report stats about the slots, etc. """ # Values for gate_gradients. GATE_NONE = 0 GATE_OP = 1 GATE_GRAPH = 2 def __init__(self, use_locking, name): """Create a new Optimizer. This must be called by the constructors of subclasses. Args: use_locking: Bool. If True apply use locks to prevent concurrent updates to variables. name: A non-empty string. The name to use for accumulators created for the optimizer. Raises: ValueError: If name is malformed. """ if not name: raise ValueError("Must specify the optimizer name") self._use_locking = use_locking self._name = name # Dictionary of slots. # {slot_name : # {_var_key(variable_to_train): slot_for_the_variable, ... }, # ... } self._slots = {} self._non_slot_dict = {} # For implementing Checkpointable. Stores information about how to restore # slot variables which have not yet been created # (checkpointable._CheckpointPosition objects). # {slot_name : # {_var_key(variable_to_train): [checkpoint_position, ... ], ... }, # ... } self._deferred_slot_restorations = {} # TODO(isaprykin): When using a DistributionStrategy, and when an # optimizer is created in each tower, it might be dangerous to # rely on some Optimer methods. When such methods are called on a # per-tower optimizer, an exception needs to be thrown. We do # allow creation per-tower optimizers however, because the # compute_gradients()->apply_gradients() sequence is safe. def get_name(self): return self._name def minimize(self, loss, global_step=None, var_list=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Add operations to minimize `loss` by updating `var_list`. This method simply combines calls `compute_gradients()` and `apply_gradients()`. If you want to process the gradient before applying them call `compute_gradients()` and `apply_gradients()` explicitly instead of using this function. Args: loss: A `Tensor` containing the value to minimize. global_step: Optional `Variable` to increment by one after the variables have been updated. var_list: Optional list or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class `AggregationMethod`. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. name: Optional name for the returned operation. grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`. Returns: An Operation that updates the variables in `var_list`. If `global_step` was not `None`, that operation also increments `global_step`. Raises: ValueError: If some of the variables are not `Variable` objects. @compatibility(eager) When eager execution is enabled, `loss` should be a Python function that takes elements of `var_list` as arguments and computes the value to be minimized. If `var_list` is None, `loss` should take no arguments. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled. @end_compatibility """ grads_and_vars = self.compute_gradients( loss, var_list=var_list, gate_gradients=gate_gradients, aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops, grad_loss=grad_loss) vars_with_grad = [v for g, v in grads_and_vars if g is not None] if not vars_with_grad: raise ValueError( "No gradients provided for any variable, check your graph for ops" " that do not support gradients, between variables %s and loss %s." % ([str(v) for _, v in grads_and_vars], loss)) return self.apply_gradients(grads_and_vars, global_step=global_step, name=name) def compute_gradients(self, loss, var_list=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, grad_loss=None): """Compute gradients of `loss` for the variables in `var_list`. This is the first part of `minimize()`. It returns a list of (gradient, variable) pairs where "gradient" is the gradient for "variable". Note that "gradient" can be a `Tensor`, an `IndexedSlices`, or `None` if there is no gradient for the given variable. Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var_list: Optional list or tuple of `tf.Variable` to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`. aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class `AggregationMethod`. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`. Returns: A list of (gradient, variable) pairs. Variable is always present, but gradient can be `None`. Raises: TypeError: If `var_list` contains anything else than `Variable` objects. ValueError: If some arguments are invalid. RuntimeError: If called with eager execution enabled and `loss` is not callable. @compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored. @end_compatibility """ if callable(loss): with backprop.GradientTape() as tape: if var_list is not None: tape.watch(var_list) loss_value = loss() # Scale loss if using a "mean" loss reduction and multiple towers. # Have to be careful to call distribute_lib.get_loss_reduction() # *after* loss() is evaluated, so we know what loss reduction it uses. # TODO(josh11b): Test that we handle weight decay in a reasonable way. if (distribute_lib.get_loss_reduction() == variable_scope.VariableAggregation.MEAN): num_towers = distribute_lib.get_distribution_strategy().num_towers if num_towers > 1: loss_value *= (1. / num_towers) if var_list is None: var_list = tape.watched_variables() grads = tape.gradient(loss_value, var_list, grad_loss) return list(zip(grads, var_list)) # Non-callable/Tensor loss case if context.executing_eagerly(): raise RuntimeError( "`loss` passed to Optimizer.compute_gradients should " "be a function when eager execution is enabled.") # Scale loss if using a "mean" loss reduction and multiple towers. if (distribute_lib.get_loss_reduction() == variable_scope.VariableAggregation.MEAN): num_towers = distribute_lib.get_distribution_strategy().num_towers if num_towers > 1: loss *= (1. / num_towers) if gate_gradients not in [Optimizer.GATE_NONE, Optimizer.GATE_OP, Optimizer.GATE_GRAPH]: raise ValueError("gate_gradients must be one of: Optimizer.GATE_NONE, " "Optimizer.GATE_OP, Optimizer.GATE_GRAPH. Not %s" % gate_gradients) self._assert_valid_dtypes([loss]) if grad_loss is not None: self._assert_valid_dtypes([grad_loss]) if var_list is None: var_list = ( variables.trainable_variables() + ops.get_collection(ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES)) else: var_list = nest.flatten(var_list) # pylint: disable=protected-access var_list += ops.get_collection(ops.GraphKeys._STREAMING_MODEL_PORTS) # pylint: enable=protected-access processors = [_get_processor(v) for v in var_list] if not var_list: raise ValueError("No variables to optimize.") var_refs = [p.target() for p in processors] grads = gradients.gradients( loss, var_refs, grad_ys=grad_loss, gate_gradients=(gate_gradients == Optimizer.GATE_OP), aggregation_method=aggregation_method, colocate_gradients_with_ops=colocate_gradients_with_ops) if gate_gradients == Optimizer.GATE_GRAPH: grads = control_flow_ops.tuple(grads) grads_and_vars = list(zip(grads, var_list)) self._assert_valid_dtypes( [v for g, v in grads_and_vars if g is not None and v.dtype != dtypes.resource]) return grads_and_vars def apply_gradients(self, grads_and_vars, global_step=None, name=None): """Apply gradients to variables. This is the second part of `minimize()`. It returns an `Operation` that applies gradients. Args: grads_and_vars: List of (gradient, variable) pairs as returned by `compute_gradients()`. global_step: Optional `Variable` to increment by one after the variables have been updated. name: Optional name for the returned operation. Default to the name passed to the `Optimizer` constructor. Returns: An `Operation` that applies the specified gradients. If `global_step` was not None, that operation also increments `global_step`. Raises: TypeError: If `grads_and_vars` is malformed. ValueError: If none of the variables have gradients. RuntimeError: If you should use `_distributed_apply()` instead. """ # This is a default implementation of apply_gradients() that can be shared # by most optimizers. It relies on the subclass implementing the following # methods: _create_slots(), _prepare(), _apply_dense(), and _apply_sparse(). # Handle DistributionStrategy case. if distribute_lib.get_cross_tower_context(): raise RuntimeError("Use `_distributed_apply()` instead of " "`apply_gradients()` in a cross-tower context.") # TODO(isaprykin): Get rid of `has_distribution_strategy()` check by # always calling _distributed_apply(), using the default distribution # as needed. if distribute_lib.has_distribution_strategy(): grads_and_vars = get_filtered_grad_fn(lambda _: grads_and_vars)() return distribute_lib.get_tower_context().merge_call( self._distributed_apply, grads_and_vars, global_step, name) # No DistributionStrategy case. grads_and_vars = tuple(grads_and_vars) # Make sure repeat iteration works. if not grads_and_vars: raise ValueError("No variables provided.") converted_grads_and_vars = [] for g, v in grads_and_vars: if g is not None: try: # Convert the grad to Tensor or IndexedSlices if necessary. g = ops.convert_to_tensor_or_indexed_slices(g) except TypeError: raise TypeError( "Gradient must be convertible to a Tensor" " or IndexedSlices, or None: %s" % g) if not isinstance(g, (ops.Tensor, ops.IndexedSlices)): raise TypeError( "Gradient must be a Tensor, IndexedSlices, or None: %s" % g) p = _get_processor(v) converted_grads_and_vars.append((g, v, p)) converted_grads_and_vars = tuple(converted_grads_and_vars) var_list = [v for g, v, _ in converted_grads_and_vars if g is not None] if not var_list: raise ValueError("No gradients provided for any variable: %s." % ([str(v) for _, _, v in converted_grads_and_vars],)) with ops.init_scope(): self._create_slots(var_list) update_ops = [] with ops.name_scope(name, self._name) as name: self._prepare() for grad, var, processor in converted_grads_and_vars: if grad is None: continue # We colocate all ops created in _apply_dense or _apply_sparse # on the same device as the variable. # TODO(apassos): figure out how to get the variable name here. if context.executing_eagerly() or isinstance( var, resource_variable_ops.ResourceVariable) and not var._in_graph_mode: # pylint: disable=protected-access scope_name = "" else: scope_name = var.op.name with ops.name_scope("update_" + scope_name), ops.colocate_with(var): update_ops.append(processor.update_op(self, grad)) if global_step is None: apply_updates = self._finish(update_ops, name) else: with ops.control_dependencies([self._finish(update_ops, "update")]): with ops.colocate_with(global_step): if isinstance(global_step, resource_variable_ops.ResourceVariable): # TODO(apassos): the implicit read in assign_add is slow; consider # making it less so. apply_updates = resource_variable_ops.assign_add_variable_op( global_step.handle, ops.convert_to_tensor(1, dtype=global_step.dtype), name=name) else: apply_updates = state_ops.assign_add(global_step, 1, name=name) if not context.executing_eagerly(): if isinstance(apply_updates, ops.Tensor): apply_updates = apply_updates.op train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP) if apply_updates not in train_op: train_op.append(apply_updates) return apply_updates def _distributed_apply(self, distribution, grads_and_vars, global_step=None, name=None): """A version of `apply_gradients` for cross-tower context. This is a version of `apply_gradients()` for when you are using a `DistributionStrategy` and are in a cross-tower context. If in a tower context, use `apply_gradients()` as normal. Args: distribution: A `DistributionStrategy` object. grads_and_vars: List of (gradient, variable) pairs as returned by `compute_gradients()`, and then aggregated across towers. global_step: Optional (mirrored) `Variable` to increment by one after the variables have been updated. name: Optional name for the returned operation. Default to the name passed to the `Optimizer` constructor. Returns: An `Operation` that applies the specified gradients across all towers. If `global_step` was not None, that operation also increments `global_step`. """ reduced_grads = distribution.batch_reduce( variable_scope.VariableAggregation.SUM, grads_and_vars) var_list = [v for _, v in grads_and_vars] grads_and_vars = zip(reduced_grads, var_list) # Note that this is called in a cross-tower context. self._create_slots(var_list) def update(v, g): """Apply gradients to a replica variable.""" assert v is not None try: # Convert the grad to Tensor or IndexedSlices if necessary. g = ops.convert_to_tensor_or_indexed_slices(g) except TypeError: raise TypeError("Gradient must be convertible to a Tensor" " or IndexedSlices, or None: %s" % g) if not isinstance(g, (ops.Tensor, ops.IndexedSlices)): raise TypeError( "Gradient must be a Tensor, IndexedSlices, or None: %s" % g) p = _get_processor(v) scope_name = "" if context.executing_eagerly() else v.op.name # device_policy is set because non-mirrored tensors will be read in # `update_op`. `_resource_apply_dense`, `lr_t`, `beta1_t` and `beta2_t` # is an example. with ops.name_scope("update_" + scope_name): return p.update_op(self, g) with ops.name_scope(name, self._name) as name: self._prepare() update_ops = [ op for grad, var in grads_and_vars for op in distribution.unwrap(distribution.update(var, update, grad)) ] def finish(self, update_ops): return self._finish(update_ops, "update") non_slot_devices = distribution.non_slot_devices(var_list) finish_updates = distribution.update_non_slot( non_slot_devices, finish, self, update_ops) if global_step is None: apply_updates = distribution.group(finish_updates, name=name) else: with ops.control_dependencies(distribution.unwrap(finish_updates)): apply_updates = distribution.group(distribution.update( global_step, state_ops.assign_add, 1, name=name)) if not context.executing_eagerly(): if isinstance(apply_updates, ops.Tensor): apply_updates = apply_updates.op train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP) if apply_updates not in train_op: train_op.append(apply_updates) return apply_updates def get_slot(self, var, name): """Return a slot named `name` created for `var` by the Optimizer. Some `Optimizer` subclasses use additional variables. For example `Momentum` and `Adagrad` use variables to accumulate updates. This method gives access to these `Variable` objects if for some reason you need them. Use `get_slot_names()` to get the list of slot names created by the `Optimizer`. Args: var: A variable passed to `minimize()` or `apply_gradients()`. name: A string. Returns: The `Variable` for the slot if it was created, `None` otherwise. """ # pylint: disable=protected-access named_slots = self._slots.get(name, None) if not named_slots: return None if hasattr(var, "_distributed_container"): # NOTE: If this isn't patched, then there is no `handle` in # `_resource_apply_dense`. distributed_container = var._distributed_container() assert distributed_container is not None if context.executing_eagerly(): key = distributed_container._unique_id else: key = (distributed_container.graph, distributed_container._shared_name) # pylint: enable=protected-access mirrored_slot = named_slots.get(key, None) if mirrored_slot is None: return None return mirrored_slot.get(device=var.device) return named_slots.get(_var_key(var), None) def get_slot_names(self): """Return a list of the names of slots created by the `Optimizer`. See `get_slot()`. Returns: A list of strings. """ return sorted(self._slots.keys()) def variables(self): """A list of variables which encode the current state of `Optimizer`. Includes slot variables and additional global variables created by the optimizer in the current default graph. Returns: A list of variables. """ executing_eagerly = context.executing_eagerly() current_graph = ops.get_default_graph() def _from_current_graph(variable): if executing_eagerly: # No variable.op in eager mode. We don't expect lots of eager graphs, # but behavior should be consistent with graph mode. return variable._graph_key == current_graph._graph_key # pylint: disable=protected-access else: return variable.op.graph is current_graph optimizer_variables = [v for v in self._non_slot_variables() if _from_current_graph(v)] for _, variable_dict in self._slots.items(): for _, slot_for_variable in variable_dict.items(): if _from_current_graph(slot_for_variable): optimizer_variables.append(slot_for_variable) # Sort variables by name so that the return is deterministic. return sorted(optimizer_variables, key=lambda v: v.name) def _create_non_slot_variable(self, initial_value, name, colocate_with): """Add an extra variable, not associated with a slot.""" # Recommendation: Use OptimizerV2 if your optimizer uses non-slot variables. eager = context.executing_eagerly() graph = None if eager else colocate_with.graph key = (name, graph) v = self._non_slot_dict.get(key, None) if v is None: self._maybe_initialize_checkpointable() distribution_strategy = distribute_lib.get_distribution_strategy() with distribution_strategy.colocate_vars_with(colocate_with): if eager: restored_initial_value = self._preload_simple_restoration( name=name, shape=None) if restored_initial_value is not None: initial_value = restored_initial_value v = variable_scope.variable(initial_value, name=name, trainable=False) # Restore this variable by name if necessary, but don't add a # Checkpointable dependency. Optimizers return the current graph's # non-slot variables from _checkpoint_dependencies explicitly rather # than unconditionally adding dependencies (since there may be multiple # non-slot variables with the same name in different graphs, trying to # save all of them would result in errors). self._handle_deferred_dependencies(name=name, checkpointable=v) self._non_slot_dict[key] = v return v @property def _checkpoint_dependencies(self): """From Checkpointable. Gather graph-specific non-slot variables to save.""" current_graph_non_slot_variables = [] current_graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access for (name, _), variable_object in sorted(self._non_slot_dict.items(), # Avoid comparing graphs key=lambda item: item[0][0]): if variable_object._graph_key == current_graph_key: # pylint: disable=protected-access current_graph_non_slot_variables.append( checkpointable.CheckpointableReference( name=name, ref=variable_object)) return (super(Optimizer, self)._checkpoint_dependencies + current_graph_non_slot_variables) def _lookup_dependency(self, name): """From Checkpointable. Find a non-slot variable in the current graph.""" unconditional = super(Optimizer, self)._lookup_dependency(name) if unconditional is not None: return unconditional graph = None if context.executing_eagerly() else ops.get_default_graph() return self._get_non_slot_variable(name, graph=graph) def _get_non_slot_variable(self, name, graph=None): non_slot = self._non_slot_dict.get((name, graph), None) if hasattr(non_slot, "_distributed_container"): # This is a mirrored non-slot. In order to enable code like `_finish` # to assign to a non-slot, return the current context replica. return non_slot.get() else: return non_slot def _non_slot_variables(self): """Additional variables created by the `Optimizer`. Returns: A list or tuple of variables. """ return self._non_slot_dict.values() def _assert_valid_dtypes(self, tensors): """Asserts tensors are all valid types (see `_valid_dtypes`). Args: tensors: Tensors to check. Raises: ValueError: If any tensor is not a valid type. """ valid_dtypes = self._valid_dtypes() for t in tensors: dtype = t.dtype.base_dtype if dtype not in valid_dtypes: raise ValueError( "Invalid type %r for %s, expected: %s." % ( dtype, t.name, [v for v in valid_dtypes])) # -------------- # Methods to be implemented by subclasses if they want to use the # inherited implementation of apply_gradients() or compute_gradients(). # -------------- def _valid_dtypes(self): """Valid types for loss, variables and gradients. Subclasses should override to allow other float types. Returns: Valid types for loss, variables and gradients. """ return set( [dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64]) def _create_slots(self, var_list): """Create all slots needed by the variables. Args: var_list: A list of `Variable` objects. """ # No slots needed by default pass def _prepare(self): """Create all needed tensors before applying gradients. This is called with the name_scope using the "name" that users have chosen for the application of gradients. """ pass def _apply_dense(self, grad, var): """Add ops to apply dense gradients to `var`. Args: grad: A `Tensor`. var: A `Variable` object. Returns: An `Operation`. """ raise NotImplementedError() def _resource_apply_dense(self, grad, handle): """Add ops to apply dense gradients to the variable `handle`. Args: grad: a `Tensor` representing the gradient. handle: a `Tensor` of dtype `resource` which points to the variable to be updated. Returns: An `Operation` which updates the value of the variable. """ raise NotImplementedError() def _resource_apply_sparse_duplicate_indices(self, grad, handle, indices): """Add ops to apply sparse gradients to `handle`, with repeated indices. Optimizers which override this method must deal with repeated indices. See the docstring of `_apply_sparse_duplicate_indices` for details. By default the correct behavior, to sum non-unique indices and their associated gradients, is enforced by first pre-processing `grad` and `indices` and passing them on to `_resource_apply_sparse`. Optimizers which deal correctly with duplicate indices may instead override this method to avoid the overhead of summing. Args: grad: a `Tensor` representing the gradient for the affected indices. handle: a `Tensor` of dtype `resource` which points to the variable to be updated. indices: a `Tensor` of integral type representing the indices for which the gradient is nonzero. Indices may be repeated. Returns: An `Operation` which updates the value of the variable. """ summed_grad, unique_indices = _deduplicate_indexed_slices( values=grad, indices=indices) return self._resource_apply_sparse(summed_grad, handle, unique_indices) def _resource_apply_sparse(self, grad, handle, indices): """Add ops to apply sparse gradients to the variable `handle`. Similar to `_apply_sparse`, the `indices` argument to this method has been de-duplicated. Optimizers which deal correctly with non-unique indices may instead override `_resource_apply_sparse_duplicate_indices` to avoid this overhead. Args: grad: a `Tensor` representing the gradient for the affected indices. handle: a `Tensor` of dtype `resource` which points to the variable to be updated. indices: a `Tensor` of integral type representing the indices for which the gradient is nonzero. Indices are unique. Returns: An `Operation` which updates the value of the variable. """ raise NotImplementedError() def _apply_sparse_duplicate_indices(self, grad, var): """Add ops to apply sparse gradients to `var`, with repeated sparse indices. Optimizers which override this method must deal with IndexedSlices objects such as the following: IndexedSlicesValue(values=[1, 1], indices=[0, 0], dense_shape=[1]) The correct interpretation is: IndexedSlicesValue(values=[2], indices=[0], dense_shape=[1]) Many optimizers deal incorrectly with repeated indices when updating based on sparse gradients (e.g. summing squares rather than squaring the sum, or applying momentum terms multiple times). Adding first is always the correct behavior, so this is enforced here by reconstructing the IndexedSlices to have only unique indices, then calling _apply_sparse. Optimizers which deal correctly with repeated indices may instead override this method to avoid the overhead of summing indices. Args: grad: `IndexedSlices`. var: A `Variable` object. Returns: An `Operation`. """ summed_values, unique_indices = _deduplicate_indexed_slices( values=grad.values, indices=grad.indices) gradient_no_duplicate_indices = ops.IndexedSlices( indices=unique_indices, values=summed_values, dense_shape=grad.dense_shape) return self._apply_sparse(gradient_no_duplicate_indices, var) def _apply_sparse(self, grad, var): """Add ops to apply sparse gradients to `var`. The IndexedSlices object passed to `grad` in this function is by default pre-processed in `_apply_sparse_duplicate_indices` to remove duplicate indices (see its docstring for details). Optimizers which can tolerate or have correct special cases for duplicate sparse indices may override `_apply_sparse_duplicate_indices` instead of this function, avoiding that overhead. Args: grad: `IndexedSlices`, with no repeated indices. var: A `Variable` object. Returns: An `Operation`. """ raise NotImplementedError() def _finish(self, update_ops, name_scope): """Do what is needed to finish the update. This is called with the `name_scope` using the "name" that users have chosen for the application of gradients. Args: update_ops: List of `Operation` objects to update variables. This list contains the values returned by the `_apply_dense()` and `_apply_sparse()` calls. name_scope: String. Name to use for the returned operation. Returns: The operation to apply updates. """ return control_flow_ops.group(*update_ops, name=name_scope) # -------------- # Utility methods for subclasses. # -------------- def _slot_dict(self, slot_name): """Returns a dict for caching slots created under the given name. Args: slot_name: Name for the slot. Returns: A dict that maps primary `Variable` objects to the slot created for that variable, under the given slot name. """ named_slots = self._slots.get(slot_name, None) if named_slots is None: named_slots = {} self._slots[slot_name] = named_slots return named_slots def _get_or_make_slot(self, var, val, slot_name, op_name): """Find or create a slot for a variable. Args: var: A `Variable` object. val: A `Tensor`. The initial value of the slot. slot_name: Name for the slot. op_name: Name to use when scoping the Variable that needs to be created for the slot. Returns: A `Variable` object. """ named_slots = self._slot_dict(slot_name) if _var_key(var) not in named_slots: new_slot_variable = slot_creator.create_slot(var, val, op_name) self._restore_slot_variable( slot_name=slot_name, variable=var, slot_variable=new_slot_variable) named_slots[_var_key(var)] = new_slot_variable return named_slots[_var_key(var)] def _get_or_make_slot_with_initializer(self, var, initializer, shape, dtype, slot_name, op_name): """Find or create a slot for a variable, using an Initializer. Args: var: A `Variable` object. initializer: An `Initializer`. The initial value of the slot. shape: Shape of the initial value of the slot. dtype: Type of the value of the slot. slot_name: Name for the slot. op_name: Name to use when scoping the Variable that needs to be created for the slot. Returns: A `Variable` object. """ named_slots = self._slot_dict(slot_name) if _var_key(var) not in named_slots: new_slot_variable = slot_creator.create_slot_with_initializer( var, initializer, shape, dtype, op_name) self._restore_slot_variable( slot_name=slot_name, variable=var, slot_variable=new_slot_variable) named_slots[_var_key(var)] = new_slot_variable return named_slots[_var_key(var)] def _zeros_slot(self, var, slot_name, op_name): """Find or create a slot initialized with 0.0. Args: var: A `Variable` object. slot_name: Name for the slot. op_name: Name to use when scoping the Variable that needs to be created for the slot. Returns: A `Variable` object. """ named_slots = self._slot_dict(slot_name) if _var_key(var) not in named_slots: new_slot_variable = slot_creator.create_zeros_slot(var, op_name) self._restore_slot_variable( slot_name=slot_name, variable=var, slot_variable=new_slot_variable) named_slots[_var_key(var)] = new_slot_variable return named_slots[_var_key(var)] # -------------- # For implementing the Checkpointable interface. # -------------- def _restore_slot_variable(self, slot_name, variable, slot_variable): """Restore a newly created slot variable's value.""" variable_key = _var_key(variable) deferred_restorations = self._deferred_slot_restorations.get( slot_name, {}).pop(variable_key, []) # Iterate over restores, highest restore UID first to minimize the number # of assignments. deferred_restorations.sort(key=lambda position: position.restore_uid, reverse=True) for checkpoint_position in deferred_restorations: checkpoint_position.restore(slot_variable) def _create_or_restore_slot_variable( self, slot_variable_position, slot_name, variable): """Restore a slot variable's value, possibly creating it. Called when a variable which has an associated slot variable is created or restored. When executing eagerly, we create the slot variable with a restoring initializer. No new variables are created when graph building. Instead, _restore_slot_variable catches these after normal creation and adds restore ops to the graph. This method is nonetheless important when graph building for the case when a slot variable has already been created but `variable` has just been added to a dependency graph (causing us to realize that the slot variable needs to be restored). Args: slot_variable_position: A `checkpointable._CheckpointPosition` object indicating the slot variable `Checkpointable` object to be restored. slot_name: The name of this `Optimizer`'s slot to restore into. variable: The variable object this slot is being created for. """ named_slots = self._slot_dict(slot_name) variable_key = _var_key(variable) slot_variable = named_slots.get(variable_key, None) if (slot_variable is None and context.executing_eagerly() and slot_variable_position.is_simple_variable() # Defer slot variable creation if there is an active variable creator # scope. Generally we'd like to eagerly create/restore slot variables # when possible, but this may mean that scopes intended to catch # `variable` also catch its eagerly created slot variable # unintentionally (specifically make_template would add a dependency on # a slot variable if not for this case). Deferring is mostly harmless # (aside from double initialization), and makes variable creator scopes # behave the same way they do when graph building. and not ops.get_default_graph()._variable_creator_stack): # pylint: disable=protected-access initializer = checkpointable.CheckpointInitialValue( checkpoint_position=slot_variable_position) slot_variable = self._get_or_make_slot( var=variable, val=initializer, slot_name=slot_name, op_name=self._name) # Slot variables are not owned by any one object (because we don't want to # save the slot variable if the optimizer is saved without the non-slot # variable, or if the non-slot variable is saved without the optimizer; # it's a dependency hypergraph with edges of the form (optimizer, non-slot # variable, variable)). So we don't _track_ slot variables anywhere, and # instead special-case this dependency and otherwise pretend it's a normal # graph. if slot_variable is not None: # If we've either made this slot variable, or if we've pulled out an # existing slot variable, we should restore it. slot_variable_position.restore(slot_variable) else: # We didn't make the slot variable. Defer restoring until it gets created # normally. We keep a list rather than the one with the highest restore # UID in case slot variables have their own dependencies, in which case # those could differ between restores. self._deferred_slot_restorations.setdefault( slot_name, {}).setdefault(variable_key, []).append( slot_variable_position) def _call_if_callable(self, param): """Call the function if param is callable.""" return param() if callable(param) else param
ritzk/ansible-modules-extras
refs/heads/devel
cloud/vmware/vmware_vm_facts.py
75
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Joseph Callen <jcallen () csc.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: vmware_vm_facts short_description: Return basic facts pertaining to a vSphere virtual machine guest description: - Return basic facts pertaining to a vSphere virtual machine guest version_added: 2.0 author: "Joseph Callen (@jcpowermac)" notes: - Tested on vSphere 5.5 requirements: - "python >= 2.6" - PyVmomi extends_documentation_fragment: vmware.documentation ''' EXAMPLES = ''' - name: Gather all registered virtual machines local_action: module: vmware_vm_facts hostname: esxi_or_vcenter_ip_or_hostname username: username password: password ''' try: from pyVmomi import vim, vmodl HAS_PYVMOMI = True except ImportError: HAS_PYVMOMI = False # https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/getallvms.py def get_all_virtual_machines(content): virtual_machines = get_all_objs(content, [vim.VirtualMachine]) _virtual_machines = {} for vm in virtual_machines: _ip_address = "" summary = vm.summary if summary.guest is not None: _ip_address = summary.guest.ipAddress if _ip_address is None: _ip_address = "" virtual_machine = { summary.config.name: { "guest_fullname": summary.config.guestFullName, "power_state": summary.runtime.powerState, "ip_address": _ip_address } } _virtual_machines.update(virtual_machine) return _virtual_machines def main(): argument_spec = vmware_argument_spec() module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') try: content = connect_to_api(module) _virtual_machines = get_all_virtual_machines(content) module.exit_json(changed=False, virtual_machines=_virtual_machines) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e)) from ansible.module_utils.vmware import * from ansible.module_utils.basic import * if __name__ == '__main__': main()
dev-harsh1998/Phantom-Jalebi
refs/heads/PhantoM-N
tools/perf/tests/attr.py
3174
#! /usr/bin/python import os import sys import glob import optparse import tempfile import logging import shutil import ConfigParser class Fail(Exception): def __init__(self, test, msg): self.msg = msg self.test = test def getMsg(self): return '\'%s\' - %s' % (self.test.path, self.msg) class Unsup(Exception): def __init__(self, test): self.test = test def getMsg(self): return '\'%s\'' % self.test.path class Event(dict): terms = [ 'cpu', 'flags', 'type', 'size', 'config', 'sample_period', 'sample_type', 'read_format', 'disabled', 'inherit', 'pinned', 'exclusive', 'exclude_user', 'exclude_kernel', 'exclude_hv', 'exclude_idle', 'mmap', 'comm', 'freq', 'inherit_stat', 'enable_on_exec', 'task', 'watermark', 'precise_ip', 'mmap_data', 'sample_id_all', 'exclude_host', 'exclude_guest', 'exclude_callchain_kernel', 'exclude_callchain_user', 'wakeup_events', 'bp_type', 'config1', 'config2', 'branch_sample_type', 'sample_regs_user', 'sample_stack_user', ] def add(self, data): for key, val in data: log.debug(" %s = %s" % (key, val)) self[key] = val def __init__(self, name, data, base): log.debug(" Event %s" % name); self.name = name; self.group = '' self.add(base) self.add(data) def compare_data(self, a, b): # Allow multiple values in assignment separated by '|' a_list = a.split('|') b_list = b.split('|') for a_item in a_list: for b_item in b_list: if (a_item == b_item): return True elif (a_item == '*') or (b_item == '*'): return True return False def equal(self, other): for t in Event.terms: log.debug(" [%s] %s %s" % (t, self[t], other[t])); if not self.has_key(t) or not other.has_key(t): return False if not self.compare_data(self[t], other[t]): return False return True def diff(self, other): for t in Event.terms: if not self.has_key(t) or not other.has_key(t): continue if not self.compare_data(self[t], other[t]): log.warning("expected %s=%s, got %s" % (t, self[t], other[t])) # Test file description needs to have following sections: # [config] # - just single instance in file # - needs to specify: # 'command' - perf command name # 'args' - special command arguments # 'ret' - expected command return value (0 by default) # # [eventX:base] # - one or multiple instances in file # - expected values assignments class Test(object): def __init__(self, path, options): parser = ConfigParser.SafeConfigParser() parser.read(path) log.warning("running '%s'" % path) self.path = path self.test_dir = options.test_dir self.perf = options.perf self.command = parser.get('config', 'command') self.args = parser.get('config', 'args') try: self.ret = parser.get('config', 'ret') except: self.ret = 0 self.expect = {} self.result = {} log.debug(" loading expected events"); self.load_events(path, self.expect) def is_event(self, name): if name.find("event") == -1: return False else: return True def load_events(self, path, events): parser_event = ConfigParser.SafeConfigParser() parser_event.read(path) # The event record section header contains 'event' word, # optionaly followed by ':' allowing to load 'parent # event' first as a base for section in filter(self.is_event, parser_event.sections()): parser_items = parser_event.items(section); base_items = {} # Read parent event if there's any if (':' in section): base = section[section.index(':') + 1:] parser_base = ConfigParser.SafeConfigParser() parser_base.read(self.test_dir + '/' + base) base_items = parser_base.items('event') e = Event(section, parser_items, base_items) events[section] = e def run_cmd(self, tempdir): cmd = "PERF_TEST_ATTR=%s %s %s -o %s/perf.data %s" % (tempdir, self.perf, self.command, tempdir, self.args) ret = os.WEXITSTATUS(os.system(cmd)) log.info(" '%s' ret %d " % (cmd, ret)) if ret != int(self.ret): raise Unsup(self) def compare(self, expect, result): match = {} log.debug(" compare"); # For each expected event find all matching # events in result. Fail if there's not any. for exp_name, exp_event in expect.items(): exp_list = [] log.debug(" matching [%s]" % exp_name) for res_name, res_event in result.items(): log.debug(" to [%s]" % res_name) if (exp_event.equal(res_event)): exp_list.append(res_name) log.debug(" ->OK") else: log.debug(" ->FAIL"); log.debug(" match: [%s] matches %s" % (exp_name, str(exp_list))) # we did not any matching event - fail if (not exp_list): exp_event.diff(res_event) raise Fail(self, 'match failure'); match[exp_name] = exp_list # For each defined group in the expected events # check we match the same group in the result. for exp_name, exp_event in expect.items(): group = exp_event.group if (group == ''): continue for res_name in match[exp_name]: res_group = result[res_name].group if res_group not in match[group]: raise Fail(self, 'group failure') log.debug(" group: [%s] matches group leader %s" % (exp_name, str(match[group]))) log.debug(" matched") def resolve_groups(self, events): for name, event in events.items(): group_fd = event['group_fd']; if group_fd == '-1': continue; for iname, ievent in events.items(): if (ievent['fd'] == group_fd): event.group = iname log.debug('[%s] has group leader [%s]' % (name, iname)) break; def run(self): tempdir = tempfile.mkdtemp(); try: # run the test script self.run_cmd(tempdir); # load events expectation for the test log.debug(" loading result events"); for f in glob.glob(tempdir + '/event*'): self.load_events(f, self.result); # resolve group_fd to event names self.resolve_groups(self.expect); self.resolve_groups(self.result); # do the expectation - results matching - both ways self.compare(self.expect, self.result) self.compare(self.result, self.expect) finally: # cleanup shutil.rmtree(tempdir) def run_tests(options): for f in glob.glob(options.test_dir + '/' + options.test): try: Test(f, options).run() except Unsup, obj: log.warning("unsupp %s" % obj.getMsg()) def setup_log(verbose): global log level = logging.CRITICAL if verbose == 1: level = logging.WARNING if verbose == 2: level = logging.INFO if verbose >= 3: level = logging.DEBUG log = logging.getLogger('test') log.setLevel(level) ch = logging.StreamHandler() ch.setLevel(level) formatter = logging.Formatter('%(message)s') ch.setFormatter(formatter) log.addHandler(ch) USAGE = '''%s [OPTIONS] -d dir # tests dir -p path # perf binary -t test # single test -v # verbose level ''' % sys.argv[0] def main(): parser = optparse.OptionParser(usage=USAGE) parser.add_option("-t", "--test", action="store", type="string", dest="test") parser.add_option("-d", "--test-dir", action="store", type="string", dest="test_dir") parser.add_option("-p", "--perf", action="store", type="string", dest="perf") parser.add_option("-v", "--verbose", action="count", dest="verbose") options, args = parser.parse_args() if args: parser.error('FAILED wrong arguments %s' % ' '.join(args)) return -1 setup_log(options.verbose) if not options.test_dir: print 'FAILED no -d option specified' sys.exit(-1) if not options.test: options.test = 'test*' try: run_tests(options) except Fail, obj: print "FAILED %s" % obj.getMsg(); sys.exit(-1) sys.exit(0) if __name__ == '__main__': main()
Kazade/NeHe-Website
refs/heads/master
google_appengine/lib/django-1.4/django/contrib/gis/tests/layermap/models.py
239
from django.contrib.gis.db import models class State(models.Model): name = models.CharField(max_length=20) objects = models.GeoManager() class County(models.Model): name = models.CharField(max_length=25) state = models.ForeignKey(State) mpoly = models.MultiPolygonField(srid=4269) # Multipolygon in NAD83 objects = models.GeoManager() class CountyFeat(models.Model): name = models.CharField(max_length=25) poly = models.PolygonField(srid=4269) objects = models.GeoManager() class City(models.Model): name = models.CharField(max_length=25) population = models.IntegerField() density = models.DecimalField(max_digits=7, decimal_places=1) dt = models.DateField() point = models.PointField() objects = models.GeoManager() class Interstate(models.Model): name = models.CharField(max_length=20) length = models.DecimalField(max_digits=6, decimal_places=2) path = models.LineStringField() objects = models.GeoManager() # Same as `City` above, but for testing model inheritance. class CityBase(models.Model): name = models.CharField(max_length=25) population = models.IntegerField() density = models.DecimalField(max_digits=7, decimal_places=1) point = models.PointField() objects = models.GeoManager() class ICity1(CityBase): dt = models.DateField() class ICity2(ICity1): dt_time = models.DateTimeField(auto_now=True) class Invalid(models.Model): point = models.PointField() # Mapping dictionaries for the models above. co_mapping = {'name' : 'Name', 'state' : {'name' : 'State'}, # ForeignKey's use another mapping dictionary for the _related_ Model (State in this case). 'mpoly' : 'MULTIPOLYGON', # Will convert POLYGON features into MULTIPOLYGONS. } cofeat_mapping = {'name' : 'Name', 'poly' : 'POLYGON', } city_mapping = {'name' : 'Name', 'population' : 'Population', 'density' : 'Density', 'dt' : 'Created', 'point' : 'POINT', } inter_mapping = {'name' : 'Name', 'length' : 'Length', 'path' : 'LINESTRING', }
HaveF/idapython
refs/heads/master
examples/colours.py
16
#--------------------------------------------------------------------- # Colour test # # This script demonstrates the usage of background colours. # # Author: Gergely Erdelyi <gergely.erdelyi@d-dome.net> #--------------------------------------------------------------------- # Set the colour of the current segment to BLUE SetColor(here(), CIC_SEGM, 0xc02020) # Set the colour of the current function to GREEN SetColor(here(), CIC_FUNC, 0x208020) # Set the colour of the current item to RED SetColor(here(), CIC_ITEM, 0x2020c0) # Print the colours just set print "%x" % GetColor(here(), CIC_SEGM) print "%x" % GetColor(here(), CIC_FUNC) print "%x" % GetColor(here(), CIC_ITEM)
brinbois/Sick-Beard
refs/heads/development
sickbeard/webserveInit.py
43
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. #import cherrypy import cherrypy.lib.auth_basic import os.path import sickbeard from sickbeard import logger from sickbeard.webserve import WebInterface from sickbeard.helpers import create_https_certificates def initWebServer(options = {}): options.setdefault('port', 8081) options.setdefault('host', '0.0.0.0') options.setdefault('log_dir', None) options.setdefault('username', '') options.setdefault('password', '') options.setdefault('web_root', '/') assert isinstance(options['port'], int) assert 'data_root' in options def http_error_401_hander(status, message, traceback, version): """ Custom handler for 401 error """ if status != "401 Unauthorized": logger.log(u"CherryPy caught an error: %s %s" % (status, message), logger.ERROR) logger.log(traceback, logger.DEBUG) return r''' <html> <head> <title>%s</title> </head> <body> <br/> <font color="#0000FF">Error %s: You need to provide a valid username and password.</font> </body> </html> ''' % ('Access denied', status) def http_error_404_hander(status, message, traceback, version): """ Custom handler for 404 error, redirect back to main page """ return r''' <html> <head> <title>404</title> <script type="text/javascript" charset="utf-8"> <!-- location.href = "%s" //--> </script> </head> <body> <br/> </body> </html> ''' % '/' # cherrypy setup enable_https = options['enable_https'] https_cert = options['https_cert'] https_key = options['https_key'] if enable_https: # If either the HTTPS certificate or key do not exist, make some self-signed ones. if not (https_cert and os.path.exists(https_cert)) or not (https_key and os.path.exists(https_key)): if not create_https_certificates(https_cert, https_key): logger.log(u"Unable to create cert/key files, disabling HTTPS") sickbeard.ENABLE_HTTPS = False enable_https = False if not (os.path.exists(https_cert) and os.path.exists(https_key)): logger.log(u"Disabled HTTPS because of missing CERT and KEY files", logger.WARNING) sickbeard.ENABLE_HTTPS = False enable_https = False options_dict = { 'server.socket_port': options['port'], 'server.socket_host': options['host'], 'log.screen': False, 'error_page.401': http_error_401_hander, 'error_page.404': http_error_404_hander, } if enable_https: options_dict['server.ssl_certificate'] = https_cert options_dict['server.ssl_private_key'] = https_key protocol = "https" else: protocol = "http" logger.log(u"Starting Sick Beard on "+protocol+"://" + str(options['host']) + ":" + str(options['port']) + "/") cherrypy.config.update(options_dict) # setup cherrypy logging if options['log_dir'] and os.path.isdir(options['log_dir']): cherrypy.config.update({ 'log.access_file': os.path.join(options['log_dir'], "cherrypy.log") }) logger.log('Using %s for cherrypy log' % cherrypy.config['log.access_file']) conf = { '/': { 'tools.staticdir.root': options['data_root'], 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', }, '/images': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'images' }, '/js': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'js' }, '/css': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'css' }, } app = cherrypy.tree.mount(WebInterface(), options['web_root'], conf) # auth if options['username'] != "" and options['password'] != "": checkpassword = cherrypy.lib.auth_basic.checkpassword_dict({options['username']: options['password']}) app.merge({ '/': { 'tools.auth_basic.on': True, 'tools.auth_basic.realm': 'SickBeard', 'tools.auth_basic.checkpassword': checkpassword }, '/api':{ 'tools.auth_basic.on': False }, '/api/builder':{ 'tools.auth_basic.on': True, 'tools.auth_basic.realm': 'SickBeard', 'tools.auth_basic.checkpassword': checkpassword } }) cherrypy.server.start() cherrypy.server.wait()
M4sse/chromium.src
refs/heads/nw12
tools/perf/benchmarks/power.py
10
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from measurements import power import page_sets from telemetry import benchmark @benchmark.Enabled('android') class PowerAndroidAcceptance(benchmark.Benchmark): """Android power acceptance test.""" test = power.Power page_set = page_sets.AndroidAcceptancePageSet @benchmark.Enabled('android') class PowerTypical10Mobile(benchmark.Benchmark): """Android typical 10 mobile power test.""" test = power.Power page_set = page_sets.Typical10MobilePageSet
switowski/invenio
refs/heads/master
invenio/modules/formatter/format_elements/bfe_authority_control_no.py
13
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2015 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """BibFormat element - Prints the control number of an Authority Record. """ from invenio.config import CFG_SITE_URL, CFG_SITE_NAME from invenio.legacy.bibauthority.config import \ CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME, \ CFG_BIBAUTHORITY_RECORD_CONTROL_NUMBER_FIELD, \ CFG_BIBAUTHORITY_RECORD_AUTHOR_CONTROL_NUMBER_FIELDS as control_number_fields, \ CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_IDENTIFIER as authority_identifier from invenio.legacy.bibauthority.engine import \ get_low_level_recIDs_from_control_no, \ get_dependent_records_for_control_no __revision__ = "$Id$" def format_element(bfo): """ Prints the control number of an author authority record in HTML. By default prints brief version. @param brief: whether the 'brief' rather than the 'detailed' format @type brief: 'yes' or 'no' """ from invenio.base.i18n import gettext_set_language _ = gettext_set_language(bfo.lang) # load the right message language control_nos = [d['a'] for d in bfo.fields('035__') if d.get('a')] control_nos.extend([d['a'] for d in bfo.fields('970__') if d.get('a')]) authority_type = [d.get('a') for d in bfo.fields('980__') if d.get('a') and d.get('a')!=authority_identifier] if authority_type and type(authority_type) is list: authority_type = authority_type[0] related_control_number_fields = ['510','970'] related_control_number_fields.extend(control_number_fields.get(authority_type,[])) control_nos_formatted = [] for control_no in control_nos: recIDs = get_dependent_records_for_control_no(control_no) count = len(recIDs) count_string = str(count) + " dependent records" from urllib import quote # if we have dependent records, provide a link to them if count: prefix_pattern = "<a href='" + CFG_SITE_URL + "%s" + "'>" postfix = "</a>" url_str = '' # we have multiple dependent records if count > 1: # joining control_nos might be more helpful for the user # than joining recIDs... or maybe not... parameters = [] for control_number_field in related_control_number_fields: parameters.append(control_number_field + ":" + control_no ) p_val = quote(" or ".join(parameters)) # include "&c=" parameter for bibliographic records # and one "&c=" parameter for authority records url_str = \ "/search" + \ "?p=" + p_val + \ "&c=" + quote(CFG_SITE_NAME) + \ "&c=" + CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME + \ "&sc=1" + \ "&ln=" + bfo.lang # we have exactly one dependent record elif count == 1: url_str = "/record/" + str(recIDs[0]) prefix = prefix_pattern % (url_str) count_string = prefix + count_string + postfix #assemble the html and append to list html_str = control_no + " (" + count_string + ")" # check if there are more than one authority record with the same # control number. If so, warn the user about this inconsistency. # TODO: hide this warning from unauthorized users my_recIDs = get_low_level_recIDs_from_control_no(control_no) if len(my_recIDs) > 1: url_str = \ "/search" + \ "?p=" + CFG_BIBAUTHORITY_RECORD_CONTROL_NUMBER_FIELD + ":" + control_no + \ "&c=" + quote(CFG_SITE_NAME) + \ "&c=" + CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME + \ "&sc=1" + \ "&ln=" + bfo.lang html_str += \ ' <span style="color:red">' + \ '(Warning, there is currently ' + \ '<a href="' + url_str + '">more than one authority record</a> ' + \ 'with this Control Number)' + \ '</span>' control_nos_formatted.append(html_str) title = "<strong>" + _("Control Number(s)") + "</strong>" if control_nos_formatted: content = "<ul><li>" + "</li><li> ".join(control_nos_formatted) + "</li></ul>" else: content = "<strong style='color:red'>Missing !</strong>" return "<p>" + title + ": " + content + "</p>" def escape_values(bfo): """ Called by BibFormat in order to check if output of this element should be escaped. """ return 0
oinopion/django
refs/heads/master
tests/gis_tests/geoapp/feeds.py
367
from __future__ import unicode_literals from django.contrib.gis import feeds from .models import City class TestGeoRSS1(feeds.Feed): link = '/city/' title = 'Test GeoDjango Cities' def items(self): return City.objects.all() def item_link(self, item): return '/city/%s/' % item.pk def item_geometry(self, item): return item.point class TestGeoRSS2(TestGeoRSS1): def geometry(self, obj): # This should attach a <georss:box> element for the extent of # of the cities in the database. This tuple came from # calling `City.objects.extent()` -- we can't do that call here # because `extent` is not implemented for MySQL/Oracle. return (-123.30, -41.32, 174.78, 48.46) def item_geometry(self, item): # Returning a simple tuple for the geometry. return item.point.x, item.point.y class TestGeoAtom1(TestGeoRSS1): feed_type = feeds.GeoAtom1Feed class TestGeoAtom2(TestGeoRSS2): feed_type = feeds.GeoAtom1Feed def geometry(self, obj): # This time we'll use a 2-tuple of coordinates for the box. return ((-123.30, -41.32), (174.78, 48.46)) class TestW3CGeo1(TestGeoRSS1): feed_type = feeds.W3CGeoFeed # The following feeds are invalid, and will raise exceptions. class TestW3CGeo2(TestGeoRSS2): feed_type = feeds.W3CGeoFeed class TestW3CGeo3(TestGeoRSS1): feed_type = feeds.W3CGeoFeed def item_geometry(self, item): from django.contrib.gis.geos import Polygon return Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) # The feed dictionary to use for URLs. feed_dict = { 'rss1': TestGeoRSS1, 'rss2': TestGeoRSS2, 'atom1': TestGeoAtom1, 'atom2': TestGeoAtom2, 'w3cgeo1': TestW3CGeo1, 'w3cgeo2': TestW3CGeo2, 'w3cgeo3': TestW3CGeo3, }
nanvel/c2p2
refs/heads/master
setup.py
2
# -*- encoding: utf-8 -*- """ Python setup file for the nicedit app. In order to register your app at pypi.python.org, create an account at pypi.python.org and login, then register your new app like so: python setup.py register If your name is still free, you can now make your first release but first you should check if you are uploading the correct files: python setup.py sdist Inspect the output thoroughly. There shouldn't be any temp files and if your app includes staticfiles or templates, make sure that they appear in the list. If something is wrong, you need to edit MANIFEST.in and run the command again. If all looks good, you can make your first release: python setup.py sdist upload For new releases, you need to bump the version number in tornado_botocore/__init__.py and re-run the above command. For more information on creating source distributions, see http://docs.python.org/2/distutils/sourcedist.html """ import os from setuptools import setup, find_packages from c2p2 import VERSION def read(file_name): try: return open(os.path.join(os.path.dirname(__file__), file_name)).read() except IOError: return '' def parse_requirements(): requirements_text = read(file_name='requirements.txt') return (line.strip() for line in requirements_text.split('\n') if '=' in line) setup( name="c2p2", version=VERSION, description="Code Commit Push Publish engine.", long_description=read(file_name='README.rst'), license="The MIT License", platforms=['OS Independent'], keywords='tornado, github, blog, publish', author='Oleksandr Polieno', author_email='polyenoom@gmail.com', url='https://github.com/nanvel/c2p2', packages=find_packages(), install_requires=parse_requirements() )
ravello/ansible
refs/heads/devel
v2/ansible/inventory/host.py
34
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible import constants as C from ansible.inventory.group import Group from ansible.utils.vars import combine_vars __all__ = ['Host'] class Host: ''' a single ansible host ''' #__slots__ = [ 'name', 'vars', 'groups' ] def __getstate__(self): return self.serialize() def __setstate__(self, data): return self.deserialize(data) def __eq__(self, other): return self.name == other.name def serialize(self): groups = [] for group in self.groups: groups.append(group.serialize()) return dict( name=self.name, vars=self.vars.copy(), ipv4_address=self.ipv4_address, ipv6_address=self.ipv6_address, port=self.port, gathered_facts=self._gathered_facts, groups=groups, ) def deserialize(self, data): self.__init__() self.name = data.get('name') self.vars = data.get('vars', dict()) self.ipv4_address = data.get('ipv4_address', '') self.ipv6_address = data.get('ipv6_address', '') self.port = data.get('port') groups = data.get('groups', []) for group_data in groups: g = Group() g.deserialize(group_data) self.groups.append(g) def __init__(self, name=None, port=None): self.name = name self.vars = {} self.groups = [] self.ipv4_address = name self.ipv6_address = name if port and port != C.DEFAULT_REMOTE_PORT: self.port = int(port) else: self.port = C.DEFAULT_REMOTE_PORT self._gathered_facts = False def __repr__(self): return self.get_name() def get_name(self): return self.name @property def gathered_facts(self): return self._gathered_facts def set_gathered_facts(self, gathered): self._gathered_facts = gathered def add_group(self, group): self.groups.append(group) def set_variable(self, key, value): self.vars[key]=value def get_groups(self): groups = {} for g in self.groups: groups[g.name] = g ancestors = g.get_ancestors() for a in ancestors: groups[a.name] = a return groups.values() def get_vars(self): results = {} groups = self.get_groups() for group in sorted(groups, key=lambda g: g.depth): results = combine_vars(results, group.get_vars()) results = combine_vars(results, self.vars) results['inventory_hostname'] = self.name results['inventory_hostname_short'] = self.name.split('.')[0] results['group_names'] = sorted([ g.name for g in groups if g.name != 'all']) return results
evax/ansible-modules-core
refs/heads/devel
cloud/openstack/os_volume.py
131
#!/usr/bin/python # Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False DOCUMENTATION = ''' --- module: os_volume short_description: Create/Delete Cinder Volumes extends_documentation_fragment: openstack version_added: "2.0" author: "Monty Taylor (@emonty)" description: - Create or Remove cinder block storage volumes options: size: description: - Size of volume in GB required: only when state is 'present' default: None display_name: description: - Name of volume required: true display_description: description: - String describing the volume required: false default: None volume_type: description: - Volume type for volume required: false default: None image: description: - Image name or id for boot from volume required: false default: None snapshot_id: description: - Volume snapshot id to create from required: false default: None state: description: - Should the resource be present or absent. choices: [present, absent] default: present requirements: - "python >= 2.6" - "shade" ''' EXAMPLES = ''' # Creates a new volume - name: create a volume hosts: localhost tasks: - name: create 40g test volume os_volume: state: present cloud: mordred availability_zone: az2 size: 40 display_name: test_volume ''' def _present_volume(module, cloud): if cloud.volume_exists(module.params['display_name']): v = cloud.get_volume(module.params['display_name']) module.exit_json(changed=False, id=v['id'], volume=v) volume_args = dict( size=module.params['size'], volume_type=module.params['volume_type'], display_name=module.params['display_name'], display_description=module.params['display_description'], snapshot_id=module.params['snapshot_id'], availability_zone=module.params['availability_zone'], ) if module.params['image']: image_id = cloud.get_image_id(module.params['image']) volume_args['imageRef'] = image_id volume = cloud.create_volume( wait=module.params['wait'], timeout=module.params['timeout'], **volume_args) module.exit_json(changed=True, id=volume['id'], volume=volume) def _absent_volume(module, cloud): try: cloud.delete_volume( name_or_id=module.params['display_name'], wait=module.params['wait'], timeout=module.params['timeout']) except shade.OpenStackCloudTimeout: module.exit_json(changed=False) module.exit_json(changed=True) def main(): argument_spec = openstack_full_argument_spec( size=dict(default=None), volume_type=dict(default=None), display_name=dict(required=True, aliases=['name']), display_description=dict(default=None, aliases=['description']), image=dict(default=None), snapshot_id=dict(default=None), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs( mutually_exclusive=[ ['image', 'snapshot_id'], ], ) module = AnsibleModule(argument_spec=argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') state = module.params['state'] if state == 'present' and not module.params['size']: module.fail_json(msg="Size is required when state is 'present'") try: cloud = shade.openstack_cloud(**module.params) if state == 'present': _present_volume(module, cloud) if state == 'absent': _absent_volume(module, cloud) except shade.OpenStackCloudException as e: module.fail_json(msg=e.message) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
IronLanguages/ironpython3
refs/heads/master
Tests/interop/net/loadorder/t3b.py
1
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. from iptest.assert_util import * add_clr_assemblies("loadorder_3") # namespace First { # public class Generic1<K, V> { # public static string Flag = typeof(Generic1<,>).FullName; # } # } import First add_clr_assemblies("loadorder_3b") # namespace Second { # public class Generic2 { # public static string Flag = typeof(Generic2).FullName; # } # } import Second AreEqual(First.Generic1[str, str].Flag, "First.Generic1`2") AreEqual(Second.Generic2.Flag, "Second.Generic2") from First import * from Second import * AreEqual(Generic1[str, str].Flag, "First.Generic1`2") AreEqual(Generic2.Flag, "Second.Generic2")
opensourcechipspark/platform_external_chromium_org
refs/heads/master
chrome/common/extensions/docs/server2/caching_rietveld_patcher.py
25
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from datetime import datetime, timedelta from file_system import FileNotFoundError, ToUnicode from future import Future from patcher import Patcher _VERSION_CACHE_MAXAGE = timedelta(seconds=5) ''' Append @version for keys to distinguish between different patchsets of an issue. ''' def _MakeKey(path, version): return '%s@%s' % (path, version) def _ToObjectStoreValue(raw_value, version): return dict((_MakeKey(key, version), raw_value[key]) for key in raw_value) def _FromObjectStoreValue(raw_value, binary): return dict((key[0:key.rfind('@')], _HandleBinary(raw_value[key], binary)) for key in raw_value) def _HandleBinary(data, binary): return data if binary else ToUnicode(data) class _AsyncUncachedFuture(object): def __init__(self, version, paths, binary, cached_value, missing_paths, fetch_delegate, object_store): self._version = version self._paths = paths self._binary = binary self._cached_value = cached_value self._missing_paths = missing_paths self._fetch_delegate = fetch_delegate self._object_store = object_store def Get(self): uncached_raw_value = self._fetch_delegate.Get() self._object_store.SetMulti(_ToObjectStoreValue(uncached_raw_value, self._version)) for path in self._missing_paths: if uncached_raw_value.get(path) is None: raise FileNotFoundError('File %s was not found in the patch.' % path) self._cached_value[path] = _HandleBinary(uncached_raw_value[path], self._binary) return self._cached_value class CachingRietveldPatcher(Patcher): ''' CachingRietveldPatcher implements a caching layer on top of |patcher|. In theory, it can be used with any class that implements Patcher. But this class assumes that applying to all patched files at once is more efficient than applying to individual files. ''' def __init__(self, rietveld_patcher, object_store_creator, test_datetime=datetime): self._patcher = rietveld_patcher def create_object_store(category): return object_store_creator.Create( CachingRietveldPatcher, category='%s/%s' % (rietveld_patcher.GetIdentity(), category)) self._version_object_store = create_object_store('version') self._list_object_store = create_object_store('list') self._file_object_store = create_object_store('file') self._datetime = test_datetime def GetVersion(self): key = 'version' value = self._version_object_store.Get(key).Get() if value is not None: version, time = value if self._datetime.now() - time < _VERSION_CACHE_MAXAGE: return version version = self._patcher.GetVersion() self._version_object_store.Set(key, (version, self._datetime.now())) return version def GetPatchedFiles(self, version=None): if version is None: version = self.GetVersion() patched_files = self._list_object_store.Get(version).Get() if patched_files is not None: return patched_files patched_files = self._patcher.GetPatchedFiles(version) self._list_object_store.Set(version, patched_files) return patched_files def Apply(self, paths, file_system, binary=False, version=None): if version is None: version = self.GetVersion() added, deleted, modified = self.GetPatchedFiles(version) cached_value = _FromObjectStoreValue(self._file_object_store. GetMulti([_MakeKey(path, version) for path in paths]).Get(), binary) missing_paths = list(set(paths) - set(cached_value.keys())) if len(missing_paths) == 0: return Future(value=cached_value) # binary is explicitly set to True. Here we are applying the patch to # ALL patched files without a way to know whether individual files are # binary or not. Therefore all data cached must be binary. When reading # from the cache with binary=False, it will be converted to Unicode by # _HandleBinary. return _AsyncUncachedFuture(version, paths, binary, cached_value, missing_paths, self._patcher.Apply(set(added) | set(modified), None, True, version), self._file_object_store) def GetIdentity(self): return self._patcher.GetIdentity()
StenbergSimon/CNV_pipe
refs/heads/master
cnv_caller.py
1
import pysam import numpy import sys import os import math import optparse from subprocess import call #Set the options that need to be set prsr = optparse.OptionParser() prsr.add_option("-w", "--windowSize", dest="winsize", metavar="INT", default=500, help="Windowsize (bp) to be used to calculate log2ratio [Default:%default]") prsr.add_option("-m", "--mappingQuality", dest="mapq", metavar="INT", default=0, help="Mapping quality cutoff for reads to be used in the calculation [Default:%default]") prsr.add_option("-f", "--file", dest="bam", metavar="FILE", help="Input bam file to be analyzed, should be sorted and indexed") prsr.add_option("-o", "--ouput", dest="path", metavar="PATH", default=os.getcwd() ,help="Output path") prsr.add_option("-l", "--name-list", dest="order", metavar="FILE", default=os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "chr.list"), help="List of bam headers in order as they should be plotted, [Default:%default]") prsr.add_option("-a", "--plot", dest="plot", metavar="BOOLEAN", default=True, help="Specify if plotting should be done using DNAcopy [Default:%default]") prsr.add_option("-r", "--reference", dest="ref", metavar="FILE", help="Bam file to be used as reference / control") group = optparse.OptionGroup(prsr,"Zoom mode", "Zoom into specified chromsomal location and store as a new separate plot. " "Activate by using -z/-zoom") group.add_option("-z", "--zoom", dest="zoom", action="store_true", help="Runs in zoom-mode on a prerun project") group.add_option("-s", "--zstart", dest="zstart", metavar="INT", help="Zoom: Start chromosomal location") group.add_option("-e", "--zend", dest="zend", metavar="INT", help="Zoom: End chromosomal location") group.add_option("-c", "--zchrom", dest="zchrom", metavar="STR", help="Zoom: Chromosome") prsr.add_option_group(group) # Get options (options, args) = prsr.parse_args() DEVNULL = open(os.devnull, 'wb') def checkFile(test_file): if not os.path.isfile(test_file): quit("Could not find the file:" + test_file) def checkValidArgs(options): if options.bam == None: quit("ERROR: No BAM file submitted") checkFile(options.bam) def setAbsPath(options): options.path = os.path.abspath(options.path) return options.path def getNames(bam): header_dict = bam.header NAMES = [] LENGTHS = [] i = 0 while i < len(header_dict.get('SQ')): NAMES.append(header_dict.get('SQ')[i].get('SN')) LENGTHS.append(header_dict.get('SQ')[i].get('LN')) i = i + 1 return NAMES, LENGTHS def median(lst): return numpy.median(numpy.array(lst)) def getMedianCov(bam, NAMES, LENGTH): medians_dict = {} for name, ln in zip(NAMES, LENGTH): COVS = [] for pile in bam.pileup(name, 0, ln): cov = pile.n COVS.append(cov) chr_median = median(COVS) medians_dict[name] = chr_median return medians_dict def getNormalizer(bam, ref, NAMES, LENGTH): REF = [] BAM = [] for name, ln in zip(NAMES,LENGTH): for bam_pile in bam.pileup(name, 0, ln): BAM.append(bam_pile.n) for ref_pile in ref.pileup(name, 0, ln): REF.append(ref_pile.n) normalizer = float(sum(REF)) / float(sum(BAM)) return normalizer class RWriter(): def __init__(self, options): self.options = options self.data = () self.fh = None self.name = () self.head = () self.mid = () self.zoom = () self.pdf = () self.merge = () self.main = () self.name_list = open(options.order, "r") self.counter = 0 self.path = () for name in self.name_list: self.counter = self.counter + 1 self.name_list.seek(0) def getName(self): return self.name def setPath(self, path): self.path = path def writeHeader(self): print "writing R script..." HEAD = ["#!/usr/bin/env Rscript", "library(DNAcopy)"] self.head = '\n'.join(HEAD) + '\n' def writeMid(self): MID = [] n = 1 for name in self.name_list: name = name.rstrip() MID.append("c%s <- read.table(\"%s\")" % (n, os.path.join(self.path, name))) n = n + 1 n = 1 self.name_list.seek(0) for name in self.name_list: name = name.rstrip() MID.append("c%s$chr <- (\"%s\")" % (n, name)) n = n + 1 self.mid = '\n'.join(MID) + '\n' self.name_list.seek(0) def writePdf(self): PDF=[] PDF.append("pdf(\"%s\")" % os.path.join(self.path, "cnv_report.pdf")) self.pdf = ''.join(PDF) + '\n' def writeMerger(self): MERGE = [] MERGE.append("merged <- rbind(") n = 1 for name in self.name_list: name = name.rstrip() while n <= self.counter: if n == 1: MERGE.append("c") MERGE.append(str(n)) else: MERGE.append(",c") MERGE.append(str(n)) n = n + 1 MERGE.append(")") MERGE.append("\nCNA.object <- CNA(merged$V1, merged$chr, merged$V2, data.type=(\"logratio\"), presorted=TRUE)") MERGE.append("\nCNA.smooth <- smooth.CNA(CNA.object)") MERGE.append("\nCNA.segm <- segment(CNA.smooth)") self.merge = ''.join(MERGE) + '\n' self.name_list.seek(0) def writeMain(self): MAIN = [] MAIN.append("plot(CNA.segm, plot.type=\"w\")") MAIN.append("plot(CNA.segm, plot.type=\"s\")") MAIN.append("plot(CNA.segm, plot.type=\"p\")") MAIN.append("write.table(segments.summary(CNA.segm), file = \"%s\", sep=\"\\t\")" % os.path.join(self.path, "segments_summary.tsv")) n = 1 for name in self.name_list: MAIN.append("c%s.object <- CNA(c%s$V1, c%s$chr, c%s$V2, data.type=(\"logratio\"), presorted=TRUE)" % (n,n,n,n)) MAIN.append("c%s.smooth <- smooth.CNA(c%s.object)" % (n,n)) MAIN.append("c%s.segm <- segment(c%s.smooth)" % (n,n)) MAIN.append("plot(c%s.segm, plot.type=\"s\")" % n) n = n + 1 MAIN.append("dev.off()") self.main = '\n'.join(MAIN) def setName(self, name): self.name = name def assembler(self): self.writeHeader() self.writeMid() self.writePdf() self.writeMerger() self.writeMain() self.writer(self.name) def writer(self, name): self.fh = open(name, "w") self.fh.write(self.head) self.fh.write(self.mid) self.fh.write(self.pdf) self.fh.write(self.merge) self.fh.write(self.main) self.fh.close() def writeZoom(self): ZOOM = [] ZOOM.append("\npdf(\"%s\")" % os.path.join(self.path, str(options.zchrom) + "_" + str(options.zstart) + "_" + str(options.zend) + ".pdf")) ZOOM.append("zoomIntoRegion(CNA.segm, chrom=\"%s\", maploc.start=%s, maploc.end=%s, sampleid=\"Sample.1\")" % (options.zchrom, options.zstart, options.zend)) ZOOM.append("dev.off()") self.zoom = '\n'.join(ZOOM) + '\n' def aseembleZoom(self): self.writeHeader() self.writeMid() self.writeMerger() self.writeZoom() self.zoomWriter(self.name) def zoomWriter(self, name): self.fh = open(name, "w") self.fh.write(self.head) self.fh.write(self.mid) self.fh.write(self.merge) self.fh.write(self.zoom) self.fh.close() class CovScanner(): def __init__(self): self.window_size = () self.pos_start = 0 self.pos_end = () self.bamfile = () self.ref = None self.name = () self.mapq_cutoff = () self.RATIOS = [] self.POS = [] self.medians = None self.normalizer = () def setWindowSize(self, win): self.window_size = win self.pos_end = win def setChrMedians(self, medians): self.medians = medians def setSamFile(self, bam, ref): self.bamfile = bam self.ref = ref def setNormalizer(self, normalizer): self.normalizer = normalizer def setMapq(self, mapq): self.mapq_cutoff = int(mapq) def setName(self, name): self.name = name def move(self, ln): while self.pos_end < ln: window_mean = self.windowMean(self.bamfile) self.POS.append(self.pos_end) self.RATIOS.append(self.getLogratios(window_mean)) self.pos_start = self.pos_start + self.window_size self.pos_end = self.pos_end + self.window_size return self.RATIOS, self.POS def getLogratios(self, window_mean): if self.ref == None: logratio = window_mean / self.medians[self.name] else: win_mean_ref = self.windowMean(self.ref) if win_mean_ref == 0: win_mean_ref = 1 logratio = (window_mean * self.normalizer) / win_mean_ref if logratio == 0: logratio = 0 else: logratio = math.log(logratio, 2) return logratio def windowMean(self, bam): bam = pysam.AlignmentFile(bam, "rb") WINDOW_COVS = [] cov = () for pile in bam.pileup(self.name, self.pos_start, self.pos_end, truncate=True): cov = 0 for reads in pile.pileups: if reads.alignment.mapq >= self.mapq_cutoff: cov = cov + 1 WINDOW_COVS.append(cov) if sum(WINDOW_COVS) > 0: window_mean = numpy.mean(WINDOW_COVS) else: window_mean = 0 bam.close() return window_mean class FilePrinter(): def __init__(self, path): self._path = path self._fh = None def __enter__(self): self._fh = open(self._path, "w") return self def __exit__(self, *args): self._fh.close() self._fh = None def printToFile(self, *data): if (self._fh is None): raise Exception("Only use within with statement blocks") line = '\t'.join(map(str, data)) + "\n" self._fh.write(line) def printListToFile(self, LIST): for line in LIST: self._fh.write("%s\n" % line) def printZipListToFile(self, LIST1, LIST2): for line1, line2 in zip(LIST1, LIST2): self._fh.write("%s\t%s\n" % (line1, line2)) """ START """ if __name__ == "__main__": options.path = setAbsPath(options) normalizer = 0 if not os.path.exists(options.path): os.makedirs(options.path) if options.zoom: rscripter = RWriter(options) rscripter.setName(os.path.join(options.path, "run_DNAcopy.r")) rscripter.setPath(options.path) rscripter.aseembleZoom() cmd = ["Rscript", rscripter.getName()] call(cmd, stdout=DEVNULL, stderr=DEVNULL) rm_cmd = ["rm", rscripter.getName()] call(rm_cmd) else: bam = pysam.AlignmentFile(options.bam, "rb") NAMES, LENGTH = getNames(bam) if bool(options.plot) == True: rscripter = RWriter(options) rscripter.setName(os.path.join(options.path, "run_DNAcopy.r")) rscripter.setPath(options.path) rscripter.assembler() if options.ref == None: chr_medians = getMedianCov(bam, NAMES, LENGTH) else: ref = pysam.AlignmentFile(options.ref, "rb") normalizer = getNormalizer(bam, ref, NAMES, LENGTH) print "calculating log ratios..." for name, ln in zip(NAMES, LENGTH): with FilePrinter(os.path.join(options.path, name)) as out: scan = CovScanner() if options.ref == None: scan.setChrMedians(chr_medians) scan.setSamFile(options.bam, options.ref) scan.setMapq(int(options.mapq)) scan.setWindowSize(int(options.winsize)) scan.setNormalizer(normalizer) scan.setName(name) WINDOW_RATIOS, POS = scan.move(ln) out.printZipListToFile(WINDOW_RATIOS, POS) if bool(options.plot) == True: print "running plot scripts..." cmd = ["Rscript", rscripter.getName()] call(cmd, stdout=DEVNULL, stderr=DEVNULL) rm_cmd = ["rm", rscripter.getName()] call(rm_cmd) bam.close() DEVNULL.close()
Changaco/oh-mainline
refs/heads/master
vendor/packages/PyYaml/lib/yaml/events.py
986
# Abstract classes. class Event(object): def __init__(self, start_mark=None, end_mark=None): self.start_mark = start_mark self.end_mark = end_mark def __repr__(self): attributes = [key for key in ['anchor', 'tag', 'implicit', 'value'] if hasattr(self, key)] arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) for key in attributes]) return '%s(%s)' % (self.__class__.__name__, arguments) class NodeEvent(Event): def __init__(self, anchor, start_mark=None, end_mark=None): self.anchor = anchor self.start_mark = start_mark self.end_mark = end_mark class CollectionStartEvent(NodeEvent): def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None, flow_style=None): self.anchor = anchor self.tag = tag self.implicit = implicit self.start_mark = start_mark self.end_mark = end_mark self.flow_style = flow_style class CollectionEndEvent(Event): pass # Implementations. class StreamStartEvent(Event): def __init__(self, start_mark=None, end_mark=None, encoding=None): self.start_mark = start_mark self.end_mark = end_mark self.encoding = encoding class StreamEndEvent(Event): pass class DocumentStartEvent(Event): def __init__(self, start_mark=None, end_mark=None, explicit=None, version=None, tags=None): self.start_mark = start_mark self.end_mark = end_mark self.explicit = explicit self.version = version self.tags = tags class DocumentEndEvent(Event): def __init__(self, start_mark=None, end_mark=None, explicit=None): self.start_mark = start_mark self.end_mark = end_mark self.explicit = explicit class AliasEvent(NodeEvent): pass class ScalarEvent(NodeEvent): def __init__(self, anchor, tag, implicit, value, start_mark=None, end_mark=None, style=None): self.anchor = anchor self.tag = tag self.implicit = implicit self.value = value self.start_mark = start_mark self.end_mark = end_mark self.style = style class SequenceStartEvent(CollectionStartEvent): pass class SequenceEndEvent(CollectionEndEvent): pass class MappingStartEvent(CollectionStartEvent): pass class MappingEndEvent(CollectionEndEvent): pass
sreidy/roboticsclub.org
refs/heads/master
faq/__init__.py
12133432
Shouqun/node-gn
refs/heads/master
tools/depot_tools/testing_support/__init__.py
12133432
StuntsPT/Structure_threader
refs/heads/master
structure_threader/colorer/__init__.py
12133432
monikasulik/django-oscar
refs/heads/master
src/oscar/apps/customer/notifications/__init__.py
12133432
konrado0/vosqa
refs/heads/master
conf/__init__.py
12133432
kawamon/hue
refs/heads/master
desktop/core/ext-py/boto-2.46.1/tests/integration/s3/test_mfa.py
136
# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2010, Eucalyptus Systems, Inc. # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """ Some unit tests for S3 MfaDelete with versioning """ import unittest import time from nose.plugins.attrib import attr from boto.s3.connection import S3Connection from boto.exception import S3ResponseError from boto.s3.deletemarker import DeleteMarker @attr('notdefault', 's3mfa') class S3MFATest (unittest.TestCase): def setUp(self): self.conn = S3Connection() self.bucket_name = 'mfa-%d' % int(time.time()) self.bucket = self.conn.create_bucket(self.bucket_name) def tearDown(self): for k in self.bucket.list_versions(): self.bucket.delete_key(k.name, version_id=k.version_id) self.bucket.delete() def test_mfadel(self): # Enable Versioning with MfaDelete mfa_sn = raw_input('MFA S/N: ') mfa_code = raw_input('MFA Code: ') self.bucket.configure_versioning(True, mfa_delete=True, mfa_token=(mfa_sn, mfa_code)) # Check enabling mfa worked. i = 0 for i in range(1, 8): time.sleep(2**i) d = self.bucket.get_versioning_status() if d['Versioning'] == 'Enabled' and d['MfaDelete'] == 'Enabled': break self.assertEqual('Enabled', d['Versioning']) self.assertEqual('Enabled', d['MfaDelete']) # Add a key to the bucket k = self.bucket.new_key('foobar') s1 = 'This is v1' k.set_contents_from_string(s1) v1 = k.version_id # Now try to delete v1 without the MFA token try: self.bucket.delete_key('foobar', version_id=v1) self.fail("Must fail if not using MFA token") except S3ResponseError: pass # Now try delete again with the MFA token mfa_code = raw_input('MFA Code: ') self.bucket.delete_key('foobar', version_id=v1, mfa_token=(mfa_sn, mfa_code)) # Next suspend versioning and disable MfaDelete on the bucket mfa_code = raw_input('MFA Code: ') self.bucket.configure_versioning(False, mfa_delete=False, mfa_token=(mfa_sn, mfa_code)) # Lastly, check disabling mfa worked. i = 0 for i in range(1, 8): time.sleep(2**i) d = self.bucket.get_versioning_status() if d['Versioning'] == 'Suspended' and d['MfaDelete'] != 'Enabled': break self.assertEqual('Suspended', d['Versioning']) self.assertNotEqual('Enabled', d['MfaDelete'])
stynr/diaphora
refs/heads/master
pygments/styles/vim.py
50
# -*- coding: utf-8 -*- """ pygments.styles.vim ~~~~~~~~~~~~~~~~~~~ A highlighting style for Pygments, inspired by vim. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace, Token class VimStyle(Style): """ Styles somewhat like vim 7.0 """ background_color = "#000000" highlight_color = "#222222" default_style = "#cccccc" styles = { Token: "#cccccc", Whitespace: "", Comment: "#000080", Comment.Preproc: "", Comment.Special: "bold #cd0000", Keyword: "#cdcd00", Keyword.Declaration: "#00cd00", Keyword.Namespace: "#cd00cd", Keyword.Pseudo: "", Keyword.Type: "#00cd00", Operator: "#3399cc", Operator.Word: "#cdcd00", Name: "", Name.Class: "#00cdcd", Name.Builtin: "#cd00cd", Name.Exception: "bold #666699", Name.Variable: "#00cdcd", String: "#cd0000", Number: "#cd00cd", Generic.Heading: "bold #000080", Generic.Subheading: "bold #800080", Generic.Deleted: "#cd0000", Generic.Inserted: "#00cd00", Generic.Error: "#FF0000", Generic.Emph: "italic", Generic.Strong: "bold", Generic.Prompt: "bold #000080", Generic.Output: "#888", Generic.Traceback: "#04D", Error: "border:#FF0000" }
morganics/BayesPy
refs/heads/master
bayespy/ml.py
1
from bayespy.network import NetworkFactory class Selector: def __init__(self, target, continuous=[], discrete=[]): self.target = target self._continuous = list(continuous) self._discrete = list(discrete) self._index = -1 self._all_variables = self._continuous + self._discrete self._tix = self._all_variables.index(target) def _c_length(self): return len(self._continuous) def _d_length(self): return len(self._discrete) def _is_continuous(self, ix): return ix < self._c_length() def _is_discrete(self, ix): return ix >= self._c_length() def next_combination(self): self._index += 1 if self._index >= len(self._all_variables): return False return True class UnivariateSelector(Selector): def __init__(self, target, continuous=[], discrete=[]): Selector.__init__(self, target, continuous, discrete) def _get_vars(self): return [self._all_variables[self._index], self._all_variables[self._tix]] def get_discrete_variables(self): for v in self._get_vars(): if v in self._discrete: yield v def get_continuous_variables(self): for v in self._get_vars(): if v in self._continuous: yield v def get_key_variables(self): variables = self._get_vars() variables.pop(variables.index(self.target)) return variables def next_combination(self): self._index += 1 if self._index >= len(self._all_variables): return False v = self._get_vars() if len(np.unique(v)) < len(v): return self.next_combination() return True import numpy as np import itertools class CartesianProductSelector(Selector): def __init__(self, target, continuous=[], discrete=[], n=2): Selector.__init__(self, target, continuous, discrete) self._total = len(self._all_variables) if n > self._total - 1: raise ValueError("n needs to be less or equal to the total length of the variable array - 1") list_of_lists = [range(self._total) for _ in range(n)] self._combinations = list(set(itertools.product(*list_of_lists))) self._tix = self._all_variables.index(target) def _get_vars(self): r=[] for ix in self._indexes: r.append(self._all_variables[ix]) if self.target not in r: r.append(self.target) return r def get_total_combinations(self): return len([item for item in self._combinations if self._filter_combination(item)]) def _filter_combination(self, combination): if len(np.unique(combination)) != len(combination): return False if self._tix in combination: return False return True def get_key_variables(self): variables = self._get_vars() variables.pop(variables.index(self.target)) return variables def get_discrete_variables(self): for v in self._get_vars(): if v in self._discrete: yield v def get_continuous_variables(self): for v in self._get_vars(): if v in self._continuous: yield v def next_combination(self): self._index += 1 if self._index >= len(self._combinations): return False self._indexes = list(self._combinations[self._index]) if not self._filter_combination(self._indexes): return self.next_combination() return True #l = CartesianProductSelector('c1', continuous=['c1', 'c2', 'c3'], discrete=['d1','d2','d3'], n=4) #from collections import Counter #c = Counter() #while l.next_combination(): # # for i in [v for v in l.get_continuous_variables()]: # c[i] += 1 # for i in [v for v in l.get_discrete_variables()]: # c[i] += 1 class LeaveSomeOutSelector(Selector): def __init__(self, target, continuous=[], discrete=[], some=1): Selector.__init__(self, target, continuous, discrete) self._some = some if some > len(self._all_variables): raise ValueError("Some cannot be greater than the total number of columns") def _get_vars(self): variables = list(self._all_variables) start_index = self._index if self._index + self._some > len(variables): start_index = abs(len(variables) - (self._index + self._some)) r = variables[start_index : self._index] else: r = variables[ : start_index] + variables[start_index + self._some:] if self.target not in r: r.append(self.target) return r def get_discrete_variables(self): if self._index == -1: raise ValueError("Call next_combination first") for v in self._get_vars(): if v in self._discrete: yield v def get_continuous_variables(self): if self._index == -1: raise ValueError("Call next_combination first") for v in self._get_vars(): if v in self._continuous: yield v def get_key_variables(self): if self._index == -1: raise ValueError("Call next_combination first") return list(set(self._all_variables) - set(self._get_vars())) #l = LeaveSomeOutSelector('c1', continuous=['c1', 'c2', 'c3'], discrete=['d1', 'd2', 'd3'], some=3) #while l.next_combination(): # print(l._index) # print(list(l.get_continuous_variables())) # print(list(l.get_discrete_variables())) class IterativeSelector(Selector): def __init__(self, target, continuous=[], discrete=[], ordering=[], addition=True): Selector.__init__(self, target, continuous, discrete) self._ordering = ordering self._addition = addition def _get_vars(self): variables = list(self._ordering) start_index = self._index + 1 if self._addition: r = variables[:start_index] else: r = variables[-start_index:] if self.target not in r: r.append(self.target) return r def get_discrete_variables(self): if self._index == -1: raise ValueError("Call next_combination first") for v in self._get_vars(): if v in self._discrete: yield v def get_continuous_variables(self): if self._index == -1: raise ValueError("Call next_combination first") for v in self._get_vars(): if v in self._continuous: yield v def get_key_variables(self): if self._index == -1: raise ValueError("Call next_combination first") variables = self._get_vars() variables.pop(variables.index(self.target)) return variables def next_combination(self): self._index += 1 if self._index >= len(self._ordering): return False return True class ForwardFirstGreedySelector(IterativeSelector): def __init__(self, target, continuous=[], discrete=[], ordering=[]): IterativeSelector.__init__(self, target, continuous=continuous, discrete=discrete, ordering=ordering, addition=True) class BackFirstGreedySelector(IterativeSelector): def __init__(self, target, continuous=[], discrete=[], ordering=[]): IterativeSelector.__init__(self, target, continuous=continuous, discrete=discrete, ordering=ordering, addition=False) from sklearn.metrics import r2_score def continuous_score(x, y): return r2_score(x, y, multioutput='uniform_average') from sklearn.metrics import accuracy_score def discrete_score(x, y): return accuracy_score(x, y['MaxStateLikelihood']) from sklearn.metrics import confusion_matrix def fmeasure_score(predicted, actual): return _fmeasure(*confusion_matrix(predicted, actual).flatten()) def _fmeasure(tp, fp, fn, tn): """Computes effectiveness measures given a confusion matrix.""" specificity = tn / (tn + fp) sensitivity = tp / (tp + fn) fmeasure = 2 * (specificity * sensitivity) / (specificity + sensitivity) return { 'sensitivity': sensitivity, 'specificity': specificity, 'fmeasure': fmeasure } import numpy as np from collections import defaultdict def summarise_results(results, ascending=True): averaged_results = {key: np.average(value) for key,value in results.items()} summ = defaultdict(float) for k,v in averaged_results.items(): for s in k.split(","): summ[s] += float(v) return sorted(summ.items(), key=lambda x: x[1], reverse=(not ascending)) def summarise_best_combinations(results): averaged_results = {key: np.average(value) for key,value in results.items()} return sorted(averaged_results.items(), key=lambda x: x[1], reverse=True) from collections import OrderedDict from sklearn.cross_validation import KFold class VariableSelectionWrapper: def __init__(self, selector, score_func, logger): self._selector = selector self._score_func = score_func self._logger = logger self._models = [] def pick_vars(self, data, n_folds=3): kf = KFold(data.shape[0], n_folds=n_folds, shuffle=True) results = OrderedDict() network_factory = NetworkFactory(data, self._logger) self._logger.debug("Written dataset") i = 0 while self._selector.next_combination(): self._logger.debug("Combination: {}".format( ",".join(self._selector.get_key_variables()))) network = network_factory.create(discrete=list(self._selector.get_discrete_variables()), continuous=list(self._selector.get_continuous_variables())) key = ",".join(self._selector.get_key_variables()) results.update({ key: [] }) for k, (train_indexes, test_indexes) in enumerate(kf): _, X_test = data.ix[train_indexes], data.ix[test_indexes] trained_model = network_factory.create_trained_model(network, train_indexes) self._models.append(trained_model) r = trained_model.predict(test_indexes, targets=[self._selector.target]) score = self._score_func(X_test[self._selector.target], r[self._selector.target]) self._logger.debug("Score i={}, k={}: {}".format( i, k, score)) results[key].append(score) i += 1 return results
digideskio/ajenti
refs/heads/master
ajenti/plugins/recovery/config.py
17
from ajenti.api import ModuleConfig from main import RecoveryPlugin class GeneralConfig(ModuleConfig): target = RecoveryPlugin labels = { 'auto': 'Automatic backup' } auto = True
pidydx/grr
refs/heads/master
grr/lib/builders/tests.py
2
#!/usr/bin/env python """Test registry for builders.""" # These need to register plugins so, pylint: disable=unused-import from grr.lib.builders import signing_test # pylint: enable=unused-import
timsnyder/bokeh
refs/heads/master
bokeh/models/selections.py
2
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports # External imports # Bokeh imports from ..core.has_props import abstract from ..core.properties import Dict, Int, Seq, String from ..model import Model #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'IntersectRenderers', 'Selection', 'SelectionPolicy', 'UnionRenderers', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- class Selection(Model): ''' A Selection represents a portion of the data in a ``DataSource``, which can be visually manipulated in a plot. Selections are typically created by selecting points in a plot with a ``SelectTool``, but can also be programmatically specified. ''' indices = Seq(Int, default=[], help=""" The indices included in a selection. """) line_indices = Seq(Int, default=[], help=""" """) multiline_indices = Dict(String, Seq(Int), default={}, help=""" """) # TODO (bev) image_indicies @abstract class SelectionPolicy(Model): ''' ''' pass class IntersectRenderers(SelectionPolicy): ''' When a data source is shared between multiple renderers, a row in the data source will only be selected if that point for each renderer is selected. The selection is made from the intersection of hit test results from all renderers. ''' pass class UnionRenderers(SelectionPolicy): ''' When a data source is shared between multiple renderers, selecting a point on from any renderer will cause that row in the data source to be selected. The selection is made from the union of hit test results from all renderers. ''' pass #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
tcwicklund/django
refs/heads/master
django/contrib/admindocs/apps.py
589
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class AdminDocsConfig(AppConfig): name = 'django.contrib.admindocs' verbose_name = _("Administrative Documentation")
igal/openproposals
refs/heads/master
public/fckeditor/_samples/py/sample01.py
69
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Sample page. """ import cgi import os # Ensure that the fckeditor.py is included in your classpath import fckeditor # Tell the browser to render html print "Content-Type: text/html" print "" # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Sample</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>FCKeditor - Python - Sample 1</h1> This sample displays a normal HTML form with an FCKeditor with full features enabled. <hr> <form action="sampleposteddata.py" method="post" target="_blank"> """ # This is the real work try: sBasePath = os.environ.get("SCRIPT_NAME") sBasePath = sBasePath[0:sBasePath.find("_samples")] oFCKeditor = fckeditor.FCKeditor('FCKeditor1') oFCKeditor.BasePath = sBasePath oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>""" print oFCKeditor.Create() except Exception, e: print e print """ <br> <input type="submit" value="Submit"> </form> """ # For testing your environments print "<hr>" for key in os.environ.keys(): print "%s: %s<br>" % (key, os.environ.get(key, "")) print "<hr>" # Document footer print """ </body> </html> """
JAOSP/aosp_platform_external_chromium_org
refs/heads/master
tools/perf/benchmarks/blink_perf.py
23
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry import test from telemetry.core import util from measurements import blink_perf class BlinkPerfAll(test.Test): test = blink_perf.BlinkPerf def CreatePageSet(self, options): path = os.path.join( util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests') return blink_perf.CreatePageSetFromPath(path)
spasmilo/electrum
refs/heads/master
lib/simple_config.py
2
import ast import threading import os from util import user_dir, print_error, print_msg SYSTEM_CONFIG_PATH = "/etc/electrum.conf" config = None def get_config(): global config return config def set_config(c): global config config = c class SimpleConfig(object): """ The SimpleConfig class is responsible for handling operations involving configuration files. There are 3 different sources of possible configuration values: 1. Command line options. 2. User configuration (in the user's config directory) 3. System configuration (in /etc/) They are taken in order (1. overrides config options set in 2., that override config set in 3.) """ def __init__(self, options=None, read_system_config_function=None, read_user_config_function=None, read_user_dir_function=None): # This is the holder of actual options for the current user. self.read_only_options = {} # This lock needs to be acquired for updating and reading the config in # a thread-safe way. self.lock = threading.RLock() # The path for the config directory. This is set later by init_path() self.path = None if options is None: options = {} # Having a mutable as a default value is a bad idea. # The following two functions are there for dependency injection when # testing. if read_system_config_function is None: read_system_config_function = read_system_config if read_user_config_function is None: read_user_config_function = read_user_config if read_user_dir_function is None: self.user_dir = user_dir else: self.user_dir = read_user_dir_function # Save the command-line keys to make sure we don't override them. self.command_line_keys = options.keys() # Save the system config keys to make sure we don't override them. self.system_config_keys = [] if options.get('portable') is not True: # system conf system_config = read_system_config_function() self.system_config_keys = system_config.keys() self.read_only_options.update(system_config) # update the current options with the command line options last (to # override both others). self.read_only_options.update(options) # init path self.init_path() # user config. self.user_config = read_user_config_function(self.path) set_config(self) # Make a singleton instance of 'self' def init_path(self): # Read electrum path in the command line configuration self.path = self.read_only_options.get('electrum_path') # If not set, use the user's default data directory. if self.path is None: self.path = self.user_dir() # Make directory if it does not yet exist. if not os.path.exists(self.path): os.mkdir(self.path) print_error( "electrum directory", self.path) def set_key(self, key, value, save = True): if not self.is_modifiable(key): print "Warning: not changing key '%s' because it is not modifiable" \ " (passed as command line option or defined in /etc/electrum.conf)"%key return with self.lock: self.user_config[key] = value if save: self.save_user_config() return def get(self, key, default=None): out = None with self.lock: out = self.read_only_options.get(key) if out is None: out = self.user_config.get(key, default) return out def is_modifiable(self, key): if key in self.command_line_keys: return False if key in self.system_config_keys: return False return True def save_user_config(self): if not self.path: return path = os.path.join(self.path, "config") s = repr(self.user_config) f = open(path,"w") f.write( s ) f.close() if self.get('gui') != 'android': import stat os.chmod(path, stat.S_IREAD | stat.S_IWRITE) def read_system_config(path=SYSTEM_CONFIG_PATH): """Parse and return the system config settings in /etc/electrum.conf.""" result = {} if os.path.exists(path): try: import ConfigParser except ImportError: print "cannot parse electrum.conf. please install ConfigParser" return p = ConfigParser.ConfigParser() try: p.read(path) for k, v in p.items('client'): result[k] = v except (ConfigParser.NoSectionError, ConfigParser.MissingSectionHeaderError): pass return result def read_user_config(path): """Parse and store the user config settings in electrum.conf into user_config[].""" if not path: return {} # Return a dict, since we will call update() on it. config_path = os.path.join(path, "config") result = {} if os.path.exists(config_path): try: with open(config_path, "r") as f: data = f.read() result = ast.literal_eval( data ) #parse raw data from reading wallet file except Exception: print_msg("Error: Cannot read config file.") result = {} if not type(result) is dict: return {} return result
djmitche/build-relengapi
refs/heads/master
relengapi/blueprints/tokenauth/types.py
3
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import from datetime import datetime import wsme.types from relengapi.lib.api import jsonObject class JsonToken(wsme.types.Base): """A token granting the bearer a limited set of permissions. In all cases except creating a new token, the ``token`` attribute is empty. There is no way to recover a lost token string except for revoking and re-issuing the token. """ _name = 'Token' #: token type (short string). This defaults to ``prm`` for backward #: compatibility, but should always be specified. typ = wsme.types.wsattr( wsme.types.Enum(unicode, 'prm', 'tmp', 'usr'), mandatory=False, default='prm') #: token ID for revokable tokens id = wsme.types.wsattr(int, mandatory=False) #: not-before time for limited-duration tokens (see #: :ref:`Datetime-Format` for format information) not_before = wsme.types.wsattr(datetime, mandatory=False) #: expiration time for limited-duration tokens expires = wsme.types.wsattr(datetime, mandatory=False) #: metadata fro limited-duration tokens (arbitrary JSON object) metadata = wsme.types.wsattr(jsonObject, mandatory=False) #: if true, the token is disabled because the associated user's #: permissions are no longer sufficient. disabled = wsme.types.wsattr(bool, mandatory=False) #: list of permissions this token grants permissions = wsme.types.wsattr([unicode], mandatory=True) #: the user-supplied token description for revokable tokens description = wsme.types.wsattr(unicode, mandatory=False) #: user email for user-associated tokens user = wsme.types.wsattr(unicode, mandatory=False) #: the opaque token string (only set on new tokens) token = wsme.types.wsattr(unicode, mandatory=False)
rebstar6/servo
refs/heads/master
tests/wpt/web-platform-tests/referrer-policy/generic/subresource/document.py
227
import os, json, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import subresource def generate_payload(server_data): return subresource.get_template("document.html.template") % server_data def main(request, response): subresource.respond(request, response, payload_generator = generate_payload)
garg10may/youtube-dl
refs/heads/master
devscripts/make_contributing.py
137
#!/usr/bin/env python from __future__ import unicode_literals import io import optparse import re def main(): parser = optparse.OptionParser(usage='%prog INFILE OUTFILE') options, args = parser.parse_args() if len(args) != 2: parser.error('Expected an input and an output filename') infile, outfile = args with io.open(infile, encoding='utf-8') as inf: readme = inf.read() bug_text = re.search( r'(?s)#\s*BUGS\s*[^\n]*\s*(.*?)#\s*COPYRIGHT', readme).group(1) dev_text = re.search( r'(?s)(#\s*DEVELOPER INSTRUCTIONS.*?)#\s*EMBEDDING YOUTUBE-DL', readme).group(1) out = bug_text + dev_text with io.open(outfile, 'w', encoding='utf-8') as outf: outf.write(out) if __name__ == '__main__': main()
tttthemanCorp/CardmeleonAppEngine
refs/heads/master
django/views/__init__.py
12133432
luisjuansp/NaoWatsonTutor
refs/heads/master
watson_conversation.py
1
from watson_developer_cloud import ConversationV1 import unicodedata class Watson_Conversation: def __init__(self, username, password, version, workspace_id): self.conversation = ConversationV1( username=username, password=password, version=version) self.workspace_id = workspace_id self.context = None def message(self, message, context=None): if context != None: self.context = context response = self.conversation.message(self.workspace_id, {'text': message}, self.context) self.context = response['context'] return unicodedata.normalize('NFKD', "".join(response["output"]["text"])).encode('ascii','ignore') # watson_conversation = Watson_Conversation('6432cebe-14b4-4f93-8e73-12ccdb5891c2', # 'ccaNRkHB1Uqt', '2016-09-20', # '21d88c8e-c0e8-48cb-bffb-61524417ae38') # watson_conversation.message("hello") # # print(watson_conversation.message("turn on my lights")) #"username": "6734af95-6ca0-4d72-b80b-6c3b578c16bf", # "password": "CqsrM7IrxeCZ" #6432cebe-14b4-4f93-8e73-12ccdb5891c2, ccaNRkHB1Uqt
dma-source/EjerciciosPython
refs/heads/master
numeroMayor.py
1
print "Introduce 5 numeros:" vector=[] #definimos una lista #introducimos 5 numeros for i in range(0,5): numero=int(raw_input('introduce no. '+str(i+1)+': ')) vector.append(numero) print vector mayor=0 for v in vector: if mayor<v: mayor=v print 'mayor es: ',mayor #ESTE SCRIPT NO ES MIO LO COPIÉ DE OTRA PERSONA LA CUAL NO RECUERDO SU NOMBRE NI LA PÁGINA DE DONDE LO SAQUÉ #si este script no les funciona pueden probar codificar los ascii a utf-8 o solamente borrar las letras con tilde
kasioumis/invenio
refs/heads/master
invenio/testsuite/test_legacy_webdoc.py
13
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2008, 2009, 2010, 2011, 2013 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """WebDoc module unit tests.""" __revision__ = "$Id$" from flask import current_app from invenio.base.globals import cfg from invenio.base.wrappers import lazy_import from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase gettext_set_language = lazy_import('invenio.base.i18n:gettext_set_language') transform = lazy_import('invenio.legacy.webdoc.api:transform') class WebDocLanguageTest(InvenioTestCase): """Check that WebDoc correctly supports <lang> translation directives and _()_ syntax""" def setUp(self): self.__langs = current_app.config['CFG_SITE_LANGS'] current_app.config['CFG_SITE_LANGS'] = ['de', 'en', 'fr'] def tearDown(self): current_app.config['CFG_SITE_LANGS'] = self.__langs def test_language_filtering(self): """webdoc - language filtering""" result = transform(''' <strong> <lang> <python>{}</python> <en><red>Book</red></en> <fr><yellow>Livre</yellow></fr> <de><blue>Buch</blue></de> </lang> </strong> ''', languages=['de']) # German is kept self.assertEqual(result[0][0], 'de') self.assert_('<blue>Buch</blue>' in result[0][1]) # English and French must be filtered out in any case self.assert_('Livre' not in result[0][1]) self.assert_('Book' not in result[0][1]) # Python is not considered as a language, so the string is # kept as it is self.assert_('<python>{}</python' in result[0][1]) def test_string_translation(self): """webdoc - string translation""" result = transform('my_string: _(Search)_ (end)', languages=[cfg['CFG_SITE_LANG']]) _ = gettext_set_language(cfg['CFG_SITE_LANG']) self.assertEqual(result[0][1], 'my_string: %s (end)' % _("Search")) class WebDocPartsTest(InvenioTestCase): """Check that WebDoc correctly returns values for the different parts of webdoc files""" def setUp(self): self.__langs = current_app.config['CFG_SITE_LANGS'] current_app.config['CFG_SITE_LANGS'] = ['de', 'en', 'fr'] def tearDown(self): current_app.config['CFG_SITE_LANGS'] = self.__langs def test_parts(self): """webdoc - retrieving parts of webdoc file (title, navtrail, etc)""" from invenio.config import CFG_SITE_URL _ = gettext_set_language(cfg['CFG_SITE_LANG']) result = transform(''' <!-- WebDoc-Page-Title: _(Help Central)_ --> <!-- WebDoc-Page-Navtrail: <a class="navtrail" href="<CFG_SITE_URL>/help/hacking">Hacking Invenio</a> &gt; <a class="navtrail" href="webstyle-internals">WebStyle Internals</a> --> <!-- WebDoc-Page-Revision: $Id: help-central.webdoc,v 1.5 2008/05/26 12:52:41 jerome Exp $ --> <!-- WebDoc-Page-Description: A description -->''', languages=[cfg['CFG_SITE_LANG']]) # Title self.assertEqual(result[0][2], _("Help Central")) # Keywords. None in our sample self.assertEqual(result[0][3], None) # Navtrail self.assertEqual(result[0][4], '<a class="navtrail" href="%s/help/hacking">Hacking Invenio</a> &gt; <a class="navtrail" href="webstyle-internals">WebStyle Internals</a>' % CFG_SITE_URL) # Revision. Keep date & time only self.assertEqual(result[0][5], '2008-05-26 12:52:41') # Description self.assertEqual(result[0][6], 'A description') class WebDocVariableReplacementTest(InvenioTestCase): """Check that WebDoc correctly replaces variables with their values""" def setUp(self): self.__langs = current_app.config['CFG_SITE_LANGS'] current_app.config['CFG_SITE_LANGS'] = ['de', 'en', 'fr'] def tearDown(self): current_app.config['CFG_SITE_LANGS'] = self.__langs def test_CFG_SITE_URL_variable_replacement(self): """webdoc - replacing <CFG_SITE_URL> in webdoc files""" from invenio.config import CFG_SITE_URL result = transform('<CFG_SITE_URL>', languages=[cfg['CFG_SITE_LANG']]) self.assertEqual(result[0][1], CFG_SITE_URL) def test_language_tags_replacement(self): """webdoc - replacing <lang:link /> and <lang:current /> in webdoc files""" result = transform('<lang:current />', languages=[cfg['CFG_SITE_LANG']]) self.assertEqual(result[0][1], cfg['CFG_SITE_LANG']) # ?ln=.. is returned only if not cfg['CFG_SITE_LANG'] result = transform('<lang:link />', languages=[cfg['CFG_SITE_LANG']]) self.assertEqual(result[0][1], '?ln=%s' % cfg['CFG_SITE_LANG']) result = transform('<lang:link />', languages=['fr']) self.assertEqual(result[0][1], '?ln=fr') class WebDocCommentsFiltering(InvenioTestCase): """Check that comments are correctly removed from webdoc files""" def setUp(self): self.__langs = current_app.config['CFG_SITE_LANGS'] current_app.config['CFG_SITE_LANGS'] = ['de', 'en', 'fr'] def tearDown(self): current_app.config['CFG_SITE_LANGS'] = self.__langs def test_comments_filtering(self): """webdoc - removing comments""" result = transform('''# -*- coding: utf-8 -*- ## $Id$ ##''', languages=[cfg['CFG_SITE_LANG']]) self.assertEqual(result[0][1], '') TEST_SUITE = make_test_suite(WebDocLanguageTest, WebDocPartsTest, WebDocVariableReplacementTest, WebDocCommentsFiltering,) if __name__ == "__main__": run_test_suite(TEST_SUITE)
cobbler/cobbler
refs/heads/master
cobbler/actions/reposync.py
1
""" Builds out and synchronizes yum repo mirrors. Initial support for rsync, perhaps reposync coming later. Copyright 2006-2007, Red Hat, Inc and Others Michael DeHaan <michael.dehaan AT gmail> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """ import logging import os import os.path import pipes import stat import shutil from typing import Union from cobbler import utils from cobbler import download_manager from cobbler.enums import RepoArchs from cobbler.utils import os_release HAS_LIBREPO = True try: import librepo except: HAS_LIBREPO = False def repo_walker(top, func, arg): """ Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common. :param top: The directory that should be taken as root. The root dir will also be included in the processing. :param func: The function that should be executed. :param arg: The arguments for that function. """ try: names = os.listdir(top) except os.error: return func(arg, top, names) for name in names: name = os.path.join(top, name) try: st = os.lstat(name) except os.error: continue if stat.S_ISDIR(st.st_mode): repo_walker(name, func, arg) class RepoSync: """ Handles conversion of internal state to the tftpboot tree layout. """ # ================================================================================== def __init__(self, collection_mgr, tries: int = 1, nofail: bool = False): """ Constructor :param collection_mgr: The object which holds all information in Cobbler. :param tries: The number of tries before the operation fails. :param nofail: This sets the strictness of the reposync result handling. :param logger: The logger to audit all actions with. """ self.verbose = True self.api = collection_mgr.api self.collection_mgr = collection_mgr self.distros = collection_mgr.distros() self.profiles = collection_mgr.profiles() self.systems = collection_mgr.systems() self.settings = collection_mgr.settings() self.repos = collection_mgr.repos() self.rflags = self.settings.reposync_flags self.tries = tries self.nofail = nofail self.logger = logging.getLogger() self.dlmgr = download_manager.DownloadManager(self.collection_mgr) self.logger.info("hello, reposync") # =================================================================== def run(self, name=None, verbose: bool = True): """ Syncs the current repo configuration file with the filesystem. :param name: The name of the repository to synchronize. :param verbose: If the action should be logged verbose or not. """ self.logger.info("run, reposync, run!") try: self.tries = int(self.tries) except: utils.die("retry value must be an integer") self.verbose = verbose report_failure = False for repo in self.repos: if name is not None and repo.name != name: # Invoked to sync only a specific repo, this is not the one continue elif name is None and not repo.keep_updated: # Invoked to run against all repos, but this one is off self.logger.info("%s is set to not be updated" % repo.name) continue repo_mirror = os.path.join(self.settings.webdir, "repo_mirror") repo_path = os.path.join(repo_mirror, repo.name) if not os.path.isdir(repo_path) and not repo.mirror.lower().startswith("rhn://"): os.makedirs(repo_path) # Set the environment keys specified for this repo and save the old one if they modify an existing variable. env = repo.environment old_env = {} for k in list(env.keys()): self.logger.debug("setting repo environment: %s=%s" % (k, env[k])) if env[k] is not None: if os.getenv(k): old_env[k] = os.getenv(k) else: os.environ[k] = env[k] # Which may actually NOT reposync if the repo is set to not mirror locally but that's a technicality. for x in range(self.tries + 1, 1, -1): success = False try: self.sync(repo) success = True break except: utils.log_exc() self.logger.warning("reposync failed, tries left: %s" % (x - 2)) # Cleanup/restore any environment variables that were added or changed above. for k in list(env.keys()): if env[k] is not None: if k in old_env: self.logger.debug("resetting repo environment: %s=%s" % (k, old_env[k])) os.environ[k] = old_env[k] else: self.logger.debug("removing repo environment: %s=%s" % (k, env[k])) del os.environ[k] if not success: report_failure = True if not self.nofail: utils.die("reposync failed, retry limit reached, aborting") else: self.logger.error("reposync failed, retry limit reached, skipping") self.update_permissions(repo_path) if report_failure: utils.die("overall reposync failed, at least one repo failed to synchronize") # ================================================================================== def sync(self, repo): """ Conditionally sync a repo, based on type. :param repo: The repo to sync. """ if repo.breed == "rhn": self.rhn_sync(repo) elif repo.breed == "yum": self.yum_sync(repo) elif repo.breed == "apt": self.apt_sync(repo) elif repo.breed == "rsync": self.rsync_sync(repo) elif repo.breed == "wget": self.wget_sync(repo) else: utils.die("unable to sync repo (%s), unknown or unsupported repo type (%s)" % (repo.name, repo.breed)) # ==================================================================================== def librepo_getinfo(self, dirname): h = librepo.Handle() r = librepo.Result() h.setopt(librepo.LRO_REPOTYPE, librepo.LR_YUMREPO) h.setopt(librepo.LRO_URLS, [dirname]) h.setopt(librepo.LRO_LOCAL, True) h.setopt(librepo.LRO_CHECKSUM, True) h.setopt(librepo.LRO_IGNOREMISSING, True) try: h.perform(r) except librepo.LibrepoException as e: utils.die("librepo error: " + dirname + " - " + e.args[1]) rmd = r.getinfo(librepo.LRR_RPMMD_REPOMD)['records'] return rmd # ==================================================================================== def createrepo_walker(self, repo, dirname: str, fnames): """ Used to run createrepo on a copied Yum mirror. :param repo: The repository object to run for. :param dirname: The directory to run in. :param fnames: Not known what this is for. """ if os.path.exists(dirname) or repo['breed'] == 'rsync': utils.remove_yum_olddata(dirname) # add any repo metadata we can use mdoptions = [] origin_path = os.path.join(dirname, ".origin") repodata_path = os.path.join(origin_path, "repodata") if os.path.isfile(os.path.join(repodata_path, "repomd.xml")): rd = self.librepo_getinfo(origin_path) if "group" in rd: groupmdfile = rd['group']['location_href'] mdoptions.append("-g %s" % os.path.join(origin_path, groupmdfile)) if "prestodelta" in rd: # need createrepo >= 0.9.7 to add deltas if utils.get_family() in ("redhat", "suse"): cmd = "/usr/bin/rpmquery --queryformat=%{VERSION} createrepo" createrepo_ver = utils.subprocess_get(cmd) if not createrepo_ver[0:1].isdigit(): cmd = "/usr/bin/rpmquery --queryformat=%{VERSION} createrepo_c" createrepo_ver = utils.subprocess_get(cmd) if utils.compare_versions_gt(createrepo_ver, "0.9.7"): mdoptions.append("--deltas") else: self.logger.error("this repo has presto metadata; you must upgrade createrepo to >= 0.9.7 " "first and then need to resync the repo through Cobbler.") blended = utils.blender(self.api, False, repo) flags = blended.get("createrepo_flags", "(ERROR: FLAGS)") try: cmd = "createrepo %s %s %s" % (" ".join(mdoptions), flags, pipes.quote(dirname)) utils.subprocess_call(cmd) except: utils.log_exc() self.logger.error("createrepo failed.") del fnames[:] # we're in the right place # ==================================================================================== def wget_sync(self, repo): """ Handle mirroring of directories using wget :param repo: The repo object to sync via wget. """ repo_mirror = repo.mirror.strip() if repo.rpm_list != "" and repo.rpm_list != []: self.logger.warning("--rpm-list is not supported for wget'd repositories") # FIXME: don't hardcode dest_path = os.path.join(self.settings.webdir + "/repo_mirror", repo.name) # FIXME: wrapper for subprocess that logs to logger cmd = "wget -N -np -r -l inf -nd -P %s %s" % (pipes.quote(dest_path), pipes.quote(repo_mirror)) rc = utils.subprocess_call(cmd) if rc != 0: utils.die("cobbler reposync failed") repo_walker(dest_path, self.createrepo_walker, repo) self.create_local_file(dest_path, repo) # ==================================================================================== def rsync_sync(self, repo): """ Handle copying of rsync:// and rsync-over-ssh repos. :param repo: The repo to sync via rsync. """ if not repo.mirror_locally: utils.die("rsync:// urls must be mirrored locally, yum cannot access them directly") if repo.rpm_list != "" and repo.rpm_list != []: self.logger.warning("--rpm-list is not supported for rsync'd repositories") # FIXME: don't hardcode dest_path = os.path.join(self.settings.webdir + "/repo_mirror", repo.name) spacer = "" if not repo.mirror.startswith("rsync://") and not repo.mirror.startswith("/"): spacer = "-e ssh" if not repo.mirror.strip().endswith("/"): repo.mirror = "%s/" % repo.mirror flags = '' for x in repo.rsyncopts: if repo.rsyncopts[x]: flags += " %s %s" % (x, repo.rsyncopts[x]) else: flags += " %s" % x if flags == '': flags = self.settings.reposync_rsync_flags cmd = "rsync %s --delete-after %s --delete --exclude-from=/etc/cobbler/rsync.exclude %s %s" \ % (flags, spacer, pipes.quote(repo.mirror), pipes.quote(dest_path)) rc = utils.subprocess_call(cmd) if rc != 0: utils.die("cobbler reposync failed") # If ran in archive mode then repo should already contain all repodata and does not need createrepo run archive = False if '--archive' in flags: archive = True else: # split flags and skip all --{options} as we need to look for combined flags like -vaH fl = flags.split() for f in fl: if f.startswith('--'): pass else: if 'a' in f: archive = True break if not archive: repo_walker(dest_path, self.createrepo_walker, repo) self.create_local_file(dest_path, repo) # ==================================================================================== def reposync_cmd(self) -> str: """ Determine reposync command :return: The path to the reposync command. If dnf exists it is used instead of reposync. """ cmd = None # reposync command if os.path.exists("/usr/bin/dnf"): cmd = "/usr/bin/dnf reposync" elif os.path.exists("/usr/bin/reposync"): cmd = "/usr/bin/reposync" else: # Warn about not having yum-utils. We don't want to require it in the package because Fedora 22+ has moved # to dnf. utils.die("no /usr/bin/reposync found, please install yum-utils") return cmd # ==================================================================================== def rhn_sync(self, repo): """ Handle mirroring of RHN repos. :param repo: The repo object to synchronize. """ # reposync command cmd = self.reposync_cmd() # flag indicating not to pull the whole repo has_rpm_list = False # detect cases that require special handling if repo.rpm_list != "" and repo.rpm_list != []: has_rpm_list = True # Create yum config file for use by reposync # FIXME: don't hardcode dest_path = os.path.join(self.settings.webdir + "/repo_mirror", repo.name) temp_path = os.path.join(dest_path, ".origin") if not os.path.isdir(temp_path): # FIXME: there's a chance this might break the RHN D/L case os.makedirs(temp_path) # how we invoke reposync depends on whether this is RHN content or not. # This is the somewhat more-complex RHN case. # NOTE: this requires that you have entitlements for the server and you give the mirror as rhn://$channelname if not repo.mirror_locally: utils.die("rhn:// repos do not work with --mirror-locally=1") if has_rpm_list: self.logger.warning("warning: --rpm-list is not supported for RHN content") rest = repo.mirror[6:] # everything after rhn:// cmd = "%s %s --repo=%s -p %s" % (cmd, self.rflags, pipes.quote(rest), pipes.quote(self.settings.webdir + "/repo_mirror")) if repo.name != rest: args = {"name": repo.name, "rest": rest} utils.die("ERROR: repository %(name)s needs to be renamed %(rest)s as the name of the cobbler repository " "must match the name of the RHN channel" % args) arch = repo.arch.value if arch == "i386": # Counter-intuitive, but we want the newish kernels too arch = "i686" if arch != "": cmd = "%s -a %s" % (cmd, arch) # Now regardless of whether we're doing yumdownloader or reposync or whether the repo was http://, ftp://, or # rhn://, execute all queued commands here. Any failure at any point stops the operation. if repo.mirror_locally: utils.subprocess_call(self.logger, cmd) # Some more special case handling for RHN. Create the config file now, because the directory didn't exist # earlier. self.create_local_file(temp_path, repo, output=False) # Now run createrepo to rebuild the index if repo.mirror_locally: repo_walker(dest_path, self.createrepo_walker, repo) # Create the config file the hosts will use to access the repository. self.create_local_file(dest_path, repo) # ==================================================================================== def gen_urlgrab_ssl_opts(self, yumopts) -> Union[str, bool]: """ This function translates yum repository options into the appropriate options for python-requests :param yumopts: The options to convert. :return: A tuple with the cert and a boolean if it should be verified or not. """ # use SSL options if specified in yum opts cert = None verify = False if 'sslclientkey' and 'sslclientcert' in yumopts: cert = (yumopts['sslclientcert'], yumopts['sslclientkey']) # Note that the default of requests is to verify the peer and host but the default here is NOT to verify them # unless sslverify is explicitly set to 1 in yumopts. if 'sslverify' in yumopts: if yumopts['sslverify'] == 1: verify = True else: verify = False return (cert, verify) # ==================================================================================== def yum_sync(self, repo): """ Handle copying of http:// and ftp:// yum repos. :param repo: The yum reporitory to sync. """ # create the config file the hosts will use to access the repository. repo_mirror = repo.mirror.strip() dest_path = os.path.join(self.settings.webdir + "/repo_mirror", repo.name.strip()) self.create_local_file(dest_path, repo) if not repo.mirror_locally: return # command to run cmd = self.reposync_cmd() # flag indicating not to pull the whole repo has_rpm_list = False # detect cases that require special handling if repo.rpm_list != "" and repo.rpm_list != []: has_rpm_list = True # create yum config file for use by reposync temp_path = os.path.join(dest_path, ".origin") if not os.path.isdir(temp_path): # FIXME: there's a chance this might break the RHN D/L case os.makedirs(temp_path) temp_file = self.create_local_file(temp_path, repo, output=False) if not has_rpm_list: # If we have not requested only certain RPMs, use reposync cmd = "%s %s --config=%s --repoid=%s -p %s" \ % (cmd, self.rflags, temp_file, pipes.quote(repo.name), pipes.quote(self.settings.webdir + "/repo_mirror")) if repo.arch != "": if repo.arch == RepoArchs.I386: # Counter-intuitive, but we want the newish kernels too cmd = "%s -a i686" % (cmd) else: cmd = "%s -a %s" % (cmd, repo.arch.value) else: # Create the output directory if it doesn't exist if not os.path.exists(dest_path): os.makedirs(dest_path) use_source = "" if repo.arch == "src": use_source = "--source" # Older yumdownloader sometimes explodes on --resolvedeps if this happens to you, upgrade yum & yum-utils extra_flags = self.settings.yumdownloader_flags cmd = "/usr/bin/dnf download" cmd = "%s %s %s --disablerepo=* --enablerepo=%s -c %s --destdir=%s %s" \ % (cmd, extra_flags, use_source, pipes.quote(repo.name), temp_file, pipes.quote(dest_path), " ".join(repo.rpm_list)) # Now regardless of whether we're doing yumdownloader or reposync or whether the repo was http://, ftp://, or # rhn://, execute all queued commands here. Any failure at any point stops the operation. rc = utils.subprocess_call(self.logger, cmd) if rc != 0: utils.die("cobbler reposync failed") # download any metadata we can use proxy = None if repo.proxy == '<<inherit>>': proxy = self.settings.proxy_url_ext elif repo.proxy != '<<None>>' and repo.proxy != '': proxy = repo.proxy (cert, verify) = self.gen_urlgrab_ssl_opts(repo.yumopts) # FIXME: These two variables were deleted repodata_path = "" repomd_path = "" if os.path.exists(repodata_path) and not os.path.isfile(repomd_path): shutil.rmtree(repodata_path, ignore_errors=False, onerror=None) h = librepo.Handle() r = librepo.Result() h.setopt(librepo.LRO_REPOTYPE, librepo.LR_YUMREPO) h.setopt(librepo.LRO_CHECKSUM, True) if os.path.isfile(repomd_path): h.setopt(librepo.LRO_LOCAL, True) h.setopt(librepo.LRO_URLS, [temp_path]) h.setopt(librepo.LRO_IGNOREMISSING, True) try: h.perform(r) except librepo.LibrepoException as e: utils.die("librepo error: " + temp_path + " - " + e.args[1]) h.setopt(librepo.LRO_LOCAL, False) h.setopt(librepo.LRO_URLS, []) h.setopt(librepo.LRO_IGNOREMISSING, False) h.setopt(librepo.LRO_UPDATE, True) h.setopt(librepo.LRO_DESTDIR, temp_path) if repo.mirror_type == "metalink": h.setopt(librepo.LRO_METALINKURL, repo_mirror) elif repo.mirror_type == "mirrorlist": h.setopt(librepo.LRO_MIRRORLISTURL, repo_mirror) elif repo.mirror_type == "baseurl": h.setopt(librepo.LRO_URLS, [repo_mirror]) if verify: h.setopt(librepo.LRO_SSLVERIFYPEER, True) h.setopt(librepo.LRO_SSLVERIFYHOST, True) if cert: sslclientcert, sslclientkey = cert h.setopt(librepo.LRO_SSLCLIENTCERT, sslclientcert) h.setopt(librepo.LRO_SSLCLIENTKEY, sslclientkey) if proxy: h.setopt(librepo.LRO_PROXY, proxy) h.setopt(librepo.LRO_PROXYTYPE, librepo.PROXY_HTTP) try: h.perform(r) except librepo.LibrepoException as e: utils.die("librepo error: " + temp_path + " - " + e.args[1]) # now run createrepo to rebuild the index if repo.mirror_locally: repo_walker(dest_path, self.createrepo_walker, repo) # ==================================================================================== def apt_sync(self, repo): """ Handle copying of http:// and ftp:// debian repos. :param repo: The apt repository to sync. """ # Warn about not having mirror program. mirror_program = "/usr/bin/debmirror" if not os.path.exists(mirror_program): utils.die("no %s found, please install it" % (mirror_program)) # command to run cmd = "" # detect cases that require special handling if repo.rpm_list != "" and repo.rpm_list != []: utils.die("has_rpm_list not yet supported on apt repos") if not repo.arch: utils.die("Architecture is required for apt repositories") # built destination path for the repo dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) if repo.mirror_locally: # NOTE: Dropping @@suite@@ replace as it is also dropped from "from manage_import_debian"_ubuntu.py due that # repo has no os_version attribute. If it is added again it will break the Web UI! # mirror = repo.mirror.replace("@@suite@@",repo.os_version) mirror = repo.mirror idx = mirror.find("://") method = mirror[:idx] mirror = mirror[idx + 3:] idx = mirror.find("/") host = mirror[:idx] mirror = mirror[idx:] dists = ",".join(repo.apt_dists) components = ",".join(repo.apt_components) mirror_data = "--method=%s --host=%s --root=%s --dist=%s --section=%s" \ % (pipes.quote(method), pipes.quote(host), pipes.quote(mirror), pipes.quote(dists), pipes.quote(components)) rflags = "--nocleanup" for x in repo.yumopts: if repo.yumopts[x]: rflags += " %s %s" % (x, repo.yumopts[x]) else: rflags += " %s" % x cmd = "%s %s %s %s" % (mirror_program, rflags, mirror_data, dest_path) cmd = "%s %s %s %s" % (mirror_program, rflags, mirror_data, pipes.quote(dest_path)) if repo.arch == RepoArchs.SRC: cmd = "%s --source" % cmd else: arch = repo.arch.value if arch == "x86_64": arch = "amd64" # FIX potential arch errors cmd = "%s --nosource -a %s" % (cmd, arch) # Set's an environment variable for subprocess, otherwise debmirror will fail as it needs this variable to # exist. # FIXME: might this break anything? So far it doesn't os.putenv("HOME", "/var/lib/cobbler") rc = utils.subprocess_call(cmd) if rc != 0: utils.die("cobbler reposync failed") def create_local_file(self, dest_path: str, repo, output: bool = True): """ Creates Yum config files for use by reposync Two uses: (A) output=True, Create local files that can be used with yum on provisioned clients to make use of this mirror. (B) output=False, Create a temporary file for yum to feed into yum for mirroring :param dest_path: The destination path to create the file at. :param repo: The repository object to create a file for. :param output: See described above. :return: The name of the file which was written. """ # The output case will generate repo configuration files which are usable for the installed systems. They need # to be made compatible with --server-override which means they are actually templates, which need to be # rendered by a Cobbler-sync on per profile/system basis. if output: fname = os.path.join(dest_path, "config.repo") else: fname = os.path.join(dest_path, "%s.repo" % repo.name) self.logger.debug("creating: %s" % fname) if not os.path.exists(dest_path): utils.mkdir(dest_path) config_file = open(fname, "w+") if not output: config_file.write("[main]\nreposdir=/dev/null\n") config_file.write("[%s]\n" % repo.name) config_file.write("name=%s\n" % repo.name) optenabled = False optgpgcheck = False if output: if repo.mirror_locally: line = "baseurl=http://${http_server}/cobbler/repo_mirror/%s\n" % (repo.name) else: mstr = repo.mirror if mstr.startswith("/"): mstr = "file://%s" % mstr line = "baseurl=%s\n" % mstr config_file.write(line) # User may have options specific to certain yum plugins add them to the file for x in repo.yumopts: config_file.write("%s=%s\n" % (x, repo.yumopts[x])) if x == "enabled": optenabled = True if x == "gpgcheck": optgpgcheck = True else: mstr = repo.mirror if mstr.startswith("/"): mstr = "file://%s" % mstr line = repo.mirror_type + "=%s\n" % mstr if self.settings.http_port not in (80, '80'): http_server = "%s:%s" % (self.settings.server, self.settings.http_port) else: http_server = self.settings.server line = line.replace("@@server@@", http_server) config_file.write(line) config_proxy = None if repo.proxy == '<<inherit>>': config_proxy = self.settings.proxy_url_ext elif repo.proxy != '' and repo.proxy != '<<None>>': config_proxy = repo.proxy if config_proxy is not None: config_file.write("proxy=%s\n" % config_proxy) if 'exclude' in list(repo.yumopts.keys()): self.logger.debug("excluding: %s" % repo.yumopts['exclude']) config_file.write("exclude=%s\n" % repo.yumopts['exclude']) if not optenabled: config_file.write("enabled=1\n") config_file.write("priority=%s\n" % repo.priority) # FIXME: potentially might want a way to turn this on/off on a per-repo basis if not optgpgcheck: config_file.write("gpgcheck=0\n") # user may have options specific to certain yum plugins # add them to the file for x in repo.yumopts: config_file.write("%s=%s\n" % (x, repo.yumopts[x])) if x == "enabled": optenabled = True if x == "gpgcheck": optgpgcheck = True config_file.close() return fname # ================================================================================== def update_permissions(self, repo_path): """ Verifies that permissions and contexts after an rsync are as expected. Sending proper rsync flags should prevent the need for this, though this is largely a safeguard. :param repo_path: The path to update the permissions of. """ # all_path = os.path.join(repo_path, "*") owner = "root:apache" (dist, _) = os_release() if dist == "suse": owner = "root:www" elif dist in ("debian", "ubuntu"): owner = "root:www-data" cmd1 = "chown -R " + owner + " %s" % repo_path utils.subprocess_call(cmd1) cmd2 = "chmod -R 755 %s" % repo_path utils.subprocess_call(cmd2)
OpenGenus/cosmos
refs/heads/master
code/greedy_algorithms/src/minimum_coins/minimum_coins.py
3
# Part of Cosmos by OpenGenus Foundation def minimum_coins(value, denominations): result = [] # Assuming denominations is sorted in descendig order for cur_denom in denominations: while cur_denom <= value: result.append(cur_denom) value = value - cur_denom return result # Testing def test(): scenarios = [ [100, [50, 25, 10, 5, 1], [50, 50]], [101, [50, 25, 10, 5, 1], [50, 50, 1]], [77, [50, 25, 10, 5, 1], [50, 25, 1, 1]], [38, [50, 25, 10, 5, 1], [25, 10, 1, 1, 1]], [17, [50, 25, 10, 5, 1], [10, 5, 1, 1]], [3, [50, 25, 10, 5, 1], [1, 1, 1]], [191, [100, 50, 25, 10, 5, 1], [100, 50, 25, 10, 5, 1]], ] for scenario in scenarios: actual = minimum_coins(scenario[0], scenario[1]) if actual != scenario[2]: message = "Test Failed: Value: {}, Denominations: {}, Expected Result: {}, Actual Result: {}".format( scenario[0], scenario[1], scenario[2], actual ) print(message) test()
sudosurootdev/external_chromium_org
refs/heads/L5
tools/telemetry/telemetry/__init__.py
49
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A library for cross-platform browser tests.""" import sys # Ensure Python >= 2.7. if sys.version_info < (2, 7): print >> sys.stderr, 'Need Python 2.7 or greater.' sys.exit(-1) from telemetry.util import global_hooks global_hooks.InstallHooks()
Roxling/smegod
refs/heads/master
Smegod/external/assimp-3.1.1-win-binaries/test/regression/run.py
15
#!/usr/bin/env python3 # -*- Coding: UTF-8 -*- # --------------------------------------------------------------------------- # Open Asset Import Library (ASSIMP) # --------------------------------------------------------------------------- # # Copyright (c) 2006-2010, ASSIMP Development Team # # All rights reserved. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the # following disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other # materials provided with the distribution. # # * Neither the name of the ASSIMP team, nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior # written permission of the ASSIMP Development Team. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # --------------------------------------------------------------------------- """ Run the regression test suite using the settings from settings.py. """ import sys import os import subprocess import zipfile import collections import settings import utils # ------------------------------------------------------------------------------- EXPECTED_FAILURE_NOT_MET, DATABASE_LENGTH_MISMATCH, \ DATABASE_VALUE_MISMATCH, IMPORT_FAILURE, \ FILE_NOT_READABLE, COMPARE_SUCCESS = range(6) messages = collections.defaultdict(lambda: "<unknown", { EXPECTED_FAILURE_NOT_MET: """Unexpected success during import\n\ \tReturn code was 0""", DATABASE_LENGTH_MISMATCH: """Database mismatch: lengths don't match\n\ \tExpected: {0} Actual: {1}""", DATABASE_VALUE_MISMATCH: """Database mismatch: """, IMPORT_FAILURE: """Unexpected failure during import\n\ \tReturn code was {0}""", FILE_NOT_READABLE: """Unexpected failure reading file""", COMPARE_SUCCESS: """Results match archived reference dump in database\n\ \tNumber of bytes compared: {0}""" }) outfilename_output = "run_regression_suite_output.txt" outfilename_failur = "run_regression_suite_failures.csv" # ------------------------------------------------------------------------------- class results: """ Handle formatting of results""" def __init__(self, zipin): """Init, given a ZIPed database """ self.failures = [] self.success = [] self.zipin = zipin def fail(self, failfile, filename_expect, pp, msg, *args): """ Report failure of a sub-test File f failed a test for pp config pp, failure notice is msg, *args is format()ting args for msg """ print("[FAILURE] " + messages[msg].format(*args)) self.failures.append((failfile, filename_expect, pp)) def ok(self, f, pp, msg, *args): """ Report success of a sub-test File f passed the test, msg is a happy success note, *args is format()ing args for msg. """ print("[SUCCESS] " + messages[msg].format(*args)) self.success.append(f) def report_results(self): """Write results to ../results/run_regression_suite_failures.txt""" print("\n" + ('='*60) + "\n" + "SUCCESS: {0}\nFAILURE: {1}\nPercentage good: {2}".format( len(self.success), len(self.failures), len(self.success)/(len(self.success)+len(self.failures)) ) + "\n" + ('='*60) + "\n") with open(os.path.join('..', 'results',outfilename_failur), "wt") as f: f.write("ORIGINAL FILE;EXPECTED DUMP\n") f.writelines(map( lambda x: x[0] + ' ' + x[2] + ";" + x[1] + "\n", self.failures)) if self.failures: print("\nSee " + settings.results + "\\" + outfilename_failur + " for more details\n\n") # ------------------------------------------------------------------------------- def mkoutputdir_andgetpath(fullpath, myhash, app): outfile = os.path.join(settings.results, "tmp", os.path.split(fullpath)[1] + "_" + myhash) try: os.mkdir(outfile) except OSError: pass outfile = os.path.join(outfile, app) return outfile # ------------------------------------------------------------------------------- def process_dir(d, outfile_results, zipin, result): shellparams = {'stdout':outfile_results, 'stderr':outfile_results, 'shell':False} print("Processing directory " + d) for f in os.listdir(d): fullpath = os.path.join(d, f) if os.path.isdir(fullpath) and not f == ".svn": process_dir(fullpath, outfile_results, zipin, result) continue for pppreset in settings.pp_configs_to_test: filehash = utils.hashing(fullpath, pppreset) failure = False try: input_expected = zipin.open(filehash, "r").read() # empty dump files indicate 'expected import failure' if not len(input_expected): failure = True except KeyError: #print("Didn't find "+fullpath+" (Hash is "+filehash+") in database") continue # Ignore extensions via settings.py configured list # todo: Fix for multi dot extensions like .skeleton.xml ext = os.path.splitext(fullpath)[1].lower() if ext != "" and ext in settings.exclude_extensions: continue print("-"*60 + "\n " + os.path.realpath(fullpath) + " pp: " + pppreset) outfile_actual = mkoutputdir_andgetpath(fullpath, filehash, "ACTUAL") outfile_expect = mkoutputdir_andgetpath(fullpath, filehash, "EXPECT") outfile_results.write("assimp dump "+"-"*80+"\n") outfile_results.flush() command = [utils.assimp_bin_path,"dump",fullpath,outfile_actual,"-b","-s","-l"]+pppreset.split() r = subprocess.call(command, **shellparams) if r and not failure: result.fail(fullpath, outfile_expect, pppreset, IMPORT_FAILURE, r) continue elif failure and not r: result.fail(fullpath, outfile_expect, pppreset, EXPECTED_FAILURE_NOT_MET) continue with open(outfile_expect, "wb") as s: s.write(input_expected) try: with open(outfile_actual, "rb") as s: input_actual = s.read() except IOError: continue if len(input_expected) != len(input_actual): result.fail(fullpath, outfile_expect, pppreset, DATABASE_LENGTH_MISMATCH, len(input_expected), len(input_actual)) continue outfile_results.write("assimp cmpdump "+"-"*80+"\n") outfile_results.flush() command = [utils.assimp_bin_path,'cmpdump',outfile_actual,outfile_expect] if subprocess.call(command, **shellparams) != 0: result.fail(fullpath, outfile_expect, pppreset, DATABASE_VALUE_MISMATCH) continue result.ok(fullpath, pppreset, COMPARE_SUCCESS, len(input_expected)) # ------------------------------------------------------------------------------- def del_folder_with_contents(folder): for root, dirs, files in os.walk(folder, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) # ------------------------------------------------------------------------------- def run_test(): utils.find_assimp_or_die() tmp_target_path = os.path.join(settings.results, "tmp") try: os.mkdir(tmp_target_path) except OSError as oerr: # clear contents if tmp folder exists already del_folder_with_contents(tmp_target_path) try: zipin = zipfile.ZipFile(settings.database_name + ".zip", "r", zipfile.ZIP_STORED) except IOError: print("Regression database ", settings.database_name, ".zip was not found") return res = results(zipin) with open(os.path.join(settings.results, outfilename_output), "wt") as outfile: for tp in settings.model_directories: process_dir(tp, outfile, zipin, res) res.report_results() # ------------------------------------------------------------------------------- if __name__ == "__main__": run_test() input("Press any key to continue ...") # vim: ai ts=4 sts=4 et sw=4
myvoice-nigeria/myvoice
refs/heads/develop
myvoice/clinics/migrations/0006_auto__add_service.py
1
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Service' db.create_table(u'clinics_service', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=128)), ('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50)), )) db.send_create_signal(u'clinics', ['Service']) def backwards(self, orm): # Deleting model 'Service' db.delete_table(u'clinics_service') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'clinics.clinic': { 'Meta': {'object_name': 'Clinic'}, 'category': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rapidsms.Contact']", 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_renovated': ('django.db.models.fields.CharField', [], {'max_length': '4', 'blank': 'True'}), 'lga': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'lga_rank': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'location': ('django.contrib.gis.db.models.fields.PointField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'pbf_rank': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'town': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'ward': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'year_opened': ('django.db.models.fields.CharField', [], {'max_length': '4', 'blank': 'True'}) }, u'clinics.clinicstaff': { 'Meta': {'object_name': 'ClinicStaff'}, 'clinic': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['clinics.Clinic']"}), 'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rapidsms.Contact']", 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_manager': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'staff_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'year_started': ('django.db.models.fields.CharField', [], {'max_length': '4', 'blank': 'True'}) }, u'clinics.clinicstatistic': { 'Meta': {'unique_together': "[('clinic', 'statistic', 'month')]", 'object_name': 'ClinicStatistic'}, 'clinic': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['clinics.Clinic']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'float_value': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'int_value': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'month': ('django.db.models.fields.DateField', [], {}), 'rank': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'statistic': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['statistics.Statistic']"}), 'text_value': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'clinics.patient': { 'Meta': {'object_name': 'Patient'}, 'clinic': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['clinics.Clinic']"}), 'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rapidsms.Contact']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}) }, u'clinics.region': { 'Meta': {'unique_together': "(('external_id', 'type'),)", 'object_name': 'Region'}, 'alternate_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'boundary': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}), 'external_id': ('django.db.models.fields.IntegerField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'type': ('django.db.models.fields.CharField', [], {'default': "'lga'", 'max_length': '16'}) }, u'clinics.visit': { 'Meta': {'object_name': 'Visit'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'patient': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['clinics.Patient']"}), 'service_type': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'staff': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['clinics.ClinicStaff']", 'null': 'True', 'blank': 'True'}), 'visit_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, u'clinics.service': { 'Meta': {'object_name': 'Service'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'rapidsms.contact': { 'Meta': {'object_name': 'Contact'}, 'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '6', 'blank': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'statistics.statistic': { 'Meta': {'object_name': 'Statistic'}, 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['statistics.StatisticGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'statistic_type': ('django.db.models.fields.CharField', [], {'max_length': '32'}) }, u'statistics.statisticgroup': { 'Meta': {'object_name': 'StatisticGroup'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}) } } complete_apps = ['clinics']
you21979/phantomjs
refs/heads/2.0
src/breakpad/src/tools/gyp/test/variables/gyptest-commands-repeated.py
138
#!/usr/bin/env python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Test variable expansion of '<!()' syntax commands where they are evaluated more then once.. """ import os import TestGyp test = TestGyp.TestGyp(format='gypd') expect = test.read('commands-repeated.gyp.stdout') # Set $HOME so that gyp doesn't read the user's actual # ~/.gyp/include.gypi file, which may contain variables # and other settings that would change the output. os.environ['HOME'] = test.workpath() test.run_gyp('commands-repeated.gyp', '--debug', 'variables', '--debug', 'general', stdout=expect) # Verify the commands-repeated.gypd against the checked-in expected contents. # # Normally, we should canonicalize line endings in the expected # contents file setting the Subversion svn:eol-style to native, # but that would still fail if multiple systems are sharing a single # workspace on a network-mounted file system. Consequently, we # massage the Windows line endings ('\r\n') in the output to the # checked-in UNIX endings ('\n'). contents = test.read('commands-repeated.gypd').replace('\r\n', '\n') expect = test.read('commands-repeated.gypd.golden') if not test.match(contents, expect): print "Unexpected contents of `commands-repeated.gypd'" self.diff(expect, contents, 'commands-repeated.gypd ') test.fail_test() test.pass_test()
RickyCook/DockCI
refs/heads/master
dockci/models/base.py
2
""" Base model classes, mixins """ class RepoFsMixin(object): """ Mixin to add ``display_repo`` and ``command_repo`` properties """ @property def display_repo(self): """ Repo, redacted for display """ return self.repo_fs.format( token_key='****', ) @property def command_repo(self): """ Repo, with credentials substituted in """ try: token_key = self.external_auth_token.key except AttributeError: token_key = '' return self.repo_fs.format( token_key=token_key, ) @property def repo_fs(self): """ Format string for the repo. The ``token_key`` attribute may be substituted with the OAuth token """ raise NotImplementedError("Must override repo_fs property") @property def external_auth_token(self): """ OAuthToken for the object to use in ``command_repo`` """ raise NotImplementedError("Must override external_auth_token property")
dednal/chromium.src
refs/heads/nw12
native_client_sdk/src/tools/lib/elf.py
100
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Helper script for extracting information from ELF files""" import struct class Error(Exception): '''Local Error class for this file.''' pass def ParseElfHeader(path): """Determine properties of a nexe by parsing elf header. Return tuple of architecture and boolean signalling whether the executable is dynamic (has INTERP header) or static. """ # From elf.h: # typedef struct # { # unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */ # Elf64_Half e_type; /* Object file type */ # Elf64_Half e_machine; /* Architecture */ # ... # } Elf32_Ehdr; elf_header_format = '16s2H' elf_header_size = struct.calcsize(elf_header_format) with open(path, 'rb') as f: header = f.read(elf_header_size) try: header = struct.unpack(elf_header_format, header) except struct.error: raise Error("error parsing elf header: %s" % path) e_ident, _, e_machine = header[:3] elf_magic = '\x7fELF' if e_ident[:4] != elf_magic: raise Error('Not a valid NaCl executable: %s' % path) e_machine_mapping = { 3 : 'x86-32', 8 : 'mips32', 40 : 'arm', 62 : 'x86-64' } if e_machine not in e_machine_mapping: raise Error('Unknown machine type: %s' % e_machine) # Set arch based on the machine type in the elf header arch = e_machine_mapping[e_machine] # Now read the full header in either 64bit or 32bit mode dynamic = IsDynamicElf(path, arch == 'x86-64') return arch, dynamic def IsDynamicElf(path, is64bit): """Examine an elf file to determine if it is dynamically linked or not. This is determined by searching the program headers for a header of type PT_INTERP. """ if is64bit: elf_header_format = '16s2HI3QI3H' else: elf_header_format = '16s2HI3II3H' elf_header_size = struct.calcsize(elf_header_format) with open(path, 'rb') as f: header = f.read(elf_header_size) header = struct.unpack(elf_header_format, header) p_header_offset = header[5] p_header_entry_size = header[9] num_p_header = header[10] f.seek(p_header_offset) p_headers = f.read(p_header_entry_size*num_p_header) # Read the first word of each Phdr to find out its type. # # typedef struct # { # Elf32_Word p_type; /* Segment type */ # ... # } Elf32_Phdr; elf_phdr_format = 'I' PT_INTERP = 3 while p_headers: p_header = p_headers[:p_header_entry_size] p_headers = p_headers[p_header_entry_size:] phdr_type = struct.unpack(elf_phdr_format, p_header[:4])[0] if phdr_type == PT_INTERP: return True return False
frouty/odoo_oph
refs/heads/dev_70
addons/mail/tests/test_invite.py
57
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.addons.mail.tests.test_mail_base import TestMailBase class test_invite(TestMailBase): def test_00_basic_invite(self): cr, uid = self.cr, self.uid mail_invite = self.registry('mail.wizard.invite') # Do: create a mail_wizard_invite, validate it self._init_mock_build_email() context = {'default_res_model': 'mail.group', 'default_res_id': self.group_pigs_id} mail_invite_id = mail_invite.create(cr, self.user_raoul_id, {'partner_ids': [(4, self.partner_bert_id)]}, context) mail_invite.add_followers(cr, self.user_raoul_id, [mail_invite_id], {'default_model': 'mail.group', 'default_res_id': 0}) # Test: Pigs followers should contain Admin, Bert self.group_pigs.refresh() follower_ids = [follower.id for follower in self.group_pigs.message_follower_ids] self.assertEqual(set(follower_ids), set([self.partner_admin_id, self.partner_bert_id]), 'Pigs followers after invite is incorrect') # Test: (pretend to) send email and check subject, body self.assertEqual(len(self._build_email_kwargs_list), 1, 'sent email number incorrect, should be only for Bert') for sent_email in self._build_email_kwargs_list: self.assertEqual(sent_email.get('subject'), 'Invitation to follow Pigs', 'subject of invitation email is incorrect') self.assertTrue('You have been invited to follow Pigs' in sent_email.get('body'), 'body of invitation email is incorrect')
pranavj1001/LearnLanguages
refs/heads/master
python/GraphAlgorithms/BellmanFord/Vertex.py
2
import sys class Vertex(object): # constructor # provides the basic structure of the vertex def __init__(self, name): self.name = name self.predecessor = None self.neighbourList = [] # initially minDistance = the largest positive integer supported by the platform’s Py_ssize_t type self.minDistance = sys.maxsize
schwarz/youtube-dl
refs/heads/master
youtube_dl/extractor/videolecturesnet.py
64
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( find_xpath_attr, int_or_none, parse_duration, unified_strdate, ) class VideoLecturesNetIE(InfoExtractor): _VALID_URL = r'http://(?:www\.)?videolectures\.net/(?P<id>[^/#?]+)/*(?:[#?].*)?$' IE_NAME = 'videolectures.net' _TEST = { 'url': 'http://videolectures.net/promogram_igor_mekjavic_eng/', 'info_dict': { 'id': 'promogram_igor_mekjavic_eng', 'ext': 'mp4', 'title': 'Automatics, robotics and biocybernetics', 'description': 'md5:815fc1deb6b3a2bff99de2d5325be482', 'upload_date': '20130627', 'duration': 565, 'thumbnail': 're:http://.*\.jpg', }, } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') smil_url = 'http://videolectures.net/%s/video/1/smil.xml' % video_id smil = self._download_xml(smil_url, video_id) title = find_xpath_attr(smil, './/meta', 'name', 'title').attrib['content'] description_el = find_xpath_attr(smil, './/meta', 'name', 'abstract') description = ( None if description_el is None else description_el.attrib['content']) upload_date = unified_strdate( find_xpath_attr(smil, './/meta', 'name', 'date').attrib['content']) switch = smil.find('.//switch') duration = parse_duration(switch.attrib.get('dur')) thumbnail_el = find_xpath_attr(switch, './image', 'type', 'thumbnail') thumbnail = ( None if thumbnail_el is None else thumbnail_el.attrib.get('src')) formats = [] for v in switch.findall('./video'): proto = v.attrib.get('proto') if proto not in ['http', 'rtmp']: continue f = { 'width': int_or_none(v.attrib.get('width')), 'height': int_or_none(v.attrib.get('height')), 'filesize': int_or_none(v.attrib.get('size')), 'tbr': int_or_none(v.attrib.get('systemBitrate')) / 1000.0, 'ext': v.attrib.get('ext'), } src = v.attrib['src'] if proto == 'http': if self._is_valid_url(src, video_id): f['url'] = src formats.append(f) elif proto == 'rtmp': f.update({ 'url': v.attrib['streamer'], 'play_path': src, 'rtmp_real_time': True, }) formats.append(f) self._sort_formats(formats) return { 'id': video_id, 'title': title, 'description': description, 'upload_date': upload_date, 'duration': duration, 'thumbnail': thumbnail, 'formats': formats, }
houssine78/vertical-distribution-circuits
refs/heads/9.0
distribution_circuits_base/models/res_partner.py
1
# -*- coding: utf-8 -*- from openerp import api, fields, models, _ class ResPartner(models.Model): _inherit = "res.partner" is_gac = fields.Boolean(string="Est un GAC") is_raliment_point = fields.Boolean(string="Est un Point de Raliment") is_delivery_point = fields.Boolean(string="Est un Point de livraison") raliment_point_id = fields.Many2one('res.partner', string="Point de Raliment", domain=[('is_raliment_point','=',True)]) raliment_point_manager = fields.Many2one('res.users', string="Raliment point responsible", domain=[('share','=',False)]) delivery_point_id = fields.Many2one('res.partner', string="Delivery Point", domain=[('is_delivery_point','=',True)]) def get_delivery_address(self): if len(self.child_ids) > 0: return self.env['res.partner'].search([('id','in',self.child_ids.ids),('type','=',"delivery")], limit=1) def get_delivery_points(self): return self.env['res.partner'].search([('is_delivery_point','=',True)]) def get_raliment_points(self): return self.env['res.partner'].search([('is_raliment_point','=',True)])
40223151/2014c2g9
refs/heads/master
wsgi/static/Brython2.1.0-20140419-113919/Lib/_codecs.py
107
def ascii_decode(*args,**kw): pass def ascii_encode(*args,**kw): pass def charbuffer_encode(*args,**kw): pass def charmap_build(*args,**kw): pass def charmap_decode(*args,**kw): pass def charmap_encode(*args,**kw): pass def decode(*args,**kw): """decode(obj, [encoding[,errors]]) -> object Decodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle ValueErrors.""" pass def encode(*args,**kw): """encode(obj, [encoding[,errors]]) -> object Encodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle ValueErrors.""" pass def escape_decode(*args,**kw): pass def escape_encode(*args,**kw): pass def latin_1_decode(*args,**kw): pass def latin_1_encode(*args,**kw): pass def lookup(encoding): """lookup(encoding) -> CodecInfo Looks up a codec tuple in the Python codec registry and returns a CodecInfo object.""" print('_codecs lookup',encoding) return encoding def lookup_error(*args,**kw): """lookup_error(errors) -> handler Return the error handler for the specified error handling name or raise a LookupError, if no handler exists under this name.""" pass def mbcs_decode(*args,**kw): pass def mbcs_encode(*args,**kw): pass def raw_unicode_escape_decode(*args,**kw): pass def raw_unicode_escape_encode(*args,**kw): pass def readbuffer_encode(*args,**kw): pass def register(*args,**kw): """register(search_function) Register a codec search function. Search functions are expected to take one argument, the encoding name in all lower case letters, and return a tuple of functions (encoder, decoder, stream_reader, stream_writer) (or a CodecInfo object).""" pass def register_error(*args,**kw): """register_error(errors, handler) Register the specified error handler under the name errors. handler must be a callable object, that will be called with an exception instance containing information about the location of the encoding/decoding error and must return a (replacement, new position) tuple.""" pass def unicode_escape_decode(*args,**kw): pass def unicode_escape_encode(*args,**kw): pass def unicode_internal_decode(*args,**kw): pass def unicode_internal_encode(*args,**kw): pass def utf_16_be_decode(*args,**kw): pass def utf_16_be_encode(*args,**kw): pass def utf_16_decode(*args,**kw): pass def utf_16_encode(*args,**kw): pass def utf_16_ex_decode(*args,**kw): pass def utf_16_le_decode(*args,**kw): pass def utf_16_le_encode(*args,**kw): pass def utf_32_be_decode(*args,**kw): pass def utf_32_be_encode(*args,**kw): pass def utf_32_decode(*args,**kw): pass def utf_32_encode(*args,**kw): pass def utf_32_ex_decode(*args,**kw): pass def utf_32_le_decode(*args,**kw): pass def utf_32_le_encode(*args,**kw): pass def utf_7_decode(*args,**kw): pass def utf_7_encode(*args,**kw): pass def utf_8_decode(*args,**kw): pass def utf_8_encode(*args,**kw): pass
Maikflow/django_test
refs/heads/master
lib/python2.7/site-packages/pip/_vendor/html5lib/serializer/__init__.py
1731
from __future__ import absolute_import, division, unicode_literals from .. import treewalkers from .htmlserializer import HTMLSerializer def serialize(input, tree="etree", format="html", encoding=None, **serializer_opts): # XXX: Should we cache this? walker = treewalkers.getTreeWalker(tree) if format == "html": s = HTMLSerializer(**serializer_opts) else: raise ValueError("type must be html") return s.render(walker(input), encoding)
vakaras/Memorize
refs/heads/master
bootstrap.py
44
############################################################################## # # Copyright (c) 2006 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
40123142/finalexam
refs/heads/master
static/Brython3.1.1-20150328-091302/Lib/keyword.py
761
#! /usr/bin/env python3 """Keywords (from "graminit.c") This file is automatically generated; please don't muck it up! To update the symbols in this file, 'cd' to the top directory of the python source tree after building the interpreter and run: ./python Lib/keyword.py """ __all__ = ["iskeyword", "kwlist"] kwlist = [ #--start keywords-- 'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield', #--end keywords-- ] iskeyword = frozenset(kwlist).__contains__ def main(): import sys, re args = sys.argv[1:] iptfile = args and args[0] or "Python/graminit.c" if len(args) > 1: optfile = args[1] else: optfile = "Lib/keyword.py" # scan the source file for keywords with open(iptfile) as fp: strprog = re.compile('"([^"]+)"') lines = [] for line in fp: if '{1, "' in line: match = strprog.search(line) if match: lines.append(" '" + match.group(1) + "',\n") lines.sort() # load the output skeleton from the target with open(optfile) as fp: format = fp.readlines() # insert the lines of keywords try: start = format.index("#--start keywords--\n") + 1 end = format.index("#--end keywords--\n") format[start:end] = lines except ValueError: sys.stderr.write("target does not contain format markers\n") sys.exit(1) # write the output file fp = open(optfile, 'w') fp.write(''.join(format)) fp.close() if __name__ == "__main__": main()
fo0nikens/gr-air-modes
refs/heads/master
docs/doxygen/doxyxml/generated/compoundsuper.py
348
#!/usr/bin/env python # # Generated Thu Jun 11 18:44:25 2009 by generateDS.py. # import sys import getopt from string import lower as str_lower from xml.dom import minidom from xml.dom import Node # # User methods # # Calls to the methods in these classes are generated by generateDS.py. # You can replace these methods by re-implementing the following class # in a module named generatedssuper.py. try: from generatedssuper import GeneratedsSuper except ImportError, exp: class GeneratedsSuper: def format_string(self, input_data, input_name=''): return input_data def format_integer(self, input_data, input_name=''): return '%d' % input_data def format_float(self, input_data, input_name=''): return '%f' % input_data def format_double(self, input_data, input_name=''): return '%e' % input_data def format_boolean(self, input_data, input_name=''): return '%s' % input_data # # If you have installed IPython you can uncomment and use the following. # IPython is available from http://ipython.scipy.org/. # ## from IPython.Shell import IPShellEmbed ## args = '' ## ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', ## exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: # ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit') # # Globals # ExternalEncoding = 'ascii' # # Support/utility functions. # def showIndent(outfile, level): for idx in range(level): outfile.write(' ') def quote_xml(inStr): s1 = (isinstance(inStr, basestring) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') return s1 def quote_attrib(inStr): s1 = (isinstance(inStr, basestring) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') if '"' in s1: if "'" in s1: s1 = '"%s"' % s1.replace('"', "&quot;") else: s1 = "'%s'" % s1 else: s1 = '"%s"' % s1 return s1 def quote_python(inStr): s1 = inStr if s1.find("'") == -1: if s1.find('\n') == -1: return "'%s'" % s1 else: return "'''%s'''" % s1 else: if s1.find('"') != -1: s1 = s1.replace('"', '\\"') if s1.find('\n') == -1: return '"%s"' % s1 else: return '"""%s"""' % s1 class MixedContainer: # Constants for category: CategoryNone = 0 CategoryText = 1 CategorySimple = 2 CategoryComplex = 3 # Constants for content_type: TypeNone = 0 TypeText = 1 TypeString = 2 TypeInteger = 3 TypeFloat = 4 TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value def getCategory(self): return self.category def getContenttype(self, content_type): return self.content_type def getValue(self): return self.value def getName(self): return self.name def export(self, outfile, level, name, namespace): if self.category == MixedContainer.CategoryText: outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex self.value.export(outfile, level, namespace,name) def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeInteger or \ self.content_type == MixedContainer.TypeBoolean: outfile.write('<%s>%d</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeFloat or \ self.content_type == MixedContainer.TypeDecimal: outfile.write('<%s>%f</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g</%s>' % (self.name, self.value, self.name)) def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s",\n' % \ (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') class _MemberSpec(object): def __init__(self, name='', data_type='', container=0): self.name = name self.data_type = data_type self.container = container def set_name(self, name): self.name = name def get_name(self): return self.name def set_data_type(self, data_type): self.data_type = data_type def get_data_type(self): return self.data_type def set_container(self, container): self.container = container def get_container(self): return self.container # # Data representation classes. # class DoxygenType(GeneratedsSuper): subclass = None superclass = None def __init__(self, version=None, compounddef=None): self.version = version self.compounddef = compounddef def factory(*args_, **kwargs_): if DoxygenType.subclass: return DoxygenType.subclass(*args_, **kwargs_) else: return DoxygenType(*args_, **kwargs_) factory = staticmethod(factory) def get_compounddef(self): return self.compounddef def set_compounddef(self, compounddef): self.compounddef = compounddef def get_version(self): return self.version def set_version(self, version): self.version = version def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='DoxygenType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='DoxygenType'): outfile.write(' version=%s' % (quote_attrib(self.version), )) def exportChildren(self, outfile, level, namespace_='', name_='DoxygenType'): if self.compounddef: self.compounddef.export(outfile, level, namespace_, name_='compounddef') def hasContent_(self): if ( self.compounddef is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='DoxygenType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.version is not None: showIndent(outfile, level) outfile.write('version = "%s",\n' % (self.version,)) def exportLiteralChildren(self, outfile, level, name_): if self.compounddef: showIndent(outfile, level) outfile.write('compounddef=model_.compounddefType(\n') self.compounddef.exportLiteral(outfile, level, name_='compounddef') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('version'): self.version = attrs.get('version').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'compounddef': obj_ = compounddefType.factory() obj_.build(child_) self.set_compounddef(obj_) # end class DoxygenType class compounddefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, prot=None, id=None, compoundname=None, title=None, basecompoundref=None, derivedcompoundref=None, includes=None, includedby=None, incdepgraph=None, invincdepgraph=None, innerdir=None, innerfile=None, innerclass=None, innernamespace=None, innerpage=None, innergroup=None, templateparamlist=None, sectiondef=None, briefdescription=None, detaileddescription=None, inheritancegraph=None, collaborationgraph=None, programlisting=None, location=None, listofallmembers=None): self.kind = kind self.prot = prot self.id = id self.compoundname = compoundname self.title = title if basecompoundref is None: self.basecompoundref = [] else: self.basecompoundref = basecompoundref if derivedcompoundref is None: self.derivedcompoundref = [] else: self.derivedcompoundref = derivedcompoundref if includes is None: self.includes = [] else: self.includes = includes if includedby is None: self.includedby = [] else: self.includedby = includedby self.incdepgraph = incdepgraph self.invincdepgraph = invincdepgraph if innerdir is None: self.innerdir = [] else: self.innerdir = innerdir if innerfile is None: self.innerfile = [] else: self.innerfile = innerfile if innerclass is None: self.innerclass = [] else: self.innerclass = innerclass if innernamespace is None: self.innernamespace = [] else: self.innernamespace = innernamespace if innerpage is None: self.innerpage = [] else: self.innerpage = innerpage if innergroup is None: self.innergroup = [] else: self.innergroup = innergroup self.templateparamlist = templateparamlist if sectiondef is None: self.sectiondef = [] else: self.sectiondef = sectiondef self.briefdescription = briefdescription self.detaileddescription = detaileddescription self.inheritancegraph = inheritancegraph self.collaborationgraph = collaborationgraph self.programlisting = programlisting self.location = location self.listofallmembers = listofallmembers def factory(*args_, **kwargs_): if compounddefType.subclass: return compounddefType.subclass(*args_, **kwargs_) else: return compounddefType(*args_, **kwargs_) factory = staticmethod(factory) def get_compoundname(self): return self.compoundname def set_compoundname(self, compoundname): self.compoundname = compoundname def get_title(self): return self.title def set_title(self, title): self.title = title def get_basecompoundref(self): return self.basecompoundref def set_basecompoundref(self, basecompoundref): self.basecompoundref = basecompoundref def add_basecompoundref(self, value): self.basecompoundref.append(value) def insert_basecompoundref(self, index, value): self.basecompoundref[index] = value def get_derivedcompoundref(self): return self.derivedcompoundref def set_derivedcompoundref(self, derivedcompoundref): self.derivedcompoundref = derivedcompoundref def add_derivedcompoundref(self, value): self.derivedcompoundref.append(value) def insert_derivedcompoundref(self, index, value): self.derivedcompoundref[index] = value def get_includes(self): return self.includes def set_includes(self, includes): self.includes = includes def add_includes(self, value): self.includes.append(value) def insert_includes(self, index, value): self.includes[index] = value def get_includedby(self): return self.includedby def set_includedby(self, includedby): self.includedby = includedby def add_includedby(self, value): self.includedby.append(value) def insert_includedby(self, index, value): self.includedby[index] = value def get_incdepgraph(self): return self.incdepgraph def set_incdepgraph(self, incdepgraph): self.incdepgraph = incdepgraph def get_invincdepgraph(self): return self.invincdepgraph def set_invincdepgraph(self, invincdepgraph): self.invincdepgraph = invincdepgraph def get_innerdir(self): return self.innerdir def set_innerdir(self, innerdir): self.innerdir = innerdir def add_innerdir(self, value): self.innerdir.append(value) def insert_innerdir(self, index, value): self.innerdir[index] = value def get_innerfile(self): return self.innerfile def set_innerfile(self, innerfile): self.innerfile = innerfile def add_innerfile(self, value): self.innerfile.append(value) def insert_innerfile(self, index, value): self.innerfile[index] = value def get_innerclass(self): return self.innerclass def set_innerclass(self, innerclass): self.innerclass = innerclass def add_innerclass(self, value): self.innerclass.append(value) def insert_innerclass(self, index, value): self.innerclass[index] = value def get_innernamespace(self): return self.innernamespace def set_innernamespace(self, innernamespace): self.innernamespace = innernamespace def add_innernamespace(self, value): self.innernamespace.append(value) def insert_innernamespace(self, index, value): self.innernamespace[index] = value def get_innerpage(self): return self.innerpage def set_innerpage(self, innerpage): self.innerpage = innerpage def add_innerpage(self, value): self.innerpage.append(value) def insert_innerpage(self, index, value): self.innerpage[index] = value def get_innergroup(self): return self.innergroup def set_innergroup(self, innergroup): self.innergroup = innergroup def add_innergroup(self, value): self.innergroup.append(value) def insert_innergroup(self, index, value): self.innergroup[index] = value def get_templateparamlist(self): return self.templateparamlist def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist def get_sectiondef(self): return self.sectiondef def set_sectiondef(self, sectiondef): self.sectiondef = sectiondef def add_sectiondef(self, value): self.sectiondef.append(value) def insert_sectiondef(self, index, value): self.sectiondef[index] = value def get_briefdescription(self): return self.briefdescription def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription def get_detaileddescription(self): return self.detaileddescription def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription def get_inheritancegraph(self): return self.inheritancegraph def set_inheritancegraph(self, inheritancegraph): self.inheritancegraph = inheritancegraph def get_collaborationgraph(self): return self.collaborationgraph def set_collaborationgraph(self, collaborationgraph): self.collaborationgraph = collaborationgraph def get_programlisting(self): return self.programlisting def set_programlisting(self, programlisting): self.programlisting = programlisting def get_location(self): return self.location def set_location(self, location): self.location = location def get_listofallmembers(self): return self.listofallmembers def set_listofallmembers(self, listofallmembers): self.listofallmembers = listofallmembers def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='compounddefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='compounddefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='compounddefType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='compounddefType'): if self.compoundname is not None: showIndent(outfile, level) outfile.write('<%scompoundname>%s</%scompoundname>\n' % (namespace_, self.format_string(quote_xml(self.compoundname).encode(ExternalEncoding), input_name='compoundname'), namespace_)) if self.title is not None: showIndent(outfile, level) outfile.write('<%stitle>%s</%stitle>\n' % (namespace_, self.format_string(quote_xml(self.title).encode(ExternalEncoding), input_name='title'), namespace_)) for basecompoundref_ in self.basecompoundref: basecompoundref_.export(outfile, level, namespace_, name_='basecompoundref') for derivedcompoundref_ in self.derivedcompoundref: derivedcompoundref_.export(outfile, level, namespace_, name_='derivedcompoundref') for includes_ in self.includes: includes_.export(outfile, level, namespace_, name_='includes') for includedby_ in self.includedby: includedby_.export(outfile, level, namespace_, name_='includedby') if self.incdepgraph: self.incdepgraph.export(outfile, level, namespace_, name_='incdepgraph') if self.invincdepgraph: self.invincdepgraph.export(outfile, level, namespace_, name_='invincdepgraph') for innerdir_ in self.innerdir: innerdir_.export(outfile, level, namespace_, name_='innerdir') for innerfile_ in self.innerfile: innerfile_.export(outfile, level, namespace_, name_='innerfile') for innerclass_ in self.innerclass: innerclass_.export(outfile, level, namespace_, name_='innerclass') for innernamespace_ in self.innernamespace: innernamespace_.export(outfile, level, namespace_, name_='innernamespace') for innerpage_ in self.innerpage: innerpage_.export(outfile, level, namespace_, name_='innerpage') for innergroup_ in self.innergroup: innergroup_.export(outfile, level, namespace_, name_='innergroup') if self.templateparamlist: self.templateparamlist.export(outfile, level, namespace_, name_='templateparamlist') for sectiondef_ in self.sectiondef: sectiondef_.export(outfile, level, namespace_, name_='sectiondef') if self.briefdescription: self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') if self.detaileddescription: self.detaileddescription.export(outfile, level, namespace_, name_='detaileddescription') if self.inheritancegraph: self.inheritancegraph.export(outfile, level, namespace_, name_='inheritancegraph') if self.collaborationgraph: self.collaborationgraph.export(outfile, level, namespace_, name_='collaborationgraph') if self.programlisting: self.programlisting.export(outfile, level, namespace_, name_='programlisting') if self.location: self.location.export(outfile, level, namespace_, name_='location') if self.listofallmembers: self.listofallmembers.export(outfile, level, namespace_, name_='listofallmembers') def hasContent_(self): if ( self.compoundname is not None or self.title is not None or self.basecompoundref is not None or self.derivedcompoundref is not None or self.includes is not None or self.includedby is not None or self.incdepgraph is not None or self.invincdepgraph is not None or self.innerdir is not None or self.innerfile is not None or self.innerclass is not None or self.innernamespace is not None or self.innerpage is not None or self.innergroup is not None or self.templateparamlist is not None or self.sectiondef is not None or self.briefdescription is not None or self.detaileddescription is not None or self.inheritancegraph is not None or self.collaborationgraph is not None or self.programlisting is not None or self.location is not None or self.listofallmembers is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='compounddefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('compoundname=%s,\n' % quote_python(self.compoundname).encode(ExternalEncoding)) if self.title: showIndent(outfile, level) outfile.write('title=model_.xsd_string(\n') self.title.exportLiteral(outfile, level, name_='title') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('basecompoundref=[\n') level += 1 for basecompoundref in self.basecompoundref: showIndent(outfile, level) outfile.write('model_.basecompoundref(\n') basecompoundref.exportLiteral(outfile, level, name_='basecompoundref') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('derivedcompoundref=[\n') level += 1 for derivedcompoundref in self.derivedcompoundref: showIndent(outfile, level) outfile.write('model_.derivedcompoundref(\n') derivedcompoundref.exportLiteral(outfile, level, name_='derivedcompoundref') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('includes=[\n') level += 1 for includes in self.includes: showIndent(outfile, level) outfile.write('model_.includes(\n') includes.exportLiteral(outfile, level, name_='includes') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('includedby=[\n') level += 1 for includedby in self.includedby: showIndent(outfile, level) outfile.write('model_.includedby(\n') includedby.exportLiteral(outfile, level, name_='includedby') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.incdepgraph: showIndent(outfile, level) outfile.write('incdepgraph=model_.graphType(\n') self.incdepgraph.exportLiteral(outfile, level, name_='incdepgraph') showIndent(outfile, level) outfile.write('),\n') if self.invincdepgraph: showIndent(outfile, level) outfile.write('invincdepgraph=model_.graphType(\n') self.invincdepgraph.exportLiteral(outfile, level, name_='invincdepgraph') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('innerdir=[\n') level += 1 for innerdir in self.innerdir: showIndent(outfile, level) outfile.write('model_.innerdir(\n') innerdir.exportLiteral(outfile, level, name_='innerdir') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innerfile=[\n') level += 1 for innerfile in self.innerfile: showIndent(outfile, level) outfile.write('model_.innerfile(\n') innerfile.exportLiteral(outfile, level, name_='innerfile') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innerclass=[\n') level += 1 for innerclass in self.innerclass: showIndent(outfile, level) outfile.write('model_.innerclass(\n') innerclass.exportLiteral(outfile, level, name_='innerclass') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innernamespace=[\n') level += 1 for innernamespace in self.innernamespace: showIndent(outfile, level) outfile.write('model_.innernamespace(\n') innernamespace.exportLiteral(outfile, level, name_='innernamespace') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innerpage=[\n') level += 1 for innerpage in self.innerpage: showIndent(outfile, level) outfile.write('model_.innerpage(\n') innerpage.exportLiteral(outfile, level, name_='innerpage') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innergroup=[\n') level += 1 for innergroup in self.innergroup: showIndent(outfile, level) outfile.write('model_.innergroup(\n') innergroup.exportLiteral(outfile, level, name_='innergroup') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.templateparamlist: showIndent(outfile, level) outfile.write('templateparamlist=model_.templateparamlistType(\n') self.templateparamlist.exportLiteral(outfile, level, name_='templateparamlist') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('sectiondef=[\n') level += 1 for sectiondef in self.sectiondef: showIndent(outfile, level) outfile.write('model_.sectiondef(\n') sectiondef.exportLiteral(outfile, level, name_='sectiondef') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') if self.detaileddescription: showIndent(outfile, level) outfile.write('detaileddescription=model_.descriptionType(\n') self.detaileddescription.exportLiteral(outfile, level, name_='detaileddescription') showIndent(outfile, level) outfile.write('),\n') if self.inheritancegraph: showIndent(outfile, level) outfile.write('inheritancegraph=model_.graphType(\n') self.inheritancegraph.exportLiteral(outfile, level, name_='inheritancegraph') showIndent(outfile, level) outfile.write('),\n') if self.collaborationgraph: showIndent(outfile, level) outfile.write('collaborationgraph=model_.graphType(\n') self.collaborationgraph.exportLiteral(outfile, level, name_='collaborationgraph') showIndent(outfile, level) outfile.write('),\n') if self.programlisting: showIndent(outfile, level) outfile.write('programlisting=model_.listingType(\n') self.programlisting.exportLiteral(outfile, level, name_='programlisting') showIndent(outfile, level) outfile.write('),\n') if self.location: showIndent(outfile, level) outfile.write('location=model_.locationType(\n') self.location.exportLiteral(outfile, level, name_='location') showIndent(outfile, level) outfile.write('),\n') if self.listofallmembers: showIndent(outfile, level) outfile.write('listofallmembers=model_.listofallmembersType(\n') self.listofallmembers.exportLiteral(outfile, level, name_='listofallmembers') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'compoundname': compoundname_ = '' for text__content_ in child_.childNodes: compoundname_ += text__content_.nodeValue self.compoundname = compoundname_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': obj_ = docTitleType.factory() obj_.build(child_) self.set_title(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'basecompoundref': obj_ = compoundRefType.factory() obj_.build(child_) self.basecompoundref.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'derivedcompoundref': obj_ = compoundRefType.factory() obj_.build(child_) self.derivedcompoundref.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'includes': obj_ = incType.factory() obj_.build(child_) self.includes.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'includedby': obj_ = incType.factory() obj_.build(child_) self.includedby.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'incdepgraph': obj_ = graphType.factory() obj_.build(child_) self.set_incdepgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'invincdepgraph': obj_ = graphType.factory() obj_.build(child_) self.set_invincdepgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innerdir': obj_ = refType.factory() obj_.build(child_) self.innerdir.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innerfile': obj_ = refType.factory() obj_.build(child_) self.innerfile.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innerclass': obj_ = refType.factory() obj_.build(child_) self.innerclass.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innernamespace': obj_ = refType.factory() obj_.build(child_) self.innernamespace.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innerpage': obj_ = refType.factory() obj_.build(child_) self.innerpage.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innergroup': obj_ = refType.factory() obj_.build(child_) self.innergroup.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'templateparamlist': obj_ = templateparamlistType.factory() obj_.build(child_) self.set_templateparamlist(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sectiondef': obj_ = sectiondefType.factory() obj_.build(child_) self.sectiondef.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'detaileddescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_detaileddescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'inheritancegraph': obj_ = graphType.factory() obj_.build(child_) self.set_inheritancegraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'collaborationgraph': obj_ = graphType.factory() obj_.build(child_) self.set_collaborationgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'programlisting': obj_ = listingType.factory() obj_.build(child_) self.set_programlisting(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'location': obj_ = locationType.factory() obj_.build(child_) self.set_location(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'listofallmembers': obj_ = listofallmembersType.factory() obj_.build(child_) self.set_listofallmembers(obj_) # end class compounddefType class listofallmembersType(GeneratedsSuper): subclass = None superclass = None def __init__(self, member=None): if member is None: self.member = [] else: self.member = member def factory(*args_, **kwargs_): if listofallmembersType.subclass: return listofallmembersType.subclass(*args_, **kwargs_) else: return listofallmembersType(*args_, **kwargs_) factory = staticmethod(factory) def get_member(self): return self.member def set_member(self, member): self.member = member def add_member(self, value): self.member.append(value) def insert_member(self, index, value): self.member[index] = value def export(self, outfile, level, namespace_='', name_='listofallmembersType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='listofallmembersType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='listofallmembersType'): pass def exportChildren(self, outfile, level, namespace_='', name_='listofallmembersType'): for member_ in self.member: member_.export(outfile, level, namespace_, name_='member') def hasContent_(self): if ( self.member is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='listofallmembersType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('member=[\n') level += 1 for member in self.member: showIndent(outfile, level) outfile.write('model_.member(\n') member.exportLiteral(outfile, level, name_='member') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'member': obj_ = memberRefType.factory() obj_.build(child_) self.member.append(obj_) # end class listofallmembersType class memberRefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope=None, name=None): self.virt = virt self.prot = prot self.refid = refid self.ambiguityscope = ambiguityscope self.scope = scope self.name = name def factory(*args_, **kwargs_): if memberRefType.subclass: return memberRefType.subclass(*args_, **kwargs_) else: return memberRefType(*args_, **kwargs_) factory = staticmethod(factory) def get_scope(self): return self.scope def set_scope(self, scope): self.scope = scope def get_name(self): return self.name def set_name(self, name): self.name = name def get_virt(self): return self.virt def set_virt(self, virt): self.virt = virt def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_ambiguityscope(self): return self.ambiguityscope def set_ambiguityscope(self, ambiguityscope): self.ambiguityscope = ambiguityscope def export(self, outfile, level, namespace_='', name_='memberRefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='memberRefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='memberRefType'): if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.ambiguityscope is not None: outfile.write(' ambiguityscope=%s' % (self.format_string(quote_attrib(self.ambiguityscope).encode(ExternalEncoding), input_name='ambiguityscope'), )) def exportChildren(self, outfile, level, namespace_='', name_='memberRefType'): if self.scope is not None: showIndent(outfile, level) outfile.write('<%sscope>%s</%sscope>\n' % (namespace_, self.format_string(quote_xml(self.scope).encode(ExternalEncoding), input_name='scope'), namespace_)) if self.name is not None: showIndent(outfile, level) outfile.write('<%sname>%s</%sname>\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) def hasContent_(self): if ( self.scope is not None or self.name is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='memberRefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.virt is not None: showIndent(outfile, level) outfile.write('virt = "%s",\n' % (self.virt,)) if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.ambiguityscope is not None: showIndent(outfile, level) outfile.write('ambiguityscope = %s,\n' % (self.ambiguityscope,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('scope=%s,\n' % quote_python(self.scope).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('virt'): self.virt = attrs.get('virt').value if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('ambiguityscope'): self.ambiguityscope = attrs.get('ambiguityscope').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'scope': scope_ = '' for text__content_ in child_.childNodes: scope_ += text__content_.nodeValue self.scope = scope_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue self.name = name_ # end class memberRefType class scope(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if scope.subclass: return scope.subclass(*args_, **kwargs_) else: return scope(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='scope', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='scope') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='scope'): pass def exportChildren(self, outfile, level, namespace_='', name_='scope'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='scope'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class scope class name(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if name.subclass: return name.subclass(*args_, **kwargs_) else: return name(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='name', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='name') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='name'): pass def exportChildren(self, outfile, level, namespace_='', name_='name'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='name'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class name class compoundRefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.virt = virt self.prot = prot self.refid = refid if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if compoundRefType.subclass: return compoundRefType.subclass(*args_, **kwargs_) else: return compoundRefType(*args_, **kwargs_) factory = staticmethod(factory) def get_virt(self): return self.virt def set_virt(self, virt): self.virt = virt def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='compoundRefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='compoundRefType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='compoundRefType'): if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='compoundRefType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='compoundRefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.virt is not None: showIndent(outfile, level) outfile.write('virt = "%s",\n' % (self.virt,)) if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('virt'): self.virt = attrs.get('virt').value if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class compoundRefType class reimplementType(GeneratedsSuper): subclass = None superclass = None def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if reimplementType.subclass: return reimplementType.subclass(*args_, **kwargs_) else: return reimplementType(*args_, **kwargs_) factory = staticmethod(factory) def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='reimplementType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='reimplementType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='reimplementType'): if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='reimplementType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='reimplementType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class reimplementType class incType(GeneratedsSuper): subclass = None superclass = None def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.local = local self.refid = refid if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if incType.subclass: return incType.subclass(*args_, **kwargs_) else: return incType(*args_, **kwargs_) factory = staticmethod(factory) def get_local(self): return self.local def set_local(self, local): self.local = local def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='incType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='incType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='incType'): if self.local is not None: outfile.write(' local=%s' % (quote_attrib(self.local), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='incType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='incType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.local is not None: showIndent(outfile, level) outfile.write('local = "%s",\n' % (self.local,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('local'): self.local = attrs.get('local').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class incType class refType(GeneratedsSuper): subclass = None superclass = None def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.prot = prot self.refid = refid if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if refType.subclass: return refType.subclass(*args_, **kwargs_) else: return refType(*args_, **kwargs_) factory = staticmethod(factory) def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='refType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='refType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='refType'): if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='refType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='refType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class refType class refTextType(GeneratedsSuper): subclass = None superclass = None def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid self.kindref = kindref self.external = external if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if refTextType.subclass: return refTextType.subclass(*args_, **kwargs_) else: return refTextType(*args_, **kwargs_) factory = staticmethod(factory) def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_kindref(self): return self.kindref def set_kindref(self, kindref): self.kindref = kindref def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='refTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='refTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='refTextType'): if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.kindref is not None: outfile.write(' kindref=%s' % (quote_attrib(self.kindref), )) if self.external is not None: outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) def exportChildren(self, outfile, level, namespace_='', name_='refTextType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='refTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.kindref is not None: showIndent(outfile, level) outfile.write('kindref = "%s",\n' % (self.kindref,)) if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('kindref'): self.kindref = attrs.get('kindref').value if attrs.get('external'): self.external = attrs.get('external').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class refTextType class sectiondefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, header=None, description=None, memberdef=None): self.kind = kind self.header = header self.description = description if memberdef is None: self.memberdef = [] else: self.memberdef = memberdef def factory(*args_, **kwargs_): if sectiondefType.subclass: return sectiondefType.subclass(*args_, **kwargs_) else: return sectiondefType(*args_, **kwargs_) factory = staticmethod(factory) def get_header(self): return self.header def set_header(self, header): self.header = header def get_description(self): return self.description def set_description(self, description): self.description = description def get_memberdef(self): return self.memberdef def set_memberdef(self, memberdef): self.memberdef = memberdef def add_memberdef(self, value): self.memberdef.append(value) def insert_memberdef(self, index, value): self.memberdef[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def export(self, outfile, level, namespace_='', name_='sectiondefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='sectiondefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='sectiondefType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) def exportChildren(self, outfile, level, namespace_='', name_='sectiondefType'): if self.header is not None: showIndent(outfile, level) outfile.write('<%sheader>%s</%sheader>\n' % (namespace_, self.format_string(quote_xml(self.header).encode(ExternalEncoding), input_name='header'), namespace_)) if self.description: self.description.export(outfile, level, namespace_, name_='description') for memberdef_ in self.memberdef: memberdef_.export(outfile, level, namespace_, name_='memberdef') def hasContent_(self): if ( self.header is not None or self.description is not None or self.memberdef is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='sectiondefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('header=%s,\n' % quote_python(self.header).encode(ExternalEncoding)) if self.description: showIndent(outfile, level) outfile.write('description=model_.descriptionType(\n') self.description.exportLiteral(outfile, level, name_='description') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('memberdef=[\n') level += 1 for memberdef in self.memberdef: showIndent(outfile, level) outfile.write('model_.memberdef(\n') memberdef.exportLiteral(outfile, level, name_='memberdef') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'header': header_ = '' for text__content_ in child_.childNodes: header_ += text__content_.nodeValue self.header = header_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'description': obj_ = descriptionType.factory() obj_.build(child_) self.set_description(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'memberdef': obj_ = memberdefType.factory() obj_.build(child_) self.memberdef.append(obj_) # end class sectiondefType class memberdefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, initonly=None, kind=None, volatile=None, const=None, raisexx=None, virt=None, readable=None, prot=None, explicit=None, new=None, final=None, writable=None, add=None, static=None, remove=None, sealed=None, mutable=None, gettable=None, inline=None, settable=None, id=None, templateparamlist=None, type_=None, definition=None, argsstring=None, name=None, read=None, write=None, bitfield=None, reimplements=None, reimplementedby=None, param=None, enumvalue=None, initializer=None, exceptions=None, briefdescription=None, detaileddescription=None, inbodydescription=None, location=None, references=None, referencedby=None): self.initonly = initonly self.kind = kind self.volatile = volatile self.const = const self.raisexx = raisexx self.virt = virt self.readable = readable self.prot = prot self.explicit = explicit self.new = new self.final = final self.writable = writable self.add = add self.static = static self.remove = remove self.sealed = sealed self.mutable = mutable self.gettable = gettable self.inline = inline self.settable = settable self.id = id self.templateparamlist = templateparamlist self.type_ = type_ self.definition = definition self.argsstring = argsstring self.name = name self.read = read self.write = write self.bitfield = bitfield if reimplements is None: self.reimplements = [] else: self.reimplements = reimplements if reimplementedby is None: self.reimplementedby = [] else: self.reimplementedby = reimplementedby if param is None: self.param = [] else: self.param = param if enumvalue is None: self.enumvalue = [] else: self.enumvalue = enumvalue self.initializer = initializer self.exceptions = exceptions self.briefdescription = briefdescription self.detaileddescription = detaileddescription self.inbodydescription = inbodydescription self.location = location if references is None: self.references = [] else: self.references = references if referencedby is None: self.referencedby = [] else: self.referencedby = referencedby def factory(*args_, **kwargs_): if memberdefType.subclass: return memberdefType.subclass(*args_, **kwargs_) else: return memberdefType(*args_, **kwargs_) factory = staticmethod(factory) def get_templateparamlist(self): return self.templateparamlist def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_definition(self): return self.definition def set_definition(self, definition): self.definition = definition def get_argsstring(self): return self.argsstring def set_argsstring(self, argsstring): self.argsstring = argsstring def get_name(self): return self.name def set_name(self, name): self.name = name def get_read(self): return self.read def set_read(self, read): self.read = read def get_write(self): return self.write def set_write(self, write): self.write = write def get_bitfield(self): return self.bitfield def set_bitfield(self, bitfield): self.bitfield = bitfield def get_reimplements(self): return self.reimplements def set_reimplements(self, reimplements): self.reimplements = reimplements def add_reimplements(self, value): self.reimplements.append(value) def insert_reimplements(self, index, value): self.reimplements[index] = value def get_reimplementedby(self): return self.reimplementedby def set_reimplementedby(self, reimplementedby): self.reimplementedby = reimplementedby def add_reimplementedby(self, value): self.reimplementedby.append(value) def insert_reimplementedby(self, index, value): self.reimplementedby[index] = value def get_param(self): return self.param def set_param(self, param): self.param = param def add_param(self, value): self.param.append(value) def insert_param(self, index, value): self.param[index] = value def get_enumvalue(self): return self.enumvalue def set_enumvalue(self, enumvalue): self.enumvalue = enumvalue def add_enumvalue(self, value): self.enumvalue.append(value) def insert_enumvalue(self, index, value): self.enumvalue[index] = value def get_initializer(self): return self.initializer def set_initializer(self, initializer): self.initializer = initializer def get_exceptions(self): return self.exceptions def set_exceptions(self, exceptions): self.exceptions = exceptions def get_briefdescription(self): return self.briefdescription def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription def get_detaileddescription(self): return self.detaileddescription def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription def get_inbodydescription(self): return self.inbodydescription def set_inbodydescription(self, inbodydescription): self.inbodydescription = inbodydescription def get_location(self): return self.location def set_location(self, location): self.location = location def get_references(self): return self.references def set_references(self, references): self.references = references def add_references(self, value): self.references.append(value) def insert_references(self, index, value): self.references[index] = value def get_referencedby(self): return self.referencedby def set_referencedby(self, referencedby): self.referencedby = referencedby def add_referencedby(self, value): self.referencedby.append(value) def insert_referencedby(self, index, value): self.referencedby[index] = value def get_initonly(self): return self.initonly def set_initonly(self, initonly): self.initonly = initonly def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_volatile(self): return self.volatile def set_volatile(self, volatile): self.volatile = volatile def get_const(self): return self.const def set_const(self, const): self.const = const def get_raise(self): return self.raisexx def set_raise(self, raisexx): self.raisexx = raisexx def get_virt(self): return self.virt def set_virt(self, virt): self.virt = virt def get_readable(self): return self.readable def set_readable(self, readable): self.readable = readable def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_explicit(self): return self.explicit def set_explicit(self, explicit): self.explicit = explicit def get_new(self): return self.new def set_new(self, new): self.new = new def get_final(self): return self.final def set_final(self, final): self.final = final def get_writable(self): return self.writable def set_writable(self, writable): self.writable = writable def get_add(self): return self.add def set_add(self, add): self.add = add def get_static(self): return self.static def set_static(self, static): self.static = static def get_remove(self): return self.remove def set_remove(self, remove): self.remove = remove def get_sealed(self): return self.sealed def set_sealed(self, sealed): self.sealed = sealed def get_mutable(self): return self.mutable def set_mutable(self, mutable): self.mutable = mutable def get_gettable(self): return self.gettable def set_gettable(self, gettable): self.gettable = gettable def get_inline(self): return self.inline def set_inline(self, inline): self.inline = inline def get_settable(self): return self.settable def set_settable(self, settable): self.settable = settable def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='memberdefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='memberdefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='memberdefType'): if self.initonly is not None: outfile.write(' initonly=%s' % (quote_attrib(self.initonly), )) if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) if self.volatile is not None: outfile.write(' volatile=%s' % (quote_attrib(self.volatile), )) if self.const is not None: outfile.write(' const=%s' % (quote_attrib(self.const), )) if self.raisexx is not None: outfile.write(' raise=%s' % (quote_attrib(self.raisexx), )) if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.readable is not None: outfile.write(' readable=%s' % (quote_attrib(self.readable), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.explicit is not None: outfile.write(' explicit=%s' % (quote_attrib(self.explicit), )) if self.new is not None: outfile.write(' new=%s' % (quote_attrib(self.new), )) if self.final is not None: outfile.write(' final=%s' % (quote_attrib(self.final), )) if self.writable is not None: outfile.write(' writable=%s' % (quote_attrib(self.writable), )) if self.add is not None: outfile.write(' add=%s' % (quote_attrib(self.add), )) if self.static is not None: outfile.write(' static=%s' % (quote_attrib(self.static), )) if self.remove is not None: outfile.write(' remove=%s' % (quote_attrib(self.remove), )) if self.sealed is not None: outfile.write(' sealed=%s' % (quote_attrib(self.sealed), )) if self.mutable is not None: outfile.write(' mutable=%s' % (quote_attrib(self.mutable), )) if self.gettable is not None: outfile.write(' gettable=%s' % (quote_attrib(self.gettable), )) if self.inline is not None: outfile.write(' inline=%s' % (quote_attrib(self.inline), )) if self.settable is not None: outfile.write(' settable=%s' % (quote_attrib(self.settable), )) if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='memberdefType'): if self.templateparamlist: self.templateparamlist.export(outfile, level, namespace_, name_='templateparamlist') if self.type_: self.type_.export(outfile, level, namespace_, name_='type') if self.definition is not None: showIndent(outfile, level) outfile.write('<%sdefinition>%s</%sdefinition>\n' % (namespace_, self.format_string(quote_xml(self.definition).encode(ExternalEncoding), input_name='definition'), namespace_)) if self.argsstring is not None: showIndent(outfile, level) outfile.write('<%sargsstring>%s</%sargsstring>\n' % (namespace_, self.format_string(quote_xml(self.argsstring).encode(ExternalEncoding), input_name='argsstring'), namespace_)) if self.name is not None: showIndent(outfile, level) outfile.write('<%sname>%s</%sname>\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) if self.read is not None: showIndent(outfile, level) outfile.write('<%sread>%s</%sread>\n' % (namespace_, self.format_string(quote_xml(self.read).encode(ExternalEncoding), input_name='read'), namespace_)) if self.write is not None: showIndent(outfile, level) outfile.write('<%swrite>%s</%swrite>\n' % (namespace_, self.format_string(quote_xml(self.write).encode(ExternalEncoding), input_name='write'), namespace_)) if self.bitfield is not None: showIndent(outfile, level) outfile.write('<%sbitfield>%s</%sbitfield>\n' % (namespace_, self.format_string(quote_xml(self.bitfield).encode(ExternalEncoding), input_name='bitfield'), namespace_)) for reimplements_ in self.reimplements: reimplements_.export(outfile, level, namespace_, name_='reimplements') for reimplementedby_ in self.reimplementedby: reimplementedby_.export(outfile, level, namespace_, name_='reimplementedby') for param_ in self.param: param_.export(outfile, level, namespace_, name_='param') for enumvalue_ in self.enumvalue: enumvalue_.export(outfile, level, namespace_, name_='enumvalue') if self.initializer: self.initializer.export(outfile, level, namespace_, name_='initializer') if self.exceptions: self.exceptions.export(outfile, level, namespace_, name_='exceptions') if self.briefdescription: self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') if self.detaileddescription: self.detaileddescription.export(outfile, level, namespace_, name_='detaileddescription') if self.inbodydescription: self.inbodydescription.export(outfile, level, namespace_, name_='inbodydescription') if self.location: self.location.export(outfile, level, namespace_, name_='location', ) for references_ in self.references: references_.export(outfile, level, namespace_, name_='references') for referencedby_ in self.referencedby: referencedby_.export(outfile, level, namespace_, name_='referencedby') def hasContent_(self): if ( self.templateparamlist is not None or self.type_ is not None or self.definition is not None or self.argsstring is not None or self.name is not None or self.read is not None or self.write is not None or self.bitfield is not None or self.reimplements is not None or self.reimplementedby is not None or self.param is not None or self.enumvalue is not None or self.initializer is not None or self.exceptions is not None or self.briefdescription is not None or self.detaileddescription is not None or self.inbodydescription is not None or self.location is not None or self.references is not None or self.referencedby is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='memberdefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.initonly is not None: showIndent(outfile, level) outfile.write('initonly = "%s",\n' % (self.initonly,)) if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) if self.volatile is not None: showIndent(outfile, level) outfile.write('volatile = "%s",\n' % (self.volatile,)) if self.const is not None: showIndent(outfile, level) outfile.write('const = "%s",\n' % (self.const,)) if self.raisexx is not None: showIndent(outfile, level) outfile.write('raisexx = "%s",\n' % (self.raisexx,)) if self.virt is not None: showIndent(outfile, level) outfile.write('virt = "%s",\n' % (self.virt,)) if self.readable is not None: showIndent(outfile, level) outfile.write('readable = "%s",\n' % (self.readable,)) if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.explicit is not None: showIndent(outfile, level) outfile.write('explicit = "%s",\n' % (self.explicit,)) if self.new is not None: showIndent(outfile, level) outfile.write('new = "%s",\n' % (self.new,)) if self.final is not None: showIndent(outfile, level) outfile.write('final = "%s",\n' % (self.final,)) if self.writable is not None: showIndent(outfile, level) outfile.write('writable = "%s",\n' % (self.writable,)) if self.add is not None: showIndent(outfile, level) outfile.write('add = "%s",\n' % (self.add,)) if self.static is not None: showIndent(outfile, level) outfile.write('static = "%s",\n' % (self.static,)) if self.remove is not None: showIndent(outfile, level) outfile.write('remove = "%s",\n' % (self.remove,)) if self.sealed is not None: showIndent(outfile, level) outfile.write('sealed = "%s",\n' % (self.sealed,)) if self.mutable is not None: showIndent(outfile, level) outfile.write('mutable = "%s",\n' % (self.mutable,)) if self.gettable is not None: showIndent(outfile, level) outfile.write('gettable = "%s",\n' % (self.gettable,)) if self.inline is not None: showIndent(outfile, level) outfile.write('inline = "%s",\n' % (self.inline,)) if self.settable is not None: showIndent(outfile, level) outfile.write('settable = "%s",\n' % (self.settable,)) if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): if self.templateparamlist: showIndent(outfile, level) outfile.write('templateparamlist=model_.templateparamlistType(\n') self.templateparamlist.exportLiteral(outfile, level, name_='templateparamlist') showIndent(outfile, level) outfile.write('),\n') if self.type_: showIndent(outfile, level) outfile.write('type_=model_.linkedTextType(\n') self.type_.exportLiteral(outfile, level, name_='type') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('definition=%s,\n' % quote_python(self.definition).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('argsstring=%s,\n' % quote_python(self.argsstring).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('read=%s,\n' % quote_python(self.read).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('write=%s,\n' % quote_python(self.write).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('bitfield=%s,\n' % quote_python(self.bitfield).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('reimplements=[\n') level += 1 for reimplements in self.reimplements: showIndent(outfile, level) outfile.write('model_.reimplements(\n') reimplements.exportLiteral(outfile, level, name_='reimplements') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('reimplementedby=[\n') level += 1 for reimplementedby in self.reimplementedby: showIndent(outfile, level) outfile.write('model_.reimplementedby(\n') reimplementedby.exportLiteral(outfile, level, name_='reimplementedby') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('param=[\n') level += 1 for param in self.param: showIndent(outfile, level) outfile.write('model_.param(\n') param.exportLiteral(outfile, level, name_='param') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('enumvalue=[\n') level += 1 for enumvalue in self.enumvalue: showIndent(outfile, level) outfile.write('model_.enumvalue(\n') enumvalue.exportLiteral(outfile, level, name_='enumvalue') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.initializer: showIndent(outfile, level) outfile.write('initializer=model_.linkedTextType(\n') self.initializer.exportLiteral(outfile, level, name_='initializer') showIndent(outfile, level) outfile.write('),\n') if self.exceptions: showIndent(outfile, level) outfile.write('exceptions=model_.linkedTextType(\n') self.exceptions.exportLiteral(outfile, level, name_='exceptions') showIndent(outfile, level) outfile.write('),\n') if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') if self.detaileddescription: showIndent(outfile, level) outfile.write('detaileddescription=model_.descriptionType(\n') self.detaileddescription.exportLiteral(outfile, level, name_='detaileddescription') showIndent(outfile, level) outfile.write('),\n') if self.inbodydescription: showIndent(outfile, level) outfile.write('inbodydescription=model_.descriptionType(\n') self.inbodydescription.exportLiteral(outfile, level, name_='inbodydescription') showIndent(outfile, level) outfile.write('),\n') if self.location: showIndent(outfile, level) outfile.write('location=model_.locationType(\n') self.location.exportLiteral(outfile, level, name_='location') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('references=[\n') level += 1 for references in self.references: showIndent(outfile, level) outfile.write('model_.references(\n') references.exportLiteral(outfile, level, name_='references') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('referencedby=[\n') level += 1 for referencedby in self.referencedby: showIndent(outfile, level) outfile.write('model_.referencedby(\n') referencedby.exportLiteral(outfile, level, name_='referencedby') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('initonly'): self.initonly = attrs.get('initonly').value if attrs.get('kind'): self.kind = attrs.get('kind').value if attrs.get('volatile'): self.volatile = attrs.get('volatile').value if attrs.get('const'): self.const = attrs.get('const').value if attrs.get('raise'): self.raisexx = attrs.get('raise').value if attrs.get('virt'): self.virt = attrs.get('virt').value if attrs.get('readable'): self.readable = attrs.get('readable').value if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('explicit'): self.explicit = attrs.get('explicit').value if attrs.get('new'): self.new = attrs.get('new').value if attrs.get('final'): self.final = attrs.get('final').value if attrs.get('writable'): self.writable = attrs.get('writable').value if attrs.get('add'): self.add = attrs.get('add').value if attrs.get('static'): self.static = attrs.get('static').value if attrs.get('remove'): self.remove = attrs.get('remove').value if attrs.get('sealed'): self.sealed = attrs.get('sealed').value if attrs.get('mutable'): self.mutable = attrs.get('mutable').value if attrs.get('gettable'): self.gettable = attrs.get('gettable').value if attrs.get('inline'): self.inline = attrs.get('inline').value if attrs.get('settable'): self.settable = attrs.get('settable').value if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'templateparamlist': obj_ = templateparamlistType.factory() obj_.build(child_) self.set_templateparamlist(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'type': obj_ = linkedTextType.factory() obj_.build(child_) self.set_type(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'definition': definition_ = '' for text__content_ in child_.childNodes: definition_ += text__content_.nodeValue self.definition = definition_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'argsstring': argsstring_ = '' for text__content_ in child_.childNodes: argsstring_ += text__content_.nodeValue self.argsstring = argsstring_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue self.name = name_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'read': read_ = '' for text__content_ in child_.childNodes: read_ += text__content_.nodeValue self.read = read_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'write': write_ = '' for text__content_ in child_.childNodes: write_ += text__content_.nodeValue self.write = write_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'bitfield': bitfield_ = '' for text__content_ in child_.childNodes: bitfield_ += text__content_.nodeValue self.bitfield = bitfield_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'reimplements': obj_ = reimplementType.factory() obj_.build(child_) self.reimplements.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'reimplementedby': obj_ = reimplementType.factory() obj_.build(child_) self.reimplementedby.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'param': obj_ = paramType.factory() obj_.build(child_) self.param.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'enumvalue': obj_ = enumvalueType.factory() obj_.build(child_) self.enumvalue.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'initializer': obj_ = linkedTextType.factory() obj_.build(child_) self.set_initializer(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'exceptions': obj_ = linkedTextType.factory() obj_.build(child_) self.set_exceptions(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'detaileddescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_detaileddescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'inbodydescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_inbodydescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'location': obj_ = locationType.factory() obj_.build(child_) self.set_location(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'references': obj_ = referenceType.factory() obj_.build(child_) self.references.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'referencedby': obj_ = referenceType.factory() obj_.build(child_) self.referencedby.append(obj_) # end class memberdefType class definition(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if definition.subclass: return definition.subclass(*args_, **kwargs_) else: return definition(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='definition', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='definition') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='definition'): pass def exportChildren(self, outfile, level, namespace_='', name_='definition'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='definition'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class definition class argsstring(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if argsstring.subclass: return argsstring.subclass(*args_, **kwargs_) else: return argsstring(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='argsstring', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='argsstring') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='argsstring'): pass def exportChildren(self, outfile, level, namespace_='', name_='argsstring'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='argsstring'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class argsstring class read(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if read.subclass: return read.subclass(*args_, **kwargs_) else: return read(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='read', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='read') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='read'): pass def exportChildren(self, outfile, level, namespace_='', name_='read'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='read'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class read class write(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if write.subclass: return write.subclass(*args_, **kwargs_) else: return write(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='write', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='write') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='write'): pass def exportChildren(self, outfile, level, namespace_='', name_='write'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='write'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class write class bitfield(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if bitfield.subclass: return bitfield.subclass(*args_, **kwargs_) else: return bitfield(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='bitfield', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='bitfield') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='bitfield'): pass def exportChildren(self, outfile, level, namespace_='', name_='bitfield'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='bitfield'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class bitfield class descriptionType(GeneratedsSuper): subclass = None superclass = None def __init__(self, title=None, para=None, sect1=None, internal=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if descriptionType.subclass: return descriptionType.subclass(*args_, **kwargs_) else: return descriptionType(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect1(self): return self.sect1 def set_sect1(self, sect1): self.sect1 = sect1 def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def export(self, outfile, level, namespace_='', name_='descriptionType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='descriptionType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='descriptionType'): pass def exportChildren(self, outfile, level, namespace_='', name_='descriptionType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect1 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='descriptionType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect1': childobj_ = docSect1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect1', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class descriptionType class enumvalueType(GeneratedsSuper): subclass = None superclass = None def __init__(self, prot=None, id=None, name=None, initializer=None, briefdescription=None, detaileddescription=None, mixedclass_=None, content_=None): self.prot = prot self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if enumvalueType.subclass: return enumvalueType.subclass(*args_, **kwargs_) else: return enumvalueType(*args_, **kwargs_) factory = staticmethod(factory) def get_name(self): return self.name def set_name(self, name): self.name = name def get_initializer(self): return self.initializer def set_initializer(self, initializer): self.initializer = initializer def get_briefdescription(self): return self.briefdescription def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription def get_detaileddescription(self): return self.detaileddescription def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='enumvalueType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='enumvalueType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='enumvalueType'): if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='enumvalueType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.name is not None or self.initializer is not None or self.briefdescription is not None or self.detaileddescription is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='enumvalueType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'name': value_ = [] for text_ in child_.childNodes: value_.append(text_.nodeValue) valuestr_ = ''.join(value_) obj_ = self.mixedclass_(MixedContainer.CategorySimple, MixedContainer.TypeString, 'name', valuestr_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'initializer': childobj_ = linkedTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'initializer', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'briefdescription': childobj_ = descriptionType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'briefdescription', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'detaileddescription': childobj_ = descriptionType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'detaileddescription', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class enumvalueType class templateparamlistType(GeneratedsSuper): subclass = None superclass = None def __init__(self, param=None): if param is None: self.param = [] else: self.param = param def factory(*args_, **kwargs_): if templateparamlistType.subclass: return templateparamlistType.subclass(*args_, **kwargs_) else: return templateparamlistType(*args_, **kwargs_) factory = staticmethod(factory) def get_param(self): return self.param def set_param(self, param): self.param = param def add_param(self, value): self.param.append(value) def insert_param(self, index, value): self.param[index] = value def export(self, outfile, level, namespace_='', name_='templateparamlistType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='templateparamlistType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='templateparamlistType'): pass def exportChildren(self, outfile, level, namespace_='', name_='templateparamlistType'): for param_ in self.param: param_.export(outfile, level, namespace_, name_='param') def hasContent_(self): if ( self.param is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='templateparamlistType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('param=[\n') level += 1 for param in self.param: showIndent(outfile, level) outfile.write('model_.param(\n') param.exportLiteral(outfile, level, name_='param') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'param': obj_ = paramType.factory() obj_.build(child_) self.param.append(obj_) # end class templateparamlistType class paramType(GeneratedsSuper): subclass = None superclass = None def __init__(self, type_=None, declname=None, defname=None, array=None, defval=None, briefdescription=None): self.type_ = type_ self.declname = declname self.defname = defname self.array = array self.defval = defval self.briefdescription = briefdescription def factory(*args_, **kwargs_): if paramType.subclass: return paramType.subclass(*args_, **kwargs_) else: return paramType(*args_, **kwargs_) factory = staticmethod(factory) def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_declname(self): return self.declname def set_declname(self, declname): self.declname = declname def get_defname(self): return self.defname def set_defname(self, defname): self.defname = defname def get_array(self): return self.array def set_array(self, array): self.array = array def get_defval(self): return self.defval def set_defval(self, defval): self.defval = defval def get_briefdescription(self): return self.briefdescription def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription def export(self, outfile, level, namespace_='', name_='paramType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='paramType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='paramType'): pass def exportChildren(self, outfile, level, namespace_='', name_='paramType'): if self.type_: self.type_.export(outfile, level, namespace_, name_='type') if self.declname is not None: showIndent(outfile, level) outfile.write('<%sdeclname>%s</%sdeclname>\n' % (namespace_, self.format_string(quote_xml(self.declname).encode(ExternalEncoding), input_name='declname'), namespace_)) if self.defname is not None: showIndent(outfile, level) outfile.write('<%sdefname>%s</%sdefname>\n' % (namespace_, self.format_string(quote_xml(self.defname).encode(ExternalEncoding), input_name='defname'), namespace_)) if self.array is not None: showIndent(outfile, level) outfile.write('<%sarray>%s</%sarray>\n' % (namespace_, self.format_string(quote_xml(self.array).encode(ExternalEncoding), input_name='array'), namespace_)) if self.defval: self.defval.export(outfile, level, namespace_, name_='defval') if self.briefdescription: self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') def hasContent_(self): if ( self.type_ is not None or self.declname is not None or self.defname is not None or self.array is not None or self.defval is not None or self.briefdescription is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='paramType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): if self.type_: showIndent(outfile, level) outfile.write('type_=model_.linkedTextType(\n') self.type_.exportLiteral(outfile, level, name_='type') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('declname=%s,\n' % quote_python(self.declname).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('defname=%s,\n' % quote_python(self.defname).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('array=%s,\n' % quote_python(self.array).encode(ExternalEncoding)) if self.defval: showIndent(outfile, level) outfile.write('defval=model_.linkedTextType(\n') self.defval.exportLiteral(outfile, level, name_='defval') showIndent(outfile, level) outfile.write('),\n') if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'type': obj_ = linkedTextType.factory() obj_.build(child_) self.set_type(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'declname': declname_ = '' for text__content_ in child_.childNodes: declname_ += text__content_.nodeValue self.declname = declname_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'defname': defname_ = '' for text__content_ in child_.childNodes: defname_ += text__content_.nodeValue self.defname = defname_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'array': array_ = '' for text__content_ in child_.childNodes: array_ += text__content_.nodeValue self.array = array_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'defval': obj_ = linkedTextType.factory() obj_.build(child_) self.set_defval(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) # end class paramType class declname(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if declname.subclass: return declname.subclass(*args_, **kwargs_) else: return declname(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='declname', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='declname') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='declname'): pass def exportChildren(self, outfile, level, namespace_='', name_='declname'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='declname'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class declname class defname(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if defname.subclass: return defname.subclass(*args_, **kwargs_) else: return defname(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='defname', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='defname') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='defname'): pass def exportChildren(self, outfile, level, namespace_='', name_='defname'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='defname'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class defname class array(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if array.subclass: return array.subclass(*args_, **kwargs_) else: return array(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='array', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='array') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='array'): pass def exportChildren(self, outfile, level, namespace_='', name_='array'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='array'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class array class linkedTextType(GeneratedsSuper): subclass = None superclass = None def __init__(self, ref=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if linkedTextType.subclass: return linkedTextType.subclass(*args_, **kwargs_) else: return linkedTextType(*args_, **kwargs_) factory = staticmethod(factory) def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def add_ref(self, value): self.ref.append(value) def insert_ref(self, index, value): self.ref[index] = value def export(self, outfile, level, namespace_='', name_='linkedTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='linkedTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='linkedTextType'): pass def exportChildren(self, outfile, level, namespace_='', name_='linkedTextType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.ref is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='linkedTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class linkedTextType class graphType(GeneratedsSuper): subclass = None superclass = None def __init__(self, node=None): if node is None: self.node = [] else: self.node = node def factory(*args_, **kwargs_): if graphType.subclass: return graphType.subclass(*args_, **kwargs_) else: return graphType(*args_, **kwargs_) factory = staticmethod(factory) def get_node(self): return self.node def set_node(self, node): self.node = node def add_node(self, value): self.node.append(value) def insert_node(self, index, value): self.node[index] = value def export(self, outfile, level, namespace_='', name_='graphType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='graphType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='graphType'): pass def exportChildren(self, outfile, level, namespace_='', name_='graphType'): for node_ in self.node: node_.export(outfile, level, namespace_, name_='node') def hasContent_(self): if ( self.node is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='graphType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('node=[\n') level += 1 for node in self.node: showIndent(outfile, level) outfile.write('model_.node(\n') node.exportLiteral(outfile, level, name_='node') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'node': obj_ = nodeType.factory() obj_.build(child_) self.node.append(obj_) # end class graphType class nodeType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, label=None, link=None, childnode=None): self.id = id self.label = label self.link = link if childnode is None: self.childnode = [] else: self.childnode = childnode def factory(*args_, **kwargs_): if nodeType.subclass: return nodeType.subclass(*args_, **kwargs_) else: return nodeType(*args_, **kwargs_) factory = staticmethod(factory) def get_label(self): return self.label def set_label(self, label): self.label = label def get_link(self): return self.link def set_link(self, link): self.link = link def get_childnode(self): return self.childnode def set_childnode(self, childnode): self.childnode = childnode def add_childnode(self, value): self.childnode.append(value) def insert_childnode(self, index, value): self.childnode[index] = value def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='nodeType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='nodeType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='nodeType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='nodeType'): if self.label is not None: showIndent(outfile, level) outfile.write('<%slabel>%s</%slabel>\n' % (namespace_, self.format_string(quote_xml(self.label).encode(ExternalEncoding), input_name='label'), namespace_)) if self.link: self.link.export(outfile, level, namespace_, name_='link') for childnode_ in self.childnode: childnode_.export(outfile, level, namespace_, name_='childnode') def hasContent_(self): if ( self.label is not None or self.link is not None or self.childnode is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='nodeType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('label=%s,\n' % quote_python(self.label).encode(ExternalEncoding)) if self.link: showIndent(outfile, level) outfile.write('link=model_.linkType(\n') self.link.exportLiteral(outfile, level, name_='link') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('childnode=[\n') level += 1 for childnode in self.childnode: showIndent(outfile, level) outfile.write('model_.childnode(\n') childnode.exportLiteral(outfile, level, name_='childnode') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'label': label_ = '' for text__content_ in child_.childNodes: label_ += text__content_.nodeValue self.label = label_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'link': obj_ = linkType.factory() obj_.build(child_) self.set_link(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'childnode': obj_ = childnodeType.factory() obj_.build(child_) self.childnode.append(obj_) # end class nodeType class label(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if label.subclass: return label.subclass(*args_, **kwargs_) else: return label(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='label', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='label') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='label'): pass def exportChildren(self, outfile, level, namespace_='', name_='label'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='label'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class label class childnodeType(GeneratedsSuper): subclass = None superclass = None def __init__(self, relation=None, refid=None, edgelabel=None): self.relation = relation self.refid = refid if edgelabel is None: self.edgelabel = [] else: self.edgelabel = edgelabel def factory(*args_, **kwargs_): if childnodeType.subclass: return childnodeType.subclass(*args_, **kwargs_) else: return childnodeType(*args_, **kwargs_) factory = staticmethod(factory) def get_edgelabel(self): return self.edgelabel def set_edgelabel(self, edgelabel): self.edgelabel = edgelabel def add_edgelabel(self, value): self.edgelabel.append(value) def insert_edgelabel(self, index, value): self.edgelabel[index] = value def get_relation(self): return self.relation def set_relation(self, relation): self.relation = relation def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def export(self, outfile, level, namespace_='', name_='childnodeType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='childnodeType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='childnodeType'): if self.relation is not None: outfile.write(' relation=%s' % (quote_attrib(self.relation), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='childnodeType'): for edgelabel_ in self.edgelabel: showIndent(outfile, level) outfile.write('<%sedgelabel>%s</%sedgelabel>\n' % (namespace_, self.format_string(quote_xml(edgelabel_).encode(ExternalEncoding), input_name='edgelabel'), namespace_)) def hasContent_(self): if ( self.edgelabel is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='childnodeType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.relation is not None: showIndent(outfile, level) outfile.write('relation = "%s",\n' % (self.relation,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('edgelabel=[\n') level += 1 for edgelabel in self.edgelabel: showIndent(outfile, level) outfile.write('%s,\n' % quote_python(edgelabel).encode(ExternalEncoding)) level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('relation'): self.relation = attrs.get('relation').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'edgelabel': edgelabel_ = '' for text__content_ in child_.childNodes: edgelabel_ += text__content_.nodeValue self.edgelabel.append(edgelabel_) # end class childnodeType class edgelabel(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if edgelabel.subclass: return edgelabel.subclass(*args_, **kwargs_) else: return edgelabel(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='edgelabel', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='edgelabel') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='edgelabel'): pass def exportChildren(self, outfile, level, namespace_='', name_='edgelabel'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='edgelabel'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class edgelabel class linkType(GeneratedsSuper): subclass = None superclass = None def __init__(self, refid=None, external=None, valueOf_=''): self.refid = refid self.external = external self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if linkType.subclass: return linkType.subclass(*args_, **kwargs_) else: return linkType(*args_, **kwargs_) factory = staticmethod(factory) def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='linkType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='linkType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='linkType'): if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.external is not None: outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) def exportChildren(self, outfile, level, namespace_='', name_='linkType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='linkType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('external'): self.external = attrs.get('external').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class linkType class listingType(GeneratedsSuper): subclass = None superclass = None def __init__(self, codeline=None): if codeline is None: self.codeline = [] else: self.codeline = codeline def factory(*args_, **kwargs_): if listingType.subclass: return listingType.subclass(*args_, **kwargs_) else: return listingType(*args_, **kwargs_) factory = staticmethod(factory) def get_codeline(self): return self.codeline def set_codeline(self, codeline): self.codeline = codeline def add_codeline(self, value): self.codeline.append(value) def insert_codeline(self, index, value): self.codeline[index] = value def export(self, outfile, level, namespace_='', name_='listingType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='listingType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='listingType'): pass def exportChildren(self, outfile, level, namespace_='', name_='listingType'): for codeline_ in self.codeline: codeline_.export(outfile, level, namespace_, name_='codeline') def hasContent_(self): if ( self.codeline is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='listingType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('codeline=[\n') level += 1 for codeline in self.codeline: showIndent(outfile, level) outfile.write('model_.codeline(\n') codeline.exportLiteral(outfile, level, name_='codeline') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'codeline': obj_ = codelineType.factory() obj_.build(child_) self.codeline.append(obj_) # end class listingType class codelineType(GeneratedsSuper): subclass = None superclass = None def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None): self.external = external self.lineno = lineno self.refkind = refkind self.refid = refid if highlight is None: self.highlight = [] else: self.highlight = highlight def factory(*args_, **kwargs_): if codelineType.subclass: return codelineType.subclass(*args_, **kwargs_) else: return codelineType(*args_, **kwargs_) factory = staticmethod(factory) def get_highlight(self): return self.highlight def set_highlight(self, highlight): self.highlight = highlight def add_highlight(self, value): self.highlight.append(value) def insert_highlight(self, index, value): self.highlight[index] = value def get_external(self): return self.external def set_external(self, external): self.external = external def get_lineno(self): return self.lineno def set_lineno(self, lineno): self.lineno = lineno def get_refkind(self): return self.refkind def set_refkind(self, refkind): self.refkind = refkind def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def export(self, outfile, level, namespace_='', name_='codelineType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='codelineType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='codelineType'): if self.external is not None: outfile.write(' external=%s' % (quote_attrib(self.external), )) if self.lineno is not None: outfile.write(' lineno="%s"' % self.format_integer(self.lineno, input_name='lineno')) if self.refkind is not None: outfile.write(' refkind=%s' % (quote_attrib(self.refkind), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='codelineType'): for highlight_ in self.highlight: highlight_.export(outfile, level, namespace_, name_='highlight') def hasContent_(self): if ( self.highlight is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='codelineType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) outfile.write('external = "%s",\n' % (self.external,)) if self.lineno is not None: showIndent(outfile, level) outfile.write('lineno = %s,\n' % (self.lineno,)) if self.refkind is not None: showIndent(outfile, level) outfile.write('refkind = "%s",\n' % (self.refkind,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('highlight=[\n') level += 1 for highlight in self.highlight: showIndent(outfile, level) outfile.write('model_.highlight(\n') highlight.exportLiteral(outfile, level, name_='highlight') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('external'): self.external = attrs.get('external').value if attrs.get('lineno'): try: self.lineno = int(attrs.get('lineno').value) except ValueError, exp: raise ValueError('Bad integer attribute (lineno): %s' % exp) if attrs.get('refkind'): self.refkind = attrs.get('refkind').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'highlight': obj_ = highlightType.factory() obj_.build(child_) self.highlight.append(obj_) # end class codelineType class highlightType(GeneratedsSuper): subclass = None superclass = None def __init__(self, classxx=None, sp=None, ref=None, mixedclass_=None, content_=None): self.classxx = classxx if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if highlightType.subclass: return highlightType.subclass(*args_, **kwargs_) else: return highlightType(*args_, **kwargs_) factory = staticmethod(factory) def get_sp(self): return self.sp def set_sp(self, sp): self.sp = sp def add_sp(self, value): self.sp.append(value) def insert_sp(self, index, value): self.sp[index] = value def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def add_ref(self, value): self.ref.append(value) def insert_ref(self, index, value): self.ref[index] = value def get_class(self): return self.classxx def set_class(self, classxx): self.classxx = classxx def export(self, outfile, level, namespace_='', name_='highlightType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='highlightType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='highlightType'): if self.classxx is not None: outfile.write(' class=%s' % (quote_attrib(self.classxx), )) def exportChildren(self, outfile, level, namespace_='', name_='highlightType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.sp is not None or self.ref is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='highlightType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.classxx is not None: showIndent(outfile, level) outfile.write('classxx = "%s",\n' % (self.classxx,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('class'): self.classxx = attrs.get('class').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sp': value_ = [] for text_ in child_.childNodes: value_.append(text_.nodeValue) valuestr_ = ''.join(value_) obj_ = self.mixedclass_(MixedContainer.CategorySimple, MixedContainer.TypeString, 'sp', valuestr_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class highlightType class sp(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if sp.subclass: return sp.subclass(*args_, **kwargs_) else: return sp(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='sp', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='sp') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='sp'): pass def exportChildren(self, outfile, level, namespace_='', name_='sp'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='sp'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class sp class referenceType(GeneratedsSuper): subclass = None superclass = None def __init__(self, endline=None, startline=None, refid=None, compoundref=None, valueOf_='', mixedclass_=None, content_=None): self.endline = endline self.startline = startline self.refid = refid self.compoundref = compoundref if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if referenceType.subclass: return referenceType.subclass(*args_, **kwargs_) else: return referenceType(*args_, **kwargs_) factory = staticmethod(factory) def get_endline(self): return self.endline def set_endline(self, endline): self.endline = endline def get_startline(self): return self.startline def set_startline(self, startline): self.startline = startline def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_compoundref(self): return self.compoundref def set_compoundref(self, compoundref): self.compoundref = compoundref def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='referenceType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='referenceType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='referenceType'): if self.endline is not None: outfile.write(' endline="%s"' % self.format_integer(self.endline, input_name='endline')) if self.startline is not None: outfile.write(' startline="%s"' % self.format_integer(self.startline, input_name='startline')) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.compoundref is not None: outfile.write(' compoundref=%s' % (self.format_string(quote_attrib(self.compoundref).encode(ExternalEncoding), input_name='compoundref'), )) def exportChildren(self, outfile, level, namespace_='', name_='referenceType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='referenceType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.endline is not None: showIndent(outfile, level) outfile.write('endline = %s,\n' % (self.endline,)) if self.startline is not None: showIndent(outfile, level) outfile.write('startline = %s,\n' % (self.startline,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.compoundref is not None: showIndent(outfile, level) outfile.write('compoundref = %s,\n' % (self.compoundref,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('endline'): try: self.endline = int(attrs.get('endline').value) except ValueError, exp: raise ValueError('Bad integer attribute (endline): %s' % exp) if attrs.get('startline'): try: self.startline = int(attrs.get('startline').value) except ValueError, exp: raise ValueError('Bad integer attribute (startline): %s' % exp) if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('compoundref'): self.compoundref = attrs.get('compoundref').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class referenceType class locationType(GeneratedsSuper): subclass = None superclass = None def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file=None, valueOf_=''): self.bodystart = bodystart self.line = line self.bodyend = bodyend self.bodyfile = bodyfile self.file = file self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if locationType.subclass: return locationType.subclass(*args_, **kwargs_) else: return locationType(*args_, **kwargs_) factory = staticmethod(factory) def get_bodystart(self): return self.bodystart def set_bodystart(self, bodystart): self.bodystart = bodystart def get_line(self): return self.line def set_line(self, line): self.line = line def get_bodyend(self): return self.bodyend def set_bodyend(self, bodyend): self.bodyend = bodyend def get_bodyfile(self): return self.bodyfile def set_bodyfile(self, bodyfile): self.bodyfile = bodyfile def get_file(self): return self.file def set_file(self, file): self.file = file def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='locationType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='locationType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='locationType'): if self.bodystart is not None: outfile.write(' bodystart="%s"' % self.format_integer(self.bodystart, input_name='bodystart')) if self.line is not None: outfile.write(' line="%s"' % self.format_integer(self.line, input_name='line')) if self.bodyend is not None: outfile.write(' bodyend="%s"' % self.format_integer(self.bodyend, input_name='bodyend')) if self.bodyfile is not None: outfile.write(' bodyfile=%s' % (self.format_string(quote_attrib(self.bodyfile).encode(ExternalEncoding), input_name='bodyfile'), )) if self.file is not None: outfile.write(' file=%s' % (self.format_string(quote_attrib(self.file).encode(ExternalEncoding), input_name='file'), )) def exportChildren(self, outfile, level, namespace_='', name_='locationType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='locationType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.bodystart is not None: showIndent(outfile, level) outfile.write('bodystart = %s,\n' % (self.bodystart,)) if self.line is not None: showIndent(outfile, level) outfile.write('line = %s,\n' % (self.line,)) if self.bodyend is not None: showIndent(outfile, level) outfile.write('bodyend = %s,\n' % (self.bodyend,)) if self.bodyfile is not None: showIndent(outfile, level) outfile.write('bodyfile = %s,\n' % (self.bodyfile,)) if self.file is not None: showIndent(outfile, level) outfile.write('file = %s,\n' % (self.file,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('bodystart'): try: self.bodystart = int(attrs.get('bodystart').value) except ValueError, exp: raise ValueError('Bad integer attribute (bodystart): %s' % exp) if attrs.get('line'): try: self.line = int(attrs.get('line').value) except ValueError, exp: raise ValueError('Bad integer attribute (line): %s' % exp) if attrs.get('bodyend'): try: self.bodyend = int(attrs.get('bodyend').value) except ValueError, exp: raise ValueError('Bad integer attribute (bodyend): %s' % exp) if attrs.get('bodyfile'): self.bodyfile = attrs.get('bodyfile').value if attrs.get('file'): self.file = attrs.get('file').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class locationType class docSect1Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, title=None, para=None, sect2=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docSect1Type.subclass: return docSect1Type.subclass(*args_, **kwargs_) else: return docSect1Type(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect2(self): return self.sect2 def set_sect2(self, sect2): self.sect2 = sect2 def add_sect2(self, value): self.sect2.append(value) def insert_sect2(self, index, value): self.sect2[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docSect1Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSect1Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docSect1Type'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docSect1Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect2 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSect1Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect2': childobj_ = docSect2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect2', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalS1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect1Type class docSect2Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, title=None, para=None, sect3=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docSect2Type.subclass: return docSect2Type.subclass(*args_, **kwargs_) else: return docSect2Type(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docSect2Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSect2Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docSect2Type'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docSect2Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect3 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSect2Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect3': childobj_ = docSect3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalS2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect2Type class docSect3Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, title=None, para=None, sect4=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docSect3Type.subclass: return docSect3Type.subclass(*args_, **kwargs_) else: return docSect3Type(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect4(self): return self.sect4 def set_sect4(self, sect4): self.sect4 = sect4 def add_sect4(self, value): self.sect4.append(value) def insert_sect4(self, index, value): self.sect4[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docSect3Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSect3Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docSect3Type'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docSect3Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect4 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSect3Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect4': childobj_ = docSect4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect4', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalS3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect3Type class docSect4Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, title=None, para=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docSect4Type.subclass: return docSect4Type.subclass(*args_, **kwargs_) else: return docSect4Type(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docSect4Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSect4Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docSect4Type'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docSect4Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSect4Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalS4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect4Type class docInternalType(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalType.subclass: return docInternalType.subclass(*args_, **kwargs_) else: return docInternalType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect1(self): return self.sect1 def set_sect1(self, sect1): self.sect1 = sect1 def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value def export(self, outfile, level, namespace_='', name_='docInternalType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None or self.sect1 is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect1': childobj_ = docSect1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect1', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalType class docInternalS1Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalS1Type.subclass: return docInternalS1Type.subclass(*args_, **kwargs_) else: return docInternalS1Type(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect2(self): return self.sect2 def set_sect2(self, sect2): self.sect2 = sect2 def add_sect2(self, value): self.sect2.append(value) def insert_sect2(self, index, value): self.sect2[index] = value def export(self, outfile, level, namespace_='', name_='docInternalS1Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalS1Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS1Type'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalS1Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None or self.sect2 is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalS1Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect2': childobj_ = docSect2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect2', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS1Type class docInternalS2Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalS2Type.subclass: return docInternalS2Type.subclass(*args_, **kwargs_) else: return docInternalS2Type(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value def export(self, outfile, level, namespace_='', name_='docInternalS2Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalS2Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS2Type'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalS2Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None or self.sect3 is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalS2Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect3': childobj_ = docSect3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS2Type class docInternalS3Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalS3Type.subclass: return docInternalS3Type.subclass(*args_, **kwargs_) else: return docInternalS3Type(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value def export(self, outfile, level, namespace_='', name_='docInternalS3Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalS3Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS3Type'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalS3Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None or self.sect3 is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalS3Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect3': childobj_ = docSect4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS3Type class docInternalS4Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalS4Type.subclass: return docInternalS4Type.subclass(*args_, **kwargs_) else: return docInternalS4Type(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def export(self, outfile, level, namespace_='', name_='docInternalS4Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalS4Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS4Type'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalS4Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalS4Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS4Type class docTitleType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docTitleType.subclass: return docTitleType.subclass(*args_, **kwargs_) else: return docTitleType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docTitleType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docTitleType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docTitleType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docTitleType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docTitleType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docTitleType class docParaType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docParaType.subclass: return docParaType.subclass(*args_, **kwargs_) else: return docParaType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docParaType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParaType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docParaType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docParaType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParaType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docParaType class docMarkupType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docMarkupType.subclass: return docMarkupType.subclass(*args_, **kwargs_) else: return docMarkupType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docMarkupType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docMarkupType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docMarkupType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docMarkupType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docMarkupType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docMarkupType class docURLLink(GeneratedsSuper): subclass = None superclass = None def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): self.url = url if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docURLLink.subclass: return docURLLink.subclass(*args_, **kwargs_) else: return docURLLink(*args_, **kwargs_) factory = staticmethod(factory) def get_url(self): return self.url def set_url(self, url): self.url = url def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docURLLink', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docURLLink') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docURLLink'): if self.url is not None: outfile.write(' url=%s' % (self.format_string(quote_attrib(self.url).encode(ExternalEncoding), input_name='url'), )) def exportChildren(self, outfile, level, namespace_='', name_='docURLLink'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docURLLink'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.url is not None: showIndent(outfile, level) outfile.write('url = %s,\n' % (self.url,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('url'): self.url = attrs.get('url').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docURLLink class docAnchorType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docAnchorType.subclass: return docAnchorType.subclass(*args_, **kwargs_) else: return docAnchorType(*args_, **kwargs_) factory = staticmethod(factory) def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docAnchorType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docAnchorType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docAnchorType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docAnchorType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docAnchorType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docAnchorType class docFormulaType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docFormulaType.subclass: return docFormulaType.subclass(*args_, **kwargs_) else: return docFormulaType(*args_, **kwargs_) factory = staticmethod(factory) def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docFormulaType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docFormulaType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docFormulaType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docFormulaType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docFormulaType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docFormulaType class docIndexEntryType(GeneratedsSuper): subclass = None superclass = None def __init__(self, primaryie=None, secondaryie=None): self.primaryie = primaryie self.secondaryie = secondaryie def factory(*args_, **kwargs_): if docIndexEntryType.subclass: return docIndexEntryType.subclass(*args_, **kwargs_) else: return docIndexEntryType(*args_, **kwargs_) factory = staticmethod(factory) def get_primaryie(self): return self.primaryie def set_primaryie(self, primaryie): self.primaryie = primaryie def get_secondaryie(self): return self.secondaryie def set_secondaryie(self, secondaryie): self.secondaryie = secondaryie def export(self, outfile, level, namespace_='', name_='docIndexEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docIndexEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docIndexEntryType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docIndexEntryType'): if self.primaryie is not None: showIndent(outfile, level) outfile.write('<%sprimaryie>%s</%sprimaryie>\n' % (namespace_, self.format_string(quote_xml(self.primaryie).encode(ExternalEncoding), input_name='primaryie'), namespace_)) if self.secondaryie is not None: showIndent(outfile, level) outfile.write('<%ssecondaryie>%s</%ssecondaryie>\n' % (namespace_, self.format_string(quote_xml(self.secondaryie).encode(ExternalEncoding), input_name='secondaryie'), namespace_)) def hasContent_(self): if ( self.primaryie is not None or self.secondaryie is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docIndexEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('primaryie=%s,\n' % quote_python(self.primaryie).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('secondaryie=%s,\n' % quote_python(self.secondaryie).encode(ExternalEncoding)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'primaryie': primaryie_ = '' for text__content_ in child_.childNodes: primaryie_ += text__content_.nodeValue self.primaryie = primaryie_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'secondaryie': secondaryie_ = '' for text__content_ in child_.childNodes: secondaryie_ += text__content_.nodeValue self.secondaryie = secondaryie_ # end class docIndexEntryType class docListType(GeneratedsSuper): subclass = None superclass = None def __init__(self, listitem=None): if listitem is None: self.listitem = [] else: self.listitem = listitem def factory(*args_, **kwargs_): if docListType.subclass: return docListType.subclass(*args_, **kwargs_) else: return docListType(*args_, **kwargs_) factory = staticmethod(factory) def get_listitem(self): return self.listitem def set_listitem(self, listitem): self.listitem = listitem def add_listitem(self, value): self.listitem.append(value) def insert_listitem(self, index, value): self.listitem[index] = value def export(self, outfile, level, namespace_='', name_='docListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docListType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docListType'): for listitem_ in self.listitem: listitem_.export(outfile, level, namespace_, name_='listitem') def hasContent_(self): if ( self.listitem is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('listitem=[\n') level += 1 for listitem in self.listitem: showIndent(outfile, level) outfile.write('model_.listitem(\n') listitem.exportLiteral(outfile, level, name_='listitem') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'listitem': obj_ = docListItemType.factory() obj_.build(child_) self.listitem.append(obj_) # end class docListType class docListItemType(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None): if para is None: self.para = [] else: self.para = para def factory(*args_, **kwargs_): if docListItemType.subclass: return docListItemType.subclass(*args_, **kwargs_) else: return docListItemType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def export(self, outfile, level, namespace_='', name_='docListItemType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docListItemType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docListItemType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docListItemType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') def hasContent_(self): if ( self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docListItemType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) # end class docListItemType class docSimpleSectType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, title=None, para=None): self.kind = kind self.title = title if para is None: self.para = [] else: self.para = para def factory(*args_, **kwargs_): if docSimpleSectType.subclass: return docSimpleSectType.subclass(*args_, **kwargs_) else: return docSimpleSectType(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def export(self, outfile, level, namespace_='', name_='docSimpleSectType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSimpleSectType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docSimpleSectType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) def exportChildren(self, outfile, level, namespace_='', name_='docSimpleSectType'): if self.title: self.title.export(outfile, level, namespace_, name_='title') for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') def hasContent_(self): if ( self.title is not None or self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSimpleSectType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) def exportLiteralChildren(self, outfile, level, name_): if self.title: showIndent(outfile, level) outfile.write('title=model_.docTitleType(\n') self.title.exportLiteral(outfile, level, name_='title') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': obj_ = docTitleType.factory() obj_.build(child_) self.set_title(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) # end class docSimpleSectType class docVarListEntryType(GeneratedsSuper): subclass = None superclass = None def __init__(self, term=None): self.term = term def factory(*args_, **kwargs_): if docVarListEntryType.subclass: return docVarListEntryType.subclass(*args_, **kwargs_) else: return docVarListEntryType(*args_, **kwargs_) factory = staticmethod(factory) def get_term(self): return self.term def set_term(self, term): self.term = term def export(self, outfile, level, namespace_='', name_='docVarListEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docVarListEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docVarListEntryType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docVarListEntryType'): if self.term: self.term.export(outfile, level, namespace_, name_='term', ) def hasContent_(self): if ( self.term is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docVarListEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): if self.term: showIndent(outfile, level) outfile.write('term=model_.docTitleType(\n') self.term.exportLiteral(outfile, level, name_='term') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'term': obj_ = docTitleType.factory() obj_.build(child_) self.set_term(obj_) # end class docVarListEntryType class docVariableListType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if docVariableListType.subclass: return docVariableListType.subclass(*args_, **kwargs_) else: return docVariableListType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docVariableListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docVariableListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docVariableListType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docVariableListType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docVariableListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docVariableListType class docRefTextType(GeneratedsSuper): subclass = None superclass = None def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid self.kindref = kindref self.external = external if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docRefTextType.subclass: return docRefTextType.subclass(*args_, **kwargs_) else: return docRefTextType(*args_, **kwargs_) factory = staticmethod(factory) def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_kindref(self): return self.kindref def set_kindref(self, kindref): self.kindref = kindref def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docRefTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docRefTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docRefTextType'): if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.kindref is not None: outfile.write(' kindref=%s' % (quote_attrib(self.kindref), )) if self.external is not None: outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) def exportChildren(self, outfile, level, namespace_='', name_='docRefTextType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docRefTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.kindref is not None: showIndent(outfile, level) outfile.write('kindref = "%s",\n' % (self.kindref,)) if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('kindref'): self.kindref = attrs.get('kindref').value if attrs.get('external'): self.external = attrs.get('external').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docRefTextType class docTableType(GeneratedsSuper): subclass = None superclass = None def __init__(self, rows=None, cols=None, row=None, caption=None): self.rows = rows self.cols = cols if row is None: self.row = [] else: self.row = row self.caption = caption def factory(*args_, **kwargs_): if docTableType.subclass: return docTableType.subclass(*args_, **kwargs_) else: return docTableType(*args_, **kwargs_) factory = staticmethod(factory) def get_row(self): return self.row def set_row(self, row): self.row = row def add_row(self, value): self.row.append(value) def insert_row(self, index, value): self.row[index] = value def get_caption(self): return self.caption def set_caption(self, caption): self.caption = caption def get_rows(self): return self.rows def set_rows(self, rows): self.rows = rows def get_cols(self): return self.cols def set_cols(self, cols): self.cols = cols def export(self, outfile, level, namespace_='', name_='docTableType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docTableType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docTableType'): if self.rows is not None: outfile.write(' rows="%s"' % self.format_integer(self.rows, input_name='rows')) if self.cols is not None: outfile.write(' cols="%s"' % self.format_integer(self.cols, input_name='cols')) def exportChildren(self, outfile, level, namespace_='', name_='docTableType'): for row_ in self.row: row_.export(outfile, level, namespace_, name_='row') if self.caption: self.caption.export(outfile, level, namespace_, name_='caption') def hasContent_(self): if ( self.row is not None or self.caption is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docTableType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.rows is not None: showIndent(outfile, level) outfile.write('rows = %s,\n' % (self.rows,)) if self.cols is not None: showIndent(outfile, level) outfile.write('cols = %s,\n' % (self.cols,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('row=[\n') level += 1 for row in self.row: showIndent(outfile, level) outfile.write('model_.row(\n') row.exportLiteral(outfile, level, name_='row') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.caption: showIndent(outfile, level) outfile.write('caption=model_.docCaptionType(\n') self.caption.exportLiteral(outfile, level, name_='caption') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('rows'): try: self.rows = int(attrs.get('rows').value) except ValueError, exp: raise ValueError('Bad integer attribute (rows): %s' % exp) if attrs.get('cols'): try: self.cols = int(attrs.get('cols').value) except ValueError, exp: raise ValueError('Bad integer attribute (cols): %s' % exp) def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'row': obj_ = docRowType.factory() obj_.build(child_) self.row.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'caption': obj_ = docCaptionType.factory() obj_.build(child_) self.set_caption(obj_) # end class docTableType class docRowType(GeneratedsSuper): subclass = None superclass = None def __init__(self, entry=None): if entry is None: self.entry = [] else: self.entry = entry def factory(*args_, **kwargs_): if docRowType.subclass: return docRowType.subclass(*args_, **kwargs_) else: return docRowType(*args_, **kwargs_) factory = staticmethod(factory) def get_entry(self): return self.entry def set_entry(self, entry): self.entry = entry def add_entry(self, value): self.entry.append(value) def insert_entry(self, index, value): self.entry[index] = value def export(self, outfile, level, namespace_='', name_='docRowType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docRowType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docRowType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docRowType'): for entry_ in self.entry: entry_.export(outfile, level, namespace_, name_='entry') def hasContent_(self): if ( self.entry is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docRowType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('entry=[\n') level += 1 for entry in self.entry: showIndent(outfile, level) outfile.write('model_.entry(\n') entry.exportLiteral(outfile, level, name_='entry') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'entry': obj_ = docEntryType.factory() obj_.build(child_) self.entry.append(obj_) # end class docRowType class docEntryType(GeneratedsSuper): subclass = None superclass = None def __init__(self, thead=None, para=None): self.thead = thead if para is None: self.para = [] else: self.para = para def factory(*args_, **kwargs_): if docEntryType.subclass: return docEntryType.subclass(*args_, **kwargs_) else: return docEntryType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_thead(self): return self.thead def set_thead(self, thead): self.thead = thead def export(self, outfile, level, namespace_='', name_='docEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docEntryType'): if self.thead is not None: outfile.write(' thead=%s' % (quote_attrib(self.thead), )) def exportChildren(self, outfile, level, namespace_='', name_='docEntryType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') def hasContent_(self): if ( self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.thead is not None: showIndent(outfile, level) outfile.write('thead = "%s",\n' % (self.thead,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('thead'): self.thead = attrs.get('thead').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) # end class docEntryType class docCaptionType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docCaptionType.subclass: return docCaptionType.subclass(*args_, **kwargs_) else: return docCaptionType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docCaptionType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docCaptionType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docCaptionType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docCaptionType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docCaptionType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docCaptionType class docHeadingType(GeneratedsSuper): subclass = None superclass = None def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): self.level = level if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docHeadingType.subclass: return docHeadingType.subclass(*args_, **kwargs_) else: return docHeadingType(*args_, **kwargs_) factory = staticmethod(factory) def get_level(self): return self.level def set_level(self, level): self.level = level def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docHeadingType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docHeadingType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docHeadingType'): if self.level is not None: outfile.write(' level="%s"' % self.format_integer(self.level, input_name='level')) def exportChildren(self, outfile, level, namespace_='', name_='docHeadingType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docHeadingType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.level is not None: showIndent(outfile, level) outfile.write('level = %s,\n' % (self.level,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('level'): try: self.level = int(attrs.get('level').value) except ValueError, exp: raise ValueError('Bad integer attribute (level): %s' % exp) def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docHeadingType class docImageType(GeneratedsSuper): subclass = None superclass = None def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', mixedclass_=None, content_=None): self.width = width self.type_ = type_ self.name = name self.height = height if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docImageType.subclass: return docImageType.subclass(*args_, **kwargs_) else: return docImageType(*args_, **kwargs_) factory = staticmethod(factory) def get_width(self): return self.width def set_width(self, width): self.width = width def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_name(self): return self.name def set_name(self, name): self.name = name def get_height(self): return self.height def set_height(self, height): self.height = height def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docImageType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docImageType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docImageType'): if self.width is not None: outfile.write(' width=%s' % (self.format_string(quote_attrib(self.width).encode(ExternalEncoding), input_name='width'), )) if self.type_ is not None: outfile.write(' type=%s' % (quote_attrib(self.type_), )) if self.name is not None: outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) if self.height is not None: outfile.write(' height=%s' % (self.format_string(quote_attrib(self.height).encode(ExternalEncoding), input_name='height'), )) def exportChildren(self, outfile, level, namespace_='', name_='docImageType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docImageType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.width is not None: showIndent(outfile, level) outfile.write('width = %s,\n' % (self.width,)) if self.type_ is not None: showIndent(outfile, level) outfile.write('type_ = "%s",\n' % (self.type_,)) if self.name is not None: showIndent(outfile, level) outfile.write('name = %s,\n' % (self.name,)) if self.height is not None: showIndent(outfile, level) outfile.write('height = %s,\n' % (self.height,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('width'): self.width = attrs.get('width').value if attrs.get('type'): self.type_ = attrs.get('type').value if attrs.get('name'): self.name = attrs.get('name').value if attrs.get('height'): self.height = attrs.get('height').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docImageType class docDotFileType(GeneratedsSuper): subclass = None superclass = None def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): self.name = name if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docDotFileType.subclass: return docDotFileType.subclass(*args_, **kwargs_) else: return docDotFileType(*args_, **kwargs_) factory = staticmethod(factory) def get_name(self): return self.name def set_name(self, name): self.name = name def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docDotFileType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docDotFileType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docDotFileType'): if self.name is not None: outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) def exportChildren(self, outfile, level, namespace_='', name_='docDotFileType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docDotFileType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.name is not None: showIndent(outfile, level) outfile.write('name = %s,\n' % (self.name,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('name'): self.name = attrs.get('name').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docDotFileType class docTocItemType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docTocItemType.subclass: return docTocItemType.subclass(*args_, **kwargs_) else: return docTocItemType(*args_, **kwargs_) factory = staticmethod(factory) def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docTocItemType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docTocItemType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docTocItemType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docTocItemType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docTocItemType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docTocItemType class docTocListType(GeneratedsSuper): subclass = None superclass = None def __init__(self, tocitem=None): if tocitem is None: self.tocitem = [] else: self.tocitem = tocitem def factory(*args_, **kwargs_): if docTocListType.subclass: return docTocListType.subclass(*args_, **kwargs_) else: return docTocListType(*args_, **kwargs_) factory = staticmethod(factory) def get_tocitem(self): return self.tocitem def set_tocitem(self, tocitem): self.tocitem = tocitem def add_tocitem(self, value): self.tocitem.append(value) def insert_tocitem(self, index, value): self.tocitem[index] = value def export(self, outfile, level, namespace_='', name_='docTocListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docTocListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docTocListType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docTocListType'): for tocitem_ in self.tocitem: tocitem_.export(outfile, level, namespace_, name_='tocitem') def hasContent_(self): if ( self.tocitem is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docTocListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('tocitem=[\n') level += 1 for tocitem in self.tocitem: showIndent(outfile, level) outfile.write('model_.tocitem(\n') tocitem.exportLiteral(outfile, level, name_='tocitem') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'tocitem': obj_ = docTocItemType.factory() obj_.build(child_) self.tocitem.append(obj_) # end class docTocListType class docLanguageType(GeneratedsSuper): subclass = None superclass = None def __init__(self, langid=None, para=None): self.langid = langid if para is None: self.para = [] else: self.para = para def factory(*args_, **kwargs_): if docLanguageType.subclass: return docLanguageType.subclass(*args_, **kwargs_) else: return docLanguageType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_langid(self): return self.langid def set_langid(self, langid): self.langid = langid def export(self, outfile, level, namespace_='', name_='docLanguageType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docLanguageType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docLanguageType'): if self.langid is not None: outfile.write(' langid=%s' % (self.format_string(quote_attrib(self.langid).encode(ExternalEncoding), input_name='langid'), )) def exportChildren(self, outfile, level, namespace_='', name_='docLanguageType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') def hasContent_(self): if ( self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docLanguageType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.langid is not None: showIndent(outfile, level) outfile.write('langid = %s,\n' % (self.langid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('langid'): self.langid = attrs.get('langid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) # end class docLanguageType class docParamListType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, parameteritem=None): self.kind = kind if parameteritem is None: self.parameteritem = [] else: self.parameteritem = parameteritem def factory(*args_, **kwargs_): if docParamListType.subclass: return docParamListType.subclass(*args_, **kwargs_) else: return docParamListType(*args_, **kwargs_) factory = staticmethod(factory) def get_parameteritem(self): return self.parameteritem def set_parameteritem(self, parameteritem): self.parameteritem = parameteritem def add_parameteritem(self, value): self.parameteritem.append(value) def insert_parameteritem(self, index, value): self.parameteritem[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def export(self, outfile, level, namespace_='', name_='docParamListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParamListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docParamListType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) def exportChildren(self, outfile, level, namespace_='', name_='docParamListType'): for parameteritem_ in self.parameteritem: parameteritem_.export(outfile, level, namespace_, name_='parameteritem') def hasContent_(self): if ( self.parameteritem is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParamListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parameteritem=[\n') level += 1 for parameteritem in self.parameteritem: showIndent(outfile, level) outfile.write('model_.parameteritem(\n') parameteritem.exportLiteral(outfile, level, name_='parameteritem') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'parameteritem': obj_ = docParamListItem.factory() obj_.build(child_) self.parameteritem.append(obj_) # end class docParamListType class docParamListItem(GeneratedsSuper): subclass = None superclass = None def __init__(self, parameternamelist=None, parameterdescription=None): if parameternamelist is None: self.parameternamelist = [] else: self.parameternamelist = parameternamelist self.parameterdescription = parameterdescription def factory(*args_, **kwargs_): if docParamListItem.subclass: return docParamListItem.subclass(*args_, **kwargs_) else: return docParamListItem(*args_, **kwargs_) factory = staticmethod(factory) def get_parameternamelist(self): return self.parameternamelist def set_parameternamelist(self, parameternamelist): self.parameternamelist = parameternamelist def add_parameternamelist(self, value): self.parameternamelist.append(value) def insert_parameternamelist(self, index, value): self.parameternamelist[index] = value def get_parameterdescription(self): return self.parameterdescription def set_parameterdescription(self, parameterdescription): self.parameterdescription = parameterdescription def export(self, outfile, level, namespace_='', name_='docParamListItem', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParamListItem') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docParamListItem'): pass def exportChildren(self, outfile, level, namespace_='', name_='docParamListItem'): for parameternamelist_ in self.parameternamelist: parameternamelist_.export(outfile, level, namespace_, name_='parameternamelist') if self.parameterdescription: self.parameterdescription.export(outfile, level, namespace_, name_='parameterdescription', ) def hasContent_(self): if ( self.parameternamelist is not None or self.parameterdescription is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParamListItem'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parameternamelist=[\n') level += 1 for parameternamelist in self.parameternamelist: showIndent(outfile, level) outfile.write('model_.parameternamelist(\n') parameternamelist.exportLiteral(outfile, level, name_='parameternamelist') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.parameterdescription: showIndent(outfile, level) outfile.write('parameterdescription=model_.descriptionType(\n') self.parameterdescription.exportLiteral(outfile, level, name_='parameterdescription') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'parameternamelist': obj_ = docParamNameList.factory() obj_.build(child_) self.parameternamelist.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'parameterdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_parameterdescription(obj_) # end class docParamListItem class docParamNameList(GeneratedsSuper): subclass = None superclass = None def __init__(self, parametername=None): if parametername is None: self.parametername = [] else: self.parametername = parametername def factory(*args_, **kwargs_): if docParamNameList.subclass: return docParamNameList.subclass(*args_, **kwargs_) else: return docParamNameList(*args_, **kwargs_) factory = staticmethod(factory) def get_parametername(self): return self.parametername def set_parametername(self, parametername): self.parametername = parametername def add_parametername(self, value): self.parametername.append(value) def insert_parametername(self, index, value): self.parametername[index] = value def export(self, outfile, level, namespace_='', name_='docParamNameList', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParamNameList') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docParamNameList'): pass def exportChildren(self, outfile, level, namespace_='', name_='docParamNameList'): for parametername_ in self.parametername: parametername_.export(outfile, level, namespace_, name_='parametername') def hasContent_(self): if ( self.parametername is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParamNameList'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parametername=[\n') level += 1 for parametername in self.parametername: showIndent(outfile, level) outfile.write('model_.parametername(\n') parametername.exportLiteral(outfile, level, name_='parametername') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'parametername': obj_ = docParamName.factory() obj_.build(child_) self.parametername.append(obj_) # end class docParamNameList class docParamName(GeneratedsSuper): subclass = None superclass = None def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): self.direction = direction if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docParamName.subclass: return docParamName.subclass(*args_, **kwargs_) else: return docParamName(*args_, **kwargs_) factory = staticmethod(factory) def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def get_direction(self): return self.direction def set_direction(self, direction): self.direction = direction def export(self, outfile, level, namespace_='', name_='docParamName', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParamName') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docParamName'): if self.direction is not None: outfile.write(' direction=%s' % (quote_attrib(self.direction), )) def exportChildren(self, outfile, level, namespace_='', name_='docParamName'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.ref is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParamName'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.direction is not None: showIndent(outfile, level) outfile.write('direction = "%s",\n' % (self.direction,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('direction'): self.direction = attrs.get('direction').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docParamName class docXRefSectType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, xreftitle=None, xrefdescription=None): self.id = id if xreftitle is None: self.xreftitle = [] else: self.xreftitle = xreftitle self.xrefdescription = xrefdescription def factory(*args_, **kwargs_): if docXRefSectType.subclass: return docXRefSectType.subclass(*args_, **kwargs_) else: return docXRefSectType(*args_, **kwargs_) factory = staticmethod(factory) def get_xreftitle(self): return self.xreftitle def set_xreftitle(self, xreftitle): self.xreftitle = xreftitle def add_xreftitle(self, value): self.xreftitle.append(value) def insert_xreftitle(self, index, value): self.xreftitle[index] = value def get_xrefdescription(self): return self.xrefdescription def set_xrefdescription(self, xrefdescription): self.xrefdescription = xrefdescription def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docXRefSectType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docXRefSectType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docXRefSectType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docXRefSectType'): for xreftitle_ in self.xreftitle: showIndent(outfile, level) outfile.write('<%sxreftitle>%s</%sxreftitle>\n' % (namespace_, self.format_string(quote_xml(xreftitle_).encode(ExternalEncoding), input_name='xreftitle'), namespace_)) if self.xrefdescription: self.xrefdescription.export(outfile, level, namespace_, name_='xrefdescription', ) def hasContent_(self): if ( self.xreftitle is not None or self.xrefdescription is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docXRefSectType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('xreftitle=[\n') level += 1 for xreftitle in self.xreftitle: showIndent(outfile, level) outfile.write('%s,\n' % quote_python(xreftitle).encode(ExternalEncoding)) level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.xrefdescription: showIndent(outfile, level) outfile.write('xrefdescription=model_.descriptionType(\n') self.xrefdescription.exportLiteral(outfile, level, name_='xrefdescription') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'xreftitle': xreftitle_ = '' for text__content_ in child_.childNodes: xreftitle_ += text__content_.nodeValue self.xreftitle.append(xreftitle_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'xrefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_xrefdescription(obj_) # end class docXRefSectType class docCopyType(GeneratedsSuper): subclass = None superclass = None def __init__(self, link=None, para=None, sect1=None, internal=None): self.link = link if para is None: self.para = [] else: self.para = para if sect1 is None: self.sect1 = [] else: self.sect1 = sect1 self.internal = internal def factory(*args_, **kwargs_): if docCopyType.subclass: return docCopyType.subclass(*args_, **kwargs_) else: return docCopyType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect1(self): return self.sect1 def set_sect1(self, sect1): self.sect1 = sect1 def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_link(self): return self.link def set_link(self, link): self.link = link def export(self, outfile, level, namespace_='', name_='docCopyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docCopyType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docCopyType'): if self.link is not None: outfile.write(' link=%s' % (self.format_string(quote_attrib(self.link).encode(ExternalEncoding), input_name='link'), )) def exportChildren(self, outfile, level, namespace_='', name_='docCopyType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') for sect1_ in self.sect1: sect1_.export(outfile, level, namespace_, name_='sect1') if self.internal: self.internal.export(outfile, level, namespace_, name_='internal') def hasContent_(self): if ( self.para is not None or self.sect1 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docCopyType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.link is not None: showIndent(outfile, level) outfile.write('link = %s,\n' % (self.link,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('sect1=[\n') level += 1 for sect1 in self.sect1: showIndent(outfile, level) outfile.write('model_.sect1(\n') sect1.exportLiteral(outfile, level, name_='sect1') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.internal: showIndent(outfile, level) outfile.write('internal=model_.docInternalType(\n') self.internal.exportLiteral(outfile, level, name_='internal') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('link'): self.link = attrs.get('link').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect1': obj_ = docSect1Type.factory() obj_.build(child_) self.sect1.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': obj_ = docInternalType.factory() obj_.build(child_) self.set_internal(obj_) # end class docCopyType class docCharType(GeneratedsSuper): subclass = None superclass = None def __init__(self, char=None, valueOf_=''): self.char = char self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if docCharType.subclass: return docCharType.subclass(*args_, **kwargs_) else: return docCharType(*args_, **kwargs_) factory = staticmethod(factory) def get_char(self): return self.char def set_char(self, char): self.char = char def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docCharType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docCharType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docCharType'): if self.char is not None: outfile.write(' char=%s' % (quote_attrib(self.char), )) def exportChildren(self, outfile, level, namespace_='', name_='docCharType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docCharType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.char is not None: showIndent(outfile, level) outfile.write('char = "%s",\n' % (self.char,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('char'): self.char = attrs.get('char').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docCharType class docEmptyType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if docEmptyType.subclass: return docEmptyType.subclass(*args_, **kwargs_) else: return docEmptyType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docEmptyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docEmptyType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docEmptyType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docEmptyType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docEmptyType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docEmptyType USAGE_TEXT = """ Usage: python <Parser>.py [ -s ] <in_xml_file> Options: -s Use the SAX parser, not the minidom parser. """ def usage(): print USAGE_TEXT sys.exit(1) def parse(inFileName): doc = minidom.parse(inFileName) rootNode = doc.documentElement rootObj = DoxygenType.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_="doxygen", namespacedef_='') return rootObj def parseString(inString): doc = minidom.parseString(inString) rootNode = doc.documentElement rootObj = DoxygenType.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_="doxygen", namespacedef_='') return rootObj def parseLiteral(inFileName): doc = minidom.parse(inFileName) rootNode = doc.documentElement rootObj = DoxygenType.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('from compound import *\n\n') sys.stdout.write('rootObj = doxygen(\n') rootObj.exportLiteral(sys.stdout, 0, name_="doxygen") sys.stdout.write(')\n') return rootObj def main(): args = sys.argv[1:] if len(args) == 1: parse(args[0]) else: usage() if __name__ == '__main__': main() #import pdb #pdb.run('main()')
shakamunyi/nova
refs/heads/master
nova/tests/unit/api/openstack/compute/__init__.py
12133432
typemytype/vanilla
refs/heads/master
Lib/vanilla/vanillaProgressSpinner.py
3
from AppKit import * from vanillaBase import VanillaBaseObject, _sizeStyleMap class ProgressSpinner(VanillaBaseObject): """ An animated, spinning progress indicator.:: from vanilla import * class ProgressSpinnerDemo(object): def __init__(self): self.w = Window((80, 52)) self.w.spinner = ProgressSpinner((24, 10, 32, 32), displayWhenStopped=True) self.w.spinner.start() self.w.open() ProgressSpinnerDemo() **posSize** Tuple of form *(left, top, width, height)* representing the position and size of the spinner. The size of the spinner sould match the appropriate value for the given *sizeStyle*. +---------------------------+ | **Standard Dimensions** | +---------+---+----+---+----+ | Regular | W | 32 | H | 32 | +---------+---+----+---+----+ | Small | W | 16 | H | 16 | +---------+---+----+---+----+ **displayWhenStopped** Boolean representing if the spiiner should be displayed when it is not spinning. **sizeStyle** A string representing the desired size style of the spinner. The options are: +-----------+ | "regular" | +-----------+ | "small" | +-----------+ """ nsProgressIndicatorClass = NSProgressIndicator def __init__(self, posSize, displayWhenStopped=False, sizeStyle="regular"): self._setupView(self.nsProgressIndicatorClass, posSize) sizeStyle = _sizeStyleMap[sizeStyle] self._nsObject.setControlSize_(sizeStyle) self._nsObject.setStyle_(NSProgressIndicatorSpinningStyle) self._nsObject.setDisplayedWhenStopped_(displayWhenStopped) def getNSProgressIndicator(self): """ Return the *NSProgressIndicator* that this object wraps. """ return self._nsObject def start(self): """ Start the animation. """ self._nsObject.startAnimation_(None) def stop(self): """ Stop the animation. """ self._nsObject.stopAnimation_(None)
llhe/tensorflow
refs/heads/master
tensorflow/contrib/keras/python/keras/utils/data_utils.py
8
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # ============================================================================== """Utilities for file download and caching.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import hashlib import os import shutil import sys import tarfile import zipfile import six from six.moves.urllib.error import HTTPError from six.moves.urllib.error import URLError from six.moves.urllib.request import urlopen from tensorflow.contrib.keras.python.keras.utils.generic_utils import Progbar if sys.version_info[0] == 2: def urlretrieve(url, filename, reporthook=None, data=None): """Replacement for `urlretrive` for Python 2. Under Python 2, `urlretrieve` relies on `FancyURLopener` from legacy `urllib` module, known to have issues with proxy management. Arguments: url: url to retrieve. filename: where to store the retrieved data locally. reporthook: a hook function that will be called once on establishment of the network connection and once after each block read thereafter. The hook will be passed three arguments; a count of blocks transferred so far, a block size in bytes, and the total size of the file. data: `data` argument passed to `urlopen`. """ def chunk_read(response, chunk_size=8192, reporthook=None): content_type = response.info().get('Content-Length') total_size = -1 if content_type is not None: total_size = int(content_type.strip()) count = 0 while 1: chunk = response.read(chunk_size) count += 1 if not chunk: reporthook(count, total_size, total_size) break if reporthook: reporthook(count, chunk_size, total_size) yield chunk response = urlopen(url, data) with open(filename, 'wb') as fd: for chunk in chunk_read(response, reporthook=reporthook): fd.write(chunk) else: from six.moves.urllib.request import urlretrieve # pylint: disable=g-import-not-at-top def _extract_archive(file_path, path='.', archive_format='auto'): """Extracts an archive if it matches tar, tar.gz, tar.bz, or zip formats. Arguments: file_path: path to the archive file path: path to extract the archive file archive_format: Archive format to try for extracting the file. Options are 'auto', 'tar', 'zip', and None. 'tar' includes tar, tar.gz, and tar.bz files. The default 'auto' is ['tar', 'zip']. None or an empty list will return no matches found. Returns: True if a match was found and an archive extraction was completed, False otherwise. """ if archive_format is None: return False if archive_format is 'auto': archive_format = ['tar', 'zip'] if isinstance(archive_format, six.string_types): archive_format = [archive_format] for archive_type in archive_format: if archive_type is 'tar': open_fn = tarfile.open is_match_fn = tarfile.is_tarfile if archive_type is 'zip': open_fn = zipfile.ZipFile is_match_fn = zipfile.is_zipfile if is_match_fn(file_path): with open_fn(file_path) as archive: try: archive.extractall(path) except (tarfile.TarError, RuntimeError, KeyboardInterrupt): if os.path.exists(path): if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) raise return True return False def get_file(fname, origin, untar=False, md5_hash=None, file_hash=None, cache_subdir='datasets', hash_algorithm='auto', extract=False, archive_format='auto', cache_dir=None): """Downloads a file from a URL if it not already in the cache. By default the file at the url `origin` is downloaded to the cache_dir `~/.keras`, placed in the cache_subdir `datasets`, and given the filename `fname`. The final location of a file `example.txt` would therefore be `~/.keras/datasets/example.txt`. Files in tar, tar.gz, tar.bz, and zip formats can also be extracted. Passing a hash will verify the file after download. The command line programs `shasum` and `sha256sum` can compute the hash. Arguments: fname: Name of the file. If an absolute path `/path/to/file.txt` is specified the file will be saved at that location. origin: Original URL of the file. untar: Deprecated in favor of 'extract'. boolean, whether the file should be decompressed md5_hash: Deprecated in favor of 'file_hash'. md5 hash of the file for verification file_hash: The expected hash string of the file after download. The sha256 and md5 hash algorithms are both supported. cache_subdir: Subdirectory under the Keras cache dir where the file is saved. If an absolute path `/path/to/folder` is specified the file will be saved at that location. hash_algorithm: Select the hash algorithm to verify the file. options are 'md5', 'sha256', and 'auto'. The default 'auto' detects the hash algorithm in use. extract: True tries extracting the file as an Archive, like tar or zip. archive_format: Archive format to try for extracting the file. Options are 'auto', 'tar', 'zip', and None. 'tar' includes tar, tar.gz, and tar.bz files. The default 'auto' is ['tar', 'zip']. None or an empty list will return no matches found. cache_dir: Location to store cached files, when None it defaults to the [Keras Directory](/faq/#where-is-the-keras-configuration-filed-stored). Returns: Path to the downloaded file """ if cache_dir is None: cache_dir = os.path.expanduser(os.path.join('~', '.keras')) if md5_hash is not None and file_hash is None: file_hash = md5_hash hash_algorithm = 'md5' datadir_base = os.path.expanduser(cache_dir) if not os.access(datadir_base, os.W_OK): datadir_base = os.path.join('/tmp', '.keras') datadir = os.path.join(datadir_base, cache_subdir) if not os.path.exists(datadir): os.makedirs(datadir) if untar: untar_fpath = os.path.join(datadir, fname) fpath = untar_fpath + '.tar.gz' else: fpath = os.path.join(datadir, fname) download = False if os.path.exists(fpath): # File found; verify integrity if a hash was provided. if file_hash is not None: if not validate_file(fpath, file_hash, algorithm=hash_algorithm): print('A local file was found, but it seems to be ' 'incomplete or outdated because the ' + hash_algorithm + ' file hash does not match the original value of ' + file_hash + ' so we will re-download the data.') download = True else: download = True if download: print('Downloading data from', origin) class ProgressTracker(object): # Maintain progbar for the lifetime of download. # This design was chosen for Python 2.7 compatibility. progbar = None def dl_progress(count, block_size, total_size): if ProgressTracker.progbar is None: if total_size is -1: total_size = None ProgressTracker.progbar = Progbar(total_size) else: ProgressTracker.progbar.update(count * block_size) error_msg = 'URL fetch failure on {}: {} -- {}' try: try: urlretrieve(origin, fpath, dl_progress) except URLError as e: raise Exception(error_msg.format(origin, e.errno, e.reason)) except HTTPError as e: raise Exception(error_msg.format(origin, e.code, e.msg)) except (Exception, KeyboardInterrupt) as e: if os.path.exists(fpath): os.remove(fpath) raise ProgressTracker.progbar = None if untar: if not os.path.exists(untar_fpath): _extract_archive(fpath, datadir, archive_format='tar') return untar_fpath if extract: _extract_archive(fpath, datadir, archive_format) return fpath def _hash_file(fpath, algorithm='sha256', chunk_size=65535): """Calculates a file sha256 or md5 hash. Example: ```python >>> from keras.data_utils import _hash_file >>> _hash_file('/path/to/file.zip') 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' ``` Arguments: fpath: path to the file being validated algorithm: hash algorithm, one of 'auto', 'sha256', or 'md5'. The default 'auto' detects the hash algorithm in use. chunk_size: Bytes to read at a time, important for large files. Returns: The file hash """ if (algorithm is 'sha256') or (algorithm is 'auto' and len(hash) is 64): hasher = hashlib.sha256() else: hasher = hashlib.md5() with open(fpath, 'rb') as fpath_file: for chunk in iter(lambda: fpath_file.read(chunk_size), b''): hasher.update(chunk) return hasher.hexdigest() def validate_file(fpath, file_hash, algorithm='auto', chunk_size=65535): """Validates a file against a sha256 or md5 hash. Arguments: fpath: path to the file being validated file_hash: The expected hash string of the file. The sha256 and md5 hash algorithms are both supported. algorithm: Hash algorithm, one of 'auto', 'sha256', or 'md5'. The default 'auto' detects the hash algorithm in use. chunk_size: Bytes to read at a time, important for large files. Returns: Whether the file is valid """ if ((algorithm is 'sha256') or (algorithm is 'auto' and len(file_hash) is 64)): hasher = 'sha256' else: hasher = 'md5' if str(_hash_file(fpath, hasher, chunk_size)) == str(file_hash): return True else: return False
cirlabs/heroku-buildpack-geodjango
refs/heads/master
vendor/distribute-0.6.36/tests/shlib_test/setup.py
87
from setuptools import setup, Extension, Library setup( name="shlib_test", ext_modules = [ Library("hellolib", ["hellolib.c"]), Extension("hello", ["hello.pyx"], libraries=["hellolib"]) ], test_suite="test_hello.HelloWorldTest", )
Yrthgze/prueba-sourcetree2
refs/heads/master
renzongxian/0023/mysite/guestbook/views.py
40
from django.shortcuts import render from guestbook.models import Messages import datetime def index(request): if request.method == 'POST': p = Messages(name=request.POST['name'], pub_date=datetime.datetime.now(), content=request.POST['content']) p.save() posted_messages = Messages.objects.order_by('-pub_date') context = {'posted_messages': posted_messages} return render(request, 'index.html', context)
holmes/intellij-community
refs/heads/master
python/helpers/pydev/pydev_ipython/version.py
142
# encoding: utf-8 """ Utilities for version comparison It is a bit ridiculous that we need these. """ #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from distutils.version import LooseVersion #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def check_version(v, check): """check version string v >= check If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date. """ try: return LooseVersion(v) >= LooseVersion(check) except TypeError: return True
Just-D/chromium-1
refs/heads/master
media/tools/layout_tests/layouttest_analyzer_helpers.py
120
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Helper functions for the layout test analyzer.""" from datetime import datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import fileinput import os import pickle import re import smtplib import socket import sys import time from bug import Bug from test_expectations_history import TestExpectationsHistory DEFAULT_TEST_EXPECTATION_PATH = ('trunk/LayoutTests/TestExpectations') LEGACY_DEFAULT_TEST_EXPECTATION_PATH = ( 'trunk/LayoutTests/platform/chromium/test_expectations.txt') REVISION_LOG_URL = ('http://build.chromium.org/f/chromium/perf/dashboard/ui/' 'changelog_blink.html?url=/trunk/LayoutTests/%s&range=%d:%d') DEFAULT_REVISION_VIEW_URL = 'http://src.chromium.org/viewvc/blink?revision=%s' class AnalyzerResultMap: """A class to deal with joined result produed by the analyzer. The join is done between layouttests and the test_expectations object (based on the test expectation file). The instance variable |result_map| contains the following keys: 'whole','skip','nonskip'. The value of 'whole' contains information about all layouttests. The value of 'skip' contains information about skipped layouttests where it has 'SKIP' in its entry in the test expectation file. The value of 'nonskip' contains all information about non skipped layout tests, which are in the test expectation file but not skipped. The information is exactly same as the one parsed by the analyzer. """ def __init__(self, test_info_map): """Initialize the AnalyzerResultMap based on test_info_map. Test_info_map contains all layouttest information. The job here is to classify them as 'whole', 'skip' or 'nonskip' based on that information. Args: test_info_map: the result map of |layouttests.JoinWithTestExpectation|. The key of the map is test name such as 'media/media-foo.html'. The value of the map is a map that contains the following keys: 'desc'(description), 'te_info' (test expectation information), which is a list of test expectation information map. The key of the test expectation information map is test expectation keywords such as "SKIP" and other keywords (for full list of keywords, please refer to |test_expectations.ALL_TE_KEYWORDS|). """ self.result_map = {} self.result_map['whole'] = {} self.result_map['skip'] = {} self.result_map['nonskip'] = {} if test_info_map: for (k, value) in test_info_map.iteritems(): self.result_map['whole'][k] = value if 'te_info' in value: # Don't count SLOW PASS, WONTFIX, or ANDROID tests as failures. if any([True for x in value['te_info'] if set(x.keys()) == set(['SLOW', 'PASS', 'Bugs', 'Comments', 'Platforms']) or 'WONTFIX' in x or x['Platforms'] == ['ANDROID']]): continue if any([True for x in value['te_info'] if 'SKIP' in x]): self.result_map['skip'][k] = value else: self.result_map['nonskip'][k] = value @staticmethod def GetDiffString(diff_map_element, type_str): """Get difference string out of diff map element. The difference string shows difference between two analyzer results (for example, a result for now and a result for sometime in the past) in HTML format (with colors). This is used for generating email messages. Args: diff_map_element: An element of the compared map generated by |CompareResultMaps()|. The element has two lists of test cases. One is for test names that are in the current result but NOT in the previous result. The other is for test names that are in the previous results but NOT in the current result. Please refer to comments in |CompareResultMaps()| for details. type_str: a string indicating the test group to which |diff_map_element| belongs; used for color determination. Must be 'whole', 'skip', or 'nonskip'. Returns: a string in HTML format (with colors) to show difference between two analyzer results. """ if not diff_map_element[0] and not diff_map_element[1]: return 'No Change' color = '' diff = len(diff_map_element[0]) - len(diff_map_element[1]) if diff > 0 and type_str != 'whole': color = 'red' else: color = 'green' diff_sign = '' if diff > 0: diff_sign = '+' if not diff: whole_str = 'No Change' else: whole_str = '<font color="%s">%s%d</font>' % (color, diff_sign, diff) colors = ['red', 'green'] if type_str == 'whole': # Bug 107773 - when we increase the number of tests, # the name of the tests are in red, it should be green # since it is good thing. colors = ['green', 'red'] str1 = '' for (name, _) in diff_map_element[0]: str1 += '<font color="%s">%s,</font>' % (colors[0], name) str2 = '' for (name, _) in diff_map_element[1]: str2 += '<font color="%s">%s,</font>' % (colors[1], name) if str1 or str2: whole_str += ':' if str1: whole_str += str1 if str2: whole_str += str2 # Remove the last occurrence of ','. whole_str = ''.join(whole_str.rsplit(',', 1)) return whole_str def GetPassingRate(self): """Get passing rate. Returns: layout test passing rate of this result in percent. Raises: ValueEror when the number of tests in test group "whole" is equal or less than that of "skip". """ delta = len(self.result_map['whole'].keys()) - ( len(self.result_map['skip'].keys())) if delta <= 0: raise ValueError('The number of tests in test group "whole" is equal or ' 'less than that of "skip"') return 100 - len(self.result_map['nonskip'].keys()) * 100.0 / delta def ConvertToCSVText(self, current_time): """Convert |self.result_map| into stats and issues text in CSV format. Both are used as inputs for Google spreadsheet. Args: current_time: a string depicting a time in year-month-day-hour format (e.g., 2011-11-08-16). Returns: a tuple of stats and issues_txt stats: analyzer result in CSV format that shows: (current_time, the number of tests, the number of skipped tests, the number of failing tests, passing rate) For example, "2011-11-10-15,204,22,12,94" issues_txt: issues listed in CSV format that shows: (BUGWK or BUGCR, bug number, the test expectation entry, the name of the test) For example, "BUGWK,71543,TIMEOUT PASS,media/media-element-play-after-eos.html, BUGCR,97657,IMAGE CPU MAC TIMEOUT PASS,media/audio-repaint.html," """ stats = ','.join([current_time, str(len(self.result_map['whole'].keys())), str(len(self.result_map['skip'].keys())), str(len(self.result_map['nonskip'].keys())), str(self.GetPassingRate())]) issues_txt = '' for bug_txt, test_info_list in ( self.GetListOfBugsForNonSkippedTests().iteritems()): matches = re.match(r'(BUG(CR|WK))(\d+)', bug_txt) bug_suffix = '' bug_no = '' if matches: bug_suffix = matches.group(1) bug_no = matches.group(3) issues_txt += bug_suffix + ',' + bug_no + ',' for test_info in test_info_list: test_name, te_info = test_info issues_txt += ' '.join(te_info.keys()) + ',' + test_name + ',' issues_txt += '\n' return stats, issues_txt def ConvertToString(self, prev_time, diff_map, issue_detail_mode): """Convert this result to HTML display for email. Args: prev_time: the previous time string that are compared against. diff_map: the compared map generated by |CompareResultMaps()|. issue_detail_mode: includes the issue details in the output string if this is True. Returns: a analyzer result string in HTML format. """ return_str = '' if diff_map: return_str += ( '<b>Statistics (Diff Compared to %s):</b><ul>' '<li>The number of tests: %d (%s)</li>' '<li>The number of failing skipped tests: %d (%s)</li>' '<li>The number of failing non-skipped tests: %d (%s)</li>' '<li>Passing rate: %.2f %%</li></ul>') % ( prev_time, len(self.result_map['whole'].keys()), AnalyzerResultMap.GetDiffString(diff_map['whole'], 'whole'), len(self.result_map['skip'].keys()), AnalyzerResultMap.GetDiffString(diff_map['skip'], 'skip'), len(self.result_map['nonskip'].keys()), AnalyzerResultMap.GetDiffString(diff_map['nonskip'], 'nonskip'), self.GetPassingRate()) if issue_detail_mode: return_str += '<b>Current issues about failing non-skipped tests:</b>' for (bug_txt, test_info_list) in ( self.GetListOfBugsForNonSkippedTests().iteritems()): return_str += '<ul>%s' % Bug(bug_txt) for test_info in test_info_list: (test_name, te_info) = test_info gpu_link = '' if 'GPU' in te_info: gpu_link = 'group=%40ToT%20GPU%20Mesa%20-%20chromium.org&' dashboard_link = ('http://test-results.appspot.com/dashboards/' 'flakiness_dashboard.html#%stests=%s') % ( gpu_link, test_name) return_str += '<li><a href="%s">%s</a> (%s) </li>' % ( dashboard_link, test_name, ' '.join( [key for key in te_info.keys() if key != 'Platforms'])) return_str += '</ul>\n' return return_str def CompareToOtherResultMap(self, other_result_map): """Compare this result map with the other to see if there are any diff. The comparison is done for layouttests which belong to 'whole', 'skip', or 'nonskip'. Args: other_result_map: another result map to be compared against the result map of the current object. Returns: a map that has 'whole', 'skip' and 'nonskip' as keys. Please refer to |diff_map| in |SendStatusEmail()|. """ comp_result_map = {} for name in ['whole', 'skip', 'nonskip']: if name == 'nonskip': # Look into expectation to get diff only for non-skipped tests. lookIntoTestExpectationInfo = True else: # Otherwise, only test names are compared to get diff. lookIntoTestExpectationInfo = False comp_result_map[name] = GetDiffBetweenMaps( self.result_map[name], other_result_map.result_map[name], lookIntoTestExpectationInfo) return comp_result_map @staticmethod def Load(file_path): """Load the object from |file_path| using pickle library. Args: file_path: the string path to the file from which to read the result. Returns: a AnalyzerResultMap object read from |file_path|. """ file_object = open(file_path) analyzer_result_map = pickle.load(file_object) file_object.close() return analyzer_result_map def Save(self, file_path): """Save the object to |file_path| using pickle library. Args: file_path: the string path to the file in which to store the result. """ file_object = open(file_path, 'wb') pickle.dump(self, file_object) file_object.close() def GetListOfBugsForNonSkippedTests(self): """Get a list of bugs for non-skipped layout tests. This is used for generating email content. Returns: a mapping from bug modifier text (e.g., BUGCR1111) to a test name and main test information string which excludes comments and bugs. This is used for grouping test names by bug. """ bug_map = {} for (name, value) in self.result_map['nonskip'].iteritems(): for te_info in value['te_info']: main_te_info = {} for k in te_info.keys(): if k != 'Comments' and k != 'Bugs': main_te_info[k] = True if 'Bugs' in te_info: for bug in te_info['Bugs']: if bug not in bug_map: bug_map[bug] = [] bug_map[bug].append((name, main_te_info)) return bug_map def SendStatusEmail(prev_time, analyzer_result_map, diff_map, receiver_email_address, test_group_name, appended_text_to_email, email_content, rev_str, email_only_change_mode): """Send status email. Args: prev_time: the date string such as '2011-10-09-11'. This format has been used in this analyzer. analyzer_result_map: current analyzer result. diff_map: a map that has 'whole', 'skip' and 'nonskip' as keys. The values of the map are the result of |GetDiffBetweenMaps()|. The element has two lists of test cases. One (with index 0) is for test names that are in the current result but NOT in the previous result. The other (with index 1) is for test names that are in the previous results but NOT in the current result. For example (test expectation information is omitted for simplicity), comp_result_map['whole'][0] = ['foo1.html'] comp_result_map['whole'][1] = ['foo2.html'] This means that current result has 'foo1.html' but it is NOT in the previous result. This also means the previous result has 'foo2.html' but it is NOT in the current result. receiver_email_address: receiver's email address. test_group_name: string representing the test group name (e.g., 'media'). appended_text_to_email: a text which is appended at the end of the status email. email_content: an email content string that will be shown on the dashboard. rev_str: a revision string that contains revision information that is sent out in the status email. It is obtained by calling |GetRevisionString()|. email_only_change_mode: send email only when there is a change if this is True. Otherwise, always send email after each run. """ if rev_str: email_content += '<br><b>Revision Information:</b>' email_content += rev_str localtime = time.asctime(time.localtime(time.time())) change_str = '' if email_only_change_mode: change_str = 'Status Change ' subject = 'Layout Test Analyzer Result %s(%s): %s' % (change_str, test_group_name, localtime) SendEmail('no-reply@chromium.org', [receiver_email_address], subject, email_content + appended_text_to_email) def GetRevisionString(prev_time, current_time, diff_map): """Get a string for revision information during the specified time period. Args: prev_time: the previous time as a floating point number expressed in seconds since the epoch, in UTC. current_time: the current time as a floating point number expressed in seconds since the epoch, in UTC. It is typically obtained by time.time() function. diff_map: a map that has 'whole', 'skip' and 'nonskip' as keys. Please refer to |diff_map| in |SendStatusEmail()|. Returns: a tuple of strings: 1) full string containing links, author, date, and line for each change in the test expectation file. 2) shorter string containing only links to the change. Used for trend graph annotations. 3) last revision number for the given test group. 4) last revision date for the given test group. """ if not diff_map: return ('', '', '', '') testname_map = {} for test_group in ['skip', 'nonskip']: for i in range(2): for (k, _) in diff_map[test_group][i]: testname_map[k] = True rev_infos = TestExpectationsHistory.GetDiffBetweenTimes(prev_time, current_time, testname_map.keys()) rev_str = '' simple_rev_str = '' rev = '' rev_date = '' if rev_infos: # Get latest revision number and date. rev = rev_infos[-1][1] rev_date = rev_infos[-1][3] for rev_info in rev_infos: (old_rev, new_rev, author, date, _, target_lines) = rev_info # test_expectations.txt was renamed to TestExpectations at r119317. new_path = DEFAULT_TEST_EXPECTATION_PATH if new_rev < 119317: new_path = LEGACY_DEFAULT_TEST_EXPECTATION_PATH old_path = DEFAULT_TEST_EXPECTATION_PATH if old_rev < 119317: old_path = LEGACY_DEFAULT_TEST_EXPECTATION_PATH link = REVISION_LOG_URL % (new_path, old_rev, new_rev) rev_str += '<ul><a href="%s">%s->%s</a>\n' % (link, old_rev, new_rev) simple_rev_str = '<a href="%s">%s->%s</a>,' % (link, old_rev, new_rev) rev_str += '<li>%s</li>\n' % author rev_str += '<li>%s</li>\n<ul>' % date for line in target_lines: # Find *.html pattern (test name) and replace it with the link to # flakiness dashboard. test_name_pattern = r'(\S+.html)' match = re.search(test_name_pattern, line) if match: test_name = match.group(1) gpu_link = '' if 'GPU' in line: gpu_link = 'group=%40ToT%20GPU%20Mesa%20-%20chromium.org&' dashboard_link = ('http://test-results.appspot.com/dashboards/' 'flakiness_dashboard.html#%stests=%s') % ( gpu_link, test_name) line = line.replace(test_name, '<a href="%s">%s</a>' % ( dashboard_link, test_name)) # Find bug text and replace it with the link to the bug. bug = Bug(line) if bug.bug_txt: line = '<li>%s</li>\n' % line.replace(bug.bug_txt, str(bug)) rev_str += line rev_str += '</ul></ul>' return (rev_str, simple_rev_str, rev, rev_date) def SendEmail(sender_email_address, receivers_email_addresses, subject, message): """Send email using localhost's mail server. Args: sender_email_address: sender's email address. receivers_email_addresses: receiver's email addresses. subject: subject string. message: email message. """ try: html_top = """ <html> <head></head> <body> """ html_bot = """ </body> </html> """ html = html_top + message + html_bot msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender_email_address msg['To'] = receivers_email_addresses[0] part1 = MIMEText(html, 'html') smtp_obj = smtplib.SMTP('localhost') msg.attach(part1) smtp_obj.sendmail(sender_email_address, receivers_email_addresses, msg.as_string()) print 'Successfully sent email' except smtplib.SMTPException, ex: print 'Authentication failed:', ex print 'Error: unable to send email' except (socket.gaierror, socket.error, socket.herror), ex: print ex print 'Error: unable to send email' def FindLatestTime(time_list): """Find latest time from |time_list|. The current status is compared to the status of the latest file in |RESULT_DIR|. Args: time_list: a list of time string in the form of 'Year-Month-Day-Hour' (e.g., 2011-10-23-23). Strings not in this format are ignored. Returns: a string representing latest time among the time_list or None if |time_list| is empty or no valid date string in |time_list|. """ if not time_list: return None latest_date = None for time_element in time_list: try: item_date = datetime.strptime(time_element, '%Y-%m-%d-%H') if latest_date is None or latest_date < item_date: latest_date = item_date except ValueError: # Do nothing. pass if latest_date: return latest_date.strftime('%Y-%m-%d-%H') else: return None def ReplaceLineInFile(file_path, search_exp, replace_line): """Replace line which has |search_exp| with |replace_line| within a file. Args: file_path: the file that is being replaced. search_exp: search expression to find a line to be replaced. replace_line: the new line. """ for line in fileinput.input(file_path, inplace=1): if search_exp in line: line = replace_line sys.stdout.write(line) def FindLatestResult(result_dir): """Find the latest result in |result_dir| and read and return them. This is used for comparison of analyzer result between current analyzer and most known latest result. Args: result_dir: the result directory. Returns: A tuple of filename (latest_time) and the latest analyzer result. Returns None if there is no file or no file that matches the file patterns used ('%Y-%m-%d-%H'). """ dir_list = os.listdir(result_dir) file_name = FindLatestTime(dir_list) if not file_name: return None file_path = os.path.join(result_dir, file_name) return (file_name, AnalyzerResultMap.Load(file_path)) def GetDiffBetweenMaps(map1, map2, lookIntoTestExpectationInfo=False): """Get difference between maps. Args: map1: analyzer result map to be compared. map2: analyzer result map to be compared. lookIntoTestExpectationInfo: a boolean to indicate whether to compare test expectation information in addition to just the test case names. Returns: a tuple of |name1_list| and |name2_list|. |Name1_list| contains all test name and the test expectation information in |map1| but not in |map2|. |Name2_list| contains all test name and the test expectation information in |map2| but not in |map1|. """ def GetDiffBetweenMapsHelper(map1, map2, lookIntoTestExpectationInfo): """A helper function for GetDiffBetweenMaps. Args: map1: analyzer result map to be compared. map2: analyzer result map to be compared. lookIntoTestExpectationInfo: a boolean to indicate whether to compare test expectation information in addition to just the test case names. Returns: a list of tuples (name, te_info) that are in |map1| but not in |map2|. """ name_list = [] for (name, value1) in map1.iteritems(): if name in map2: if lookIntoTestExpectationInfo and 'te_info' in value1: list1 = value1['te_info'] list2 = map2[name]['te_info'] te_diff = [item for item in list1 if not item in list2] if te_diff: name_list.append((name, te_diff)) else: name_list.append((name, value1)) return name_list return (GetDiffBetweenMapsHelper(map1, map2, lookIntoTestExpectationInfo), GetDiffBetweenMapsHelper(map2, map1, lookIntoTestExpectationInfo))
marktiu7/demo
refs/heads/master
dbtest/dbtest/urls.py
1
"""dbtest URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/dev/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] urlpatterns +=[ url(r'^blog/',include('blog.urls')), ]
mvidalgarcia/indico
refs/heads/master
indico/modules/rb/models/room_bookable_hours.py
2
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import time from indico.core.db import db from indico.util.string import return_ascii class BookableHours(db.Model): __tablename__ = 'room_bookable_hours' __table_args__ = {'schema': 'roombooking'} start_time = db.Column( db.Time, nullable=False, primary_key=True ) end_time = db.Column( db.Time, nullable=False, primary_key=True ) room_id = db.Column( db.Integer, db.ForeignKey('roombooking.rooms.id'), primary_key=True, nullable=False ) # relationship backrefs: # - room (Room.bookable_hours) @return_ascii def __repr__(self): return u'<BookableHours({0}, {1}, {2})>'.format( self.room_id, self.start_time, self.end_time ) def fits_period(self, st, et): st = _tuplify(st, False) et = _tuplify(et, True) period_st = _tuplify(self.start_time, False) period_et = _tuplify(self.end_time, True) return period_st <= st and period_et >= et def _tuplify(t, end): if end and t == time(0): return 24, 0 return t.hour, t.minute
liangazhou/django-rdp
refs/heads/master
packages/Django-1.8.6/django/db/models/aggregates.py
26
""" Classes to represent the definitions of aggregate functions. """ from django.core.exceptions import FieldError from django.db.models.expressions import Func, Star from django.db.models.fields import FloatField, IntegerField __all__ = [ 'Aggregate', 'Avg', 'Count', 'Max', 'Min', 'StdDev', 'Sum', 'Variance', ] class Aggregate(Func): contains_aggregate = True name = None def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): assert len(self.source_expressions) == 1 # Aggregates are not allowed in UPDATE queries, so ignore for_save c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize) if c.source_expressions[0].contains_aggregate and not summarize: name = self.source_expressions[0].name raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % ( c.name, name, name)) c._patch_aggregate(query) # backward-compatibility support return c @property def input_field(self): return self.source_expressions[0] @property def default_alias(self): if hasattr(self.source_expressions[0], 'name'): return '%s__%s' % (self.source_expressions[0].name, self.name.lower()) raise TypeError("Complex expressions require an alias") def get_group_by_cols(self): return [] def _patch_aggregate(self, query): """ Helper method for patching 3rd party aggregates that do not yet support the new way of subclassing. This method will be removed in Django 1.10. add_to_query(query, alias, col, source, is_summary) will be defined on legacy aggregates which, in turn, instantiates the SQL implementation of the aggregate. In all the cases found, the general implementation of add_to_query looks like: def add_to_query(self, query, alias, col, source, is_summary): klass = SQLImplementationAggregate aggregate = klass(col, source=source, is_summary=is_summary, **self.extra) query.aggregates[alias] = aggregate By supplying a known alias, we can get the SQLAggregate out of the aggregates dict, and use the sql_function and sql_template attributes to patch *this* aggregate. """ if not hasattr(self, 'add_to_query') or self.function is not None: return placeholder_alias = "_XXXXXXXX_" self.add_to_query(query, placeholder_alias, None, None, None) sql_aggregate = query.aggregates.pop(placeholder_alias) if 'sql_function' not in self.extra and hasattr(sql_aggregate, 'sql_function'): self.extra['function'] = sql_aggregate.sql_function if hasattr(sql_aggregate, 'sql_template'): self.extra['template'] = sql_aggregate.sql_template class Avg(Aggregate): function = 'AVG' name = 'Avg' def __init__(self, expression, **extra): super(Avg, self).__init__(expression, output_field=FloatField(), **extra) def convert_value(self, value, expression, connection, context): if value is None: return value return float(value) class Count(Aggregate): function = 'COUNT' name = 'Count' template = '%(function)s(%(distinct)s%(expressions)s)' def __init__(self, expression, distinct=False, **extra): if expression == '*': expression = Star() super(Count, self).__init__( expression, distinct='DISTINCT ' if distinct else '', output_field=IntegerField(), **extra) def __repr__(self): return "{}({}, distinct={})".format( self.__class__.__name__, self.arg_joiner.join(str(arg) for arg in self.source_expressions), 'False' if self.extra['distinct'] == '' else 'True', ) def convert_value(self, value, expression, connection, context): if value is None: return 0 return int(value) class Max(Aggregate): function = 'MAX' name = 'Max' class Min(Aggregate): function = 'MIN' name = 'Min' class StdDev(Aggregate): name = 'StdDev' def __init__(self, expression, sample=False, **extra): self.function = 'STDDEV_SAMP' if sample else 'STDDEV_POP' super(StdDev, self).__init__(expression, output_field=FloatField(), **extra) def __repr__(self): return "{}({}, sample={})".format( self.__class__.__name__, self.arg_joiner.join(str(arg) for arg in self.source_expressions), 'False' if self.function == 'STDDEV_POP' else 'True', ) def convert_value(self, value, expression, connection, context): if value is None: return value return float(value) class Sum(Aggregate): function = 'SUM' name = 'Sum' class Variance(Aggregate): name = 'Variance' def __init__(self, expression, sample=False, **extra): self.function = 'VAR_SAMP' if sample else 'VAR_POP' super(Variance, self).__init__(expression, output_field=FloatField(), **extra) def __repr__(self): return "{}({}, sample={})".format( self.__class__.__name__, self.arg_joiner.join(str(arg) for arg in self.source_expressions), 'False' if self.function == 'VAR_POP' else 'True', ) def convert_value(self, value, expression, connection, context): if value is None: return value return float(value)
akhilaananthram/nupic
refs/heads/master
scripts/profiling/enc_profile.py
35
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- ## run python -m cProfile --sort cumtime $NUPIC/scripts/profiling/enc_profile.py [nMaxValue nEpochs] import sys import numpy # chose desired Encoder implementations to compare: from nupic.encoders.scalar import ScalarEncoder from nupic.encoders.random_distributed_scalar import RandomDistributedScalarEncoder as RDSE def profileEnc(maxValue, nRuns): minV=0 maxV=nRuns # generate input data data=numpy.random.randint(minV, maxV+1, nRuns) # instantiate measured encoders encScalar = ScalarEncoder(w=21, minval=minV, maxval=maxV, resolution=1) encRDSE = RDSE(resolution=1) # profile! for d in data: encScalar.encode(d) encRDSE.encode(d) print "Scalar n=",encScalar.n," RDSE n=",encRDSE.n if __name__ == "__main__": maxV=500 epochs=10000 if len(sys.argv) == 3: # 2 args + name columns=int(sys.argv[1]) epochs=int(sys.argv[2]) profileEnc(maxV, epochs)