def visit_For(self, node): forel = ET.Element("for") if node.init is not None: initel = E.init() initel.extend(self.visit(node.init)) forel.append(initel) if node.init is None: forel.extend(E.init()) elif isinstance(node.init, (ast.Assign, ast.Comma, ast.FunctionCall, ast.UnaryOp, ast.Identifier, ast.BinOp, ast.Conditional, ast.Regex, ast.NewExpr)): pass else: pass if node.cond is not None: condition = E.condition() condition.extend(self.visit(node.cond)) forel.append(condition) if node.count is not None: post = E.post() post.extend(self.visit(node.count)) forel.append(post) statement = E.statement() statement.extend(self.visit(node.statement)) forel.append(statement) return [forel]
def _r_catalog(self): get = E.applications(E.application()) got = self.R.get_config(get) for app in got.xpath("applications/application"): name = app.findtext("name") self._rcatalog[name] = {} self._xml_to_py(app, self._rcatalog[name])
def _testcases_for_task(task): if not task.is_finished(): return yield E.testcase( E(u'system-out', _systemout_for_task(task)), classname=task.name) for result in task.results: testcase = E.testcase( classname=task.name, name=result.short_path.lstrip('/') or '(none)') if result.duration: testcase.set('time', '%.0f' % total_seconds(result.duration)) # For Cancelled and Aborted, the final Warn is the reason message if (task.status == TaskStatus.cancelled and result == task.results[-1] and result.result == TaskResult.warn): testcase.append(E.skipped(message=result.log or u'', type=u'skipped')) elif (task.status == TaskStatus.aborted and result == task.results[-1] and result.result == TaskResult.warn): testcase.append(E.error(message=result.log or u'', type=u'error')) elif result.result in (TaskResult.warn, TaskResult.fail): testcase.append(E.failure(message=result.log or u'', type=u'failure')) testcase.append(E(u'system-out', _systemout_for_result(result))) yield testcase
def visit_Label(self, node): identifier = self.visit(node.identifier)[0] label = E.label(name=identifier.get("name")) statement = E.statement() statement.extend(self.visit(node.statement)) label.append(statement) return [label]
def _pull_to_parent(self, ctx, cls, inst, parent, name, parent_inst=None, label_attrs=None, parent_key=None, no_label=False, **kwargs): key = self.selsafe(name) attr = get_cls_attrs(self, cls) if inst is None: inst = [] for i, subval in enumerate(inst): new_key = '%s[%09d]' % (key, i) with parent.element('div', {"class": key}): ret = self.to_parent(ctx, cls, subval, parent, new_key, parent_inst=parent_inst, no_label=True, from_arr=True, **kwargs) if not attr.no_write: parent.write(E.button('+', **{ "class": key + "_btn_add", 'type': 'button'})) parent.write(E.button('-', **{ "class": key + "_btn_del", 'type': 'button'})) if isgenerator(ret): try: while True: sv2 = (yield) ret.send(sv2) except Break as b: try: ret.throw(b) except StopIteration: pass if not attr.no_write: _gen_array_js(parent, key)
def make_famname(famname, context): encodinganalog = famname.get("tag","") if context == "origination": atts = {"encodinganalog":encodinganalog} elif context == "controlaccess": source_mappings = {"0": "lcnaf", "4":"local"} source_indicator = famname.get("ind2", "") if source_indicator in source_mappings: source = source_mappings[source_indicator] else: source = "local" atts = {"source":source, "encodinganalog":encodinganalog} famname_element = E.famname(atts) famname_mappings = {"a":"family_name", "d":"dates", "c":"qualifier"} for subfield in famname.xpath("./marc:subfield", namespaces=ns): code = subfield.get("code", "") if code in famname_mappings: tag = famname_mappings[code] element = etree.Element(tag) element.text = subfield.text.strip().rstrip(".").rstrip(",") famname_element.append(element) term_mappings = {"t": "uniform_title", "v":"genre_form", "x": "topical", "y": "temporal", "z": "geographic"} for subfield in famname.xpath("./marc:subfield", namespaces=ns): code = subfield.get("code", "") if code in term_mappings: term_type = term_mappings[code] term = E.term({"type":term_type}, subfield.text.strip()) famname_element.append(term) return famname_element
def _get_forward_elem(**kwargs): """ <forward mode='hostdev' dev='eth0' managed='yes'> </forward> """ if "mode" in kwargs.keys() and kwargs['mode'] is None: return None forward = E.forward() if 'mode' in kwargs.keys(): forward.set('mode', kwargs['mode']) if kwargs['mode'] == 'vepa': devs = kwargs['devs'] forward.set('dev', devs[0]) for dev in devs: interface = E.interface() interface.set('dev', dev) forward.append(interface) if 'dev' in kwargs.keys(): forward.set('dev', kwargs['dev']) if 'managed' in kwargs.keys(): forward.set('managed', kwargs['managed']) return forward
def test_match_field(self): bar = E.field(name="bar") node = self.env['ir.ui.view'].locate_node( E.root(E.field(name="foo"), bar, E.field(name="baz")), E.field(name="bar"), ) self.assertIs(node, bar)
def make_subject(subject, term_types, indicator_sources, alternate_sources): encodinganalog = subject.get("tag","") atts = {"encodinganalog":encodinganalog, "source":"local"} indicator_source_found = False if indicator_sources: indicator = subject.get("ind2", "") if indicator in indicator_sources: source = indicator_sources[indicator] atts["source"] = source.strip(".").strip("]") indicator_source_found = True if alternate_sources and not indicator_source_found: for code in alternate_sources: if subject.xpath("./marc:subfield[@code={}]".format(code), namespaces=ns): source = subject.xpath("./marc:subfield[@code={}]".format(code), namespaces=ns)[0].text.strip() atts["source"] = source.rstrip(".").strip("]") subject_element = E.subject(atts) for subfield in subject.xpath("./marc:subfield", namespaces=ns): code = subfield.get("code", "") if code in term_types: term_type = term_types[code] term_text = subfield.text.strip() term = E.term({"type":term_type}, term_text) subject_element.append(term) return subject_element
def test_match_xpath(self): bar = E.bar() node = self.env['ir.ui.view'].locate_node( E.root(E.foo(), bar, E.baz()), E.xpath(expr="//bar"), ) self.assertIs(node, bar)
def test_view_inheritance_divergent_models(self): view1 = self.View.create({ 'name': "bob", 'model': 'ir.ui.view.custom', 'arch': """ <form string="Base title" version="7.0"> <separator name="separator" string="Separator" colspan="4"/> <footer> <button name="action_next" type="object" string="Next button" class="btn-primary"/> <button string="Skip" special="cancel" class="btn-default"/> </footer> </form> """ }) view2 = self.View.create({ 'name': "edmund", 'model': 'ir.ui.view', 'inherit_id': view1.id, 'arch': """ <data> <form position="attributes" version="7.0"> <attribute name="string">Replacement title</attribute> </form> <footer position="replace"> <footer> <button name="action_next" type="object" string="New button"/> </footer> </footer> <separator name="separator" position="replace"> <p>Replacement data</p> </separator> </data> """ }) view3 = self.View.create({ 'name': 'jake', 'model': 'ir.ui.menu', 'inherit_id': view1.id, 'priority': 17, 'arch': """ <footer position="attributes"> <attribute name="thing">bob</attribute> </footer> """ }) view = self.View.with_context(check_view_ids=[view2.id, view3.id]) \ .fields_view_get(view2.id, view_type='form') self.assertEqual(view['type'], 'form') self.assertEqual( etree.fromstring( view['arch'], parser=etree.XMLParser(remove_blank_text=True) ), E.form( E.p("Replacement data"), E.footer( E.button(name="action_next", type="object", string="New button")), string="Replacement title", version="7.0" ))
def test_match_other(self): bar = E.bar() node = self.env['ir.ui.view'].locate_node( E.root(E.foo(), bar, E.baz()), E.bar(), ) self.assertIs(bar, node)
def test_invalid_position(self): spec = E.field( E.field(name="whoops"), name="target", position="serious_series") with self.assertRaises(ValueError): self.View.apply_inheritance_specs(self.base_arch, spec, None)
def _r_catalog(self): get = E.security(E.nat(E.static(E("rule-set", E.name(self.P._name))))) got = self.J.rpc.get_config(get) for rule in got.xpath(".//rule"): name = rule.find("name").text self._rcatalog[name] = {} self._xml_to_py(rule, self._rcatalog[name])
def _create_task(self, cb, params): """Asynchronous function which actually creates the snapshot. Parameters: cb -- a callback function to signal the Task's progress. params -- a dict with the following values: "vm_name": the name of the VM where the snapshot will be created. "name": the snapshot name. """ vm_name = params['vm_name'] name = params['name'] cb('building snapshot XML') root_elem = E.domainsnapshot() root_elem.append(E.name(name)) xml = ET.tostring(root_elem, encoding='utf-8') try: cb('fetching snapshot domain') vir_dom = VMModel.get_vm(vm_name, self.conn) cb('creating snapshot') vir_dom.snapshotCreateXML(xml, 0) except (NotFoundError, OperationFailed, libvirt.libvirtError), e: raise OperationFailed('KCHSNAP0002E', {'name': name, 'vm': vm_name, 'err': e.message})
def visit_Switch(self, node): switch = E.switch(E.expression(self.visit(node.expr))) for case in node.cases: switch.append(self.visit_Case(case)) if node.default is not None: switch.append(self.visit_Default(node.default)) return switch
def visit_Identifier(self, node): if isinstance(node.value, (int, float)): return E.identifier(node.value) elif isinstance(node.value, (str, unicode)): if node.value == "undefined": return E.undefined() return E.identifier(node.value)
def _get_iscsi_disks_xml(self): def build_disk_xml(children=[]): disk = E.disk(type='volume', device='disk') disk.extend(children) return etree.tostring(disk) ret = "" children = [] auth = self._get_storage_auth() if auth: etree_auth = E.auth(username=auth['username']) etree_auth.append(E.secret(type=auth['type'], usage=auth['libvirtiscsi'])) children.append(etree_auth) children.append(E.driver(name='qemu', type='raw')) disk_bus = self.info['disk_bus'] dev_prefix = self._bus_to_dev[disk_bus] pool_name = pool_name_from_uri(self.info['storagepool']) for i, d in enumerate(self.info['disks']): source = E.source(pool=pool_name, volume=d.get('volume'), mode='host') # FIXME if more than 26 disks target = E.target(dev=dev_prefix + string.lowercase[i], bus=disk_bus) ret += build_disk_xml(children+[source, target]) return ret
def __call__(self, user, version, last_sync=None, app=None): """ Generates a report fixture for mobile that can be used by a report module """ if not toggles.MOBILE_UCR.enabled(user.domain): return [] apps = [app] if app else (a for a in get_apps_in_domain(user.domain, include_remote=False)) report_configs = [ report_config for app_ in apps for module in app_.modules if isinstance(module, ReportModule) for report_config in module.report_configs ] if not report_configs: return [] root = E.fixture(id=self.id) reports_elem = E.reports(last_sync=datetime.utcnow().isoformat()) for report_config in report_configs: try: reports_elem.append(self._report_config_to_fixture(report_config, user)) except BadReportConfigurationError as err: logging.exception('Error generating report fixture: {}'.format(err)) continue except UserReportsError: if settings.UNIT_TESTING or settings.DEBUG: raise except Exception as err: logging.exception('Error generating report fixture: {}'.format(err)) if settings.UNIT_TESTING or settings.DEBUG: raise root.append(reports_elem) return [root]
def extra_response_parts(self): contents = [] if self.highlighting: contents.append( E.lst({'name':'highlighting'}, E.lst({'name':'0'}, E.arr({'name':'string_field'}, E.str('zero')))) ) return contents
def _get_any_select_question_node(tag, name_, groups_=None, choices_=None, **params_): """ Return a question node for a single- or multiple-select multiple choice question e.g. <select ref="/data/multiple_answer_multichoice"> <label ref="jr:itext('multiple_answer_multichoice-label')" /> <item> <label ref="jr:itext('multiple_answer_multichoice-choice1-label')" /> <value>choice1</value> </item> <item> <label ref="jr:itext('multiple_answer_multichoice-choice2-label')" /> <value>choice2</value> </item> </select> """ node_ = etree.Element(tag, {'ref': self.get_data_ref(name_, groups_)}) node_.append(E.label({'ref': "jr:itext('{}')".format(self.get_text_id(name_, groups_))})) if 'hint' in params_: node_.append( E.hint({'ref': "jr:itext('{}')".format(self.get_text_id(name_, groups_, is_hint=True))}) ) for choice_name in choices_.keys(): node_.append( E.item( E.label({'ref': "jr:itext('{}')".format(self.get_text_id(name_, groups_, choice_name))}), E.value(choice_name if isinstance(choice_name, six.string_types) else str(choice_name)) ) ) return node_
def test_non_tagbag(self): cloth = E.a( E.b( E.c( E.d( spyne_id="i", ), spyne_id="c", ), spyne_id="i", ), spyne_tagbag='', ) class C2(ComplexModel): i = Integer class C1(ComplexModel): i = Integer c = C2 elt = self._run(C1(i=1, c=C2(i=2)), cloth=cloth) assert elt.xpath('//b/text()') == ['1'] # no order guarantee is given assert set(elt.xpath('//d/text()')) == set(['1', '2'])
def _xml_at_top(self): return E.security(E.zones( E('security-zone', E.name(self.P._name), E.interfaces(E.name(self._name)) ) ))
def _xml_change_addr_from(self, xml): # we need to always set the address/name given the structure of the # Junos configuration XML, derp. addr_from = self.should.get('addr_from') or self.has.get('addr_from') xml.append(E.address(JXML.REPLACE, E.name( addr_from ))) return True
def _r_catalog(self): get = E.security( E.nat( E.source( E.pool ))) got = self.J.rpc.get_config( get ) for pool in got.xpath('.//pool'): name = pool.find('name').text self._rcatalog[name] = {} self._xml_to_py( pool, self._rcatalog[name] )
def get_disk_xml(params): """ <disk type='file' device='cdrom'> <driver name='qemu' type='raw'/> [source XML according to src_type] <target dev='%(dev)s' bus='%(bus)s'/> <readonly/> </disk> """ path = params['path'] disk_type = params.get('disk', None) if disk_type is None: disk_type = _get_disk_type(path) if len(path) > 0 else 'file' disk = E.disk(type=disk_type, device=params['type']) driver = E.driver(name='qemu', type=params['format']) try: fd = os.open(path, os.O_RDONLY | os.O_DIRECT) os.close(fd) wok_log.debug("Disk '%s' supports direct I/O. Setting cache=none" "to enable live migration" % path) except OSError, e: if e.errno == errno.EINVAL: wok_log.debug("Disk '%s' does not support direct I/O: " "'%s'. Let libvirt sets the default cache mode." % (path, e.message))
def search(request, search_string, format="json"): """ Search the DB and return the result as JSON or XML. """ database = pymongo.Connection("localhost", 27017).symdex collection = database.libraries result = [] for i in collection.find({"symbols": {"$regex": search_string}}): package = i.get("package", None) library = i.get("library", None) if package and library: result.append((package, library)) result = sorted(result, key=lambda x: x[0]) result_dict = {} for key, values_iter in groupby(result, lambda x: x[0]): result_dict[key] = list(set([i[1] for i in list(values_iter)])) if format == "xml": root = E.results() for package, libraries in result_dict.items(): package_root = E.package(name=smart_unicode(package)) for library in libraries: package_root.append(E.libary(smart_unicode(library))) root.append(package_root) result_string, content_type = etree.tostring(root), "application/xml" else: result_string, content_type = (simplejson.dumps(result_dict), "application/json") return HttpResponse(result_string, content_type=content_type)
def requests(self, reqs): requests = E.requests() postdata = {} for req in reqs: requests.append(req.tree) postdata.update(req.form) tree = ( E.client( requests ) ) xml = etree.tostring(tree, encoding='UTF-8', xml_declaration=True) # declaration uses ' instead of " globaldata = { 'client_version': config.client_version, 'xml': xml } postdata.update(globaldata) r = self.s.post('https://client.whatpulse.org/v1.1/', verify='whatpulse.pem', data=postdata) print(r.text) tree = etree.fromstring(r.text, self.parser) ress = tree.xpath('/server/responses/response') ret = [] for res in ress: ret.append(Response.parse(res)) return ret
def visit_BracketAccessor(self, node): objel = E.object() objel.extend(self.visit(node.node)) propel = E.property() propel.extend(self.visit(node.expr)) bracket = E.bracketaccessor(objel, propel) return [bracket]
def _r_catalog(self): get = E.applications(E.application()) got = self.N.rpc.get_config( get ) for app in got.xpath('applications/application'): name = app.findtext('name') self._rcatalog[name] = {} self._xml_to_py( app, self._rcatalog[name] )
def test_view_inheritance_divergent_models(self): Views = self.registry('ir.ui.view') v1 = Views.create( self.cr, self.uid, { 'name': "bob", 'model': 'ir.ui.view.custom', 'arch': """ <form string="Base title" version="7.0"> <separator string="separator" colspan="4"/> <footer> <button name="action_next" type="object" string="Next button"/> or <button string="Skip" special="cancel" /> </footer> </form> """ }) v2 = Views.create( self.cr, self.uid, { 'name': "edmund", 'model': 'ir.ui.view', 'inherit_id': v1, 'arch': """ <data> <form position="attributes" version="7.0"> <attribute name="string">Replacement title</attribute> </form> <footer position="replace"> <footer> <button name="action_next" type="object" string="New button"/> </footer> </footer> <separator string="separator" position="replace"> <p>Replacement data</p> </separator> </data> """ }) v3 = Views.create( self.cr, self.uid, { 'name': 'jake', 'model': 'ir.ui.menu', 'inherit_id': v1, 'priority': 17, 'arch': """ <footer position="attributes"> <attribute name="thing">bob</attribute> </footer> """ }) view = self.registry('ir.ui.view').fields_view_get( self.cr, self.uid, v2, view_type='form', context={ # f*****g what? 'check_view_ids': [v2, v3] }) self.assertEqual(view['type'], 'form') self.assertEqual( ET.fromstring(view['arch'], parser=ET.XMLParser(remove_blank_text=True)), E.form(E.p("Replacement data"), E.footer( E.button(name="action_next", type="object", string="New button")), string="Replacement title", version="7.0"))
def test_p(self): self.assertEqual("foo\n\nbar\n\nbaz", html_to_text(E.div("foo", E.p("bar"), "baz"))) self.assertEqual("foo", html_to_text(E.div(E.p("foo")))) self.assertEqual("foo\n\nbar", html_to_text(E.div("foo", E.p("bar")))) self.assertEqual("foo\n\nbar", html_to_text(E.div(E.p("foo"), "bar"))) self.assertEqual( "foo\n\nbar\n\nbaz", html_to_text(E.div( E.p("foo"), E.p("bar"), E.p("baz"), )))
def test_br(self): self.assertEqual("foo\nbar", html_to_text(E.div("foo", E.br(), "bar"))) self.assertEqual( "foo\n\nbar\nbaz", html_to_text(E.div("foo", E.br(), E.br(), "bar", E.br(), "baz")))
def test_rawstring(self): self.assertEqual("foobar", html_to_text(E.div("foobar")))
def triada(itm): a, b, c = itm return E.Triada(a = str(a), b = str(b), c = str(c))
from lxml import etree from lxml.builder import E camera_matrix=[[ 532.80990646 ,0.0,342.49522219],[0.0,532.93344713,233.88792491],[0.0,0.0,1.0]] dist_coeff = [-2.81325798e-01,2.91150014e-02,1.21234399e-03,-1.40823665e-04,1.54861424e-01] def triada(itm): a, b, c = itm return E.Triada(a = str(a), b = str(b), c = str(c)) camera_matrix_xml = E.CameraMatrix(*map(triada, camera_matrix)) dist_coeff_xml = E.DistCoef(*map(E.Coef, map(str, dist_coeff))) xmldoc = E.CameraData(camera_matrix_xml, dist_coeff_xml) fname = "data.xml" with open(fname, "w") as f: f.write(etree.tostring(xmldoc, pretty_print=True))
def test_match_field(self): bar = Field(name="bar") node = self.Views.locate_node( E.root(Field(name="foo"), bar, Field(name="baz")), Field(name="bar")) self.assertIs(node, bar)
def test_branding_distribute_inner(self): """ Checks that the branding is correctly distributed within a view extension """ Views = self.registry('ir.ui.view') id = Views.create( self.cr, self.uid, { 'name': "Base view", 'type': 'qweb', 'arch': """<root> <item order="1"/> </root>""" }) id2 = Views.create( self.cr, self.uid, { 'name': "Extension", 'type': 'qweb', 'inherit_id': id, 'arch': """<xpath expr="//item" position="before"> <item order="2"> <content t-att-href="foo">bar</content> </item> </xpath>""" }) arch_string = Views.read_combined(self.cr, self.uid, id, fields=['arch'], context={'inherit_branding': True})['arch'] arch = ET.fromstring(arch_string) Views.distribute_branding(arch) self.assertEqual( arch, E.root( E.item( E.content( "bar", { 't-att-href': "foo", 'data-oe-model': 'ir.ui.view', 'data-oe-id': str(id2), 'data-oe-field': 'arch', 'data-oe-xpath': '/xpath/item/content[1]', 'data-oe-source-id': str(id) }), { 'order': '2', }), E.item({ 'order': '1', 'data-oe-model': 'ir.ui.view', 'data-oe-id': str(id), 'data-oe-field': 'arch', 'data-oe-xpath': '/root[1]/item[1]' })))
def test_applied_state_toggle(self): """ Change active states of v2 and v3, check that the results are as expected """ self.browse(self.v2).toggle() arch = self.read_combined(self.v0)['arch'] self.assertEqual(ET.fromstring(arch), E.qweb( E.base(), E.v1(), )) self.browse(self.v3).toggle() arch = self.read_combined(self.v0)['arch'] self.assertEqual(ET.fromstring(arch), E.qweb( E.base(), E.v1(), E.v3(), )) self.browse(self.v2).toggle() arch = self.read_combined(self.v0)['arch'] self.assertEqual(ET.fromstring(arch), E.qweb( E.base(), E.v1(), E.v2(), E.v3(), ))
def test_match_xpath(self): bar = E.bar() node = self.Views.locate_node(E.root(E.foo(), bar, E.baz()), E.xpath(expr="//bar")) self.assertIs(node, bar)
def test_match_other(self): bar = E.bar() node = self.Views.locate_node(E.root(E.foo(), bar, E.baz()), E.bar()) self.assertIs(bar, node)
def setUp(self): super(TestApplyInheritanceSpecs, self).setUp() self.View = self.registry('ir.ui.view') self.base_arch = E.form(Field(name="target"), string="Title")
def _parse_post(self, post_node, task, is_op_post=False, show_images=True, render_xhtml=True, thread_id=None): post = {} label = post_node.find("label") if is_op_post: title_class = "filetitle" else: title_class = "replytitle" title = label.find("span[@class='%s']" % title_class) if title is None: post["title"] = "" else: post["title"] = title.text if is_op_post: author_node_class = "postername" else: author_node_class = "commentpostername" author_node = label.find("span[@class='%s']" % author_node_class) author_email_node = author_node.find("a") if author_email_node is None: post["author_email"] = "" post["author_name"] = author_node.text else: post["author_email"] = author_email_node.get("href") post["author_name"] = author_email_node.text if not post["author_name"]: post["author_name"] = "" trip_node = label.find("span[@class='postertrip']") if trip_node is None: post["trip_text"] = "" post["trip_email"] = "" post["date"] = author_node.tail.strip() else: trip_email_node = trip_node.find("a") if trip_email_node is None: post["trip_text"] = trip_node.text post["trip_email"] = "" else: post["trip_text"] = trip_email_node.text post["trip_email"] = trip_email_node.get("href") post["date"] = trip_node.tail.strip() post["id"] = post_node.find("a[@name]").get("name") filesize_node = post_node.find("span[@class='filesize']") if filesize_node is None: post["img_src"] = "" else: em_node = filesize_node.find("em") # TODO: parse it right. if em_node is None: post["img_src"] = "" else: host = "http://" + task["host"] img_a = filesize_node.find("a") post["img_src"] = host + img_a.get("href") post["img_name"] = img_a.text post["img_size"] = em_node.text img_thumb = post_node.find(".//img[@class='thumb']") post["img_thumb_src"] = host + img_thumb.get("src") # Body post_body_node = post_node.find("blockquote") body = [] post["body_xhtml"] = E.span() for node in post_body_node: s = "" tag = E.span() if (node.tag == "blockquote" and node.get("class") == "unkfunc"): tag.set("style", "color: #789922;") elif (node.tag == "div" and node.get("class") == "abbrev"): tag.set("style", "color: #707070;") elif node.tag == "pre": tag.set("style", "font-family: monospace;") node = node[0] # Should be E.p() without additional brs but # xmpp clients processing it incorrect. tag.extend((E.br(), E.br())) if node.text: s += node.text tag[-1].tail = node.text # TODO: <strong><em>bold and italic</em></strong> # TODO: ul, ol for child in node: if child.tag == "a": s += child.text url = child.get("href") if url.startswith("/"): url = "http://" + task["host"] + url tag.append(E.a(child.text, href=url)) elif child.tag == "br": s += "\n" tag.append(E.br()) elif child.tag == "strong": s += "*%s*" % child.text tag.append( E.span(child.text, style="font-weight: bold;")) elif child.tag == "em": # TODO: baaaad hack, fix it! if child.text is None: child.text = "" s += "/%s/" % child.text tag.append( E.span(child.text, style="font-style: italic;")) elif child.tag == "del": s += "-%s-" % child.text tag.append(E.span( child.text, style="text-decoration: line-through;")) elif child.tag == "code": s += child.text tag.append( E.span(child.text, style="font-family: monospace;")) elif child.tag == "span" and child.get("class") == "spoiler": s += "%%%%%s%%%%" % child.text tag.append(E.span( child.text, style="color: #F0D0B6; background-color: #F0D0B6;")) if child.tail: s += child.tail tag[-1].tail = child.tail body.append(s) post["body_xhtml"].append(tag) post["body"] = u"\n\n".join(body) return self._format_post( post, task, show_images, render_xhtml, thread_id)
def test_attribute_filter(self): match = E.bar(attr='2') node = self.Views.locate_node( E.root(E.bar(attr='1'), match, E.root(E.bar(attr='3'))), E.bar(attr='2')) self.assertIs(node, match)
def _update_user_groups_view(self): super(GroupsView,self)._update_user_groups_view() """ Modify the view with xmlid ``base.user_groups_view``, which inherits the user form view, and introduces the reified group fields. """ # remove the language to avoid translations, it will be handled at the view level self = self.with_context(lang=None) # We have to try-catch this, because at first init the view does not # exist but we are already creating some basic groups. view = self.env.ref('base.user_groups_view', raise_if_not_found=False) if view and view.exists() and view._name == 'ir.ui.view': group_no_one = view.env.ref('base.group_no_one') group_employee = view.env.ref('base.group_user') non_user_group = view.env.ref('pos_branch.group_no_branch_user') xml1, xml2, xml3 = [], [], [] xml_by_category = {} xml1.append(E.separator(string='User Type', colspan="2", groups='base.group_no_one')) user_type_field_name = '' user_type_readonly = str({}) sorted_tuples = sorted(self.get_groups_by_application(), key=lambda t: t[0].xml_id != 'base.module_category_user_type') for app, kind, gs, category_name in sorted_tuples: # we process the user type first attrs = {} # hide groups in categories 'Hidden' and 'Extra' (except for group_no_one) if app.xml_id in self._get_hidden_extra_categories(): attrs['groups'] = 'base.group_no_one' # User type (employee, portal or public) is a separated group. This is the only 'selection' # group of res.groups without implied groups (with each other). if app.xml_id == 'base.module_category_user_type': # application name with a selection field field_name = name_selection_groups(gs.ids) user_type_field_name = field_name user_type_readonly = str({'readonly': [(user_type_field_name, '!=', group_employee.id)]}) attrs['widget'] = 'radio' attrs['groups'] = 'base.group_no_one' xml1.append(E.field(name=field_name, **attrs)) xml1.append(E.newline()) elif kind == 'selection': # application name with a selection field field_name = name_selection_groups(gs.ids) attrs['attrs'] = user_type_readonly if category_name not in xml_by_category: xml_by_category[category_name] = [] xml_by_category[category_name].append(E.newline()) xml_by_category[category_name].append(E.field(name=field_name, **attrs)) xml_by_category[category_name].append(E.newline()) else: # application separator with boolean fields app_name = app.name or 'Other' xml3.append(E.separator(string=app_name, colspan="4", **attrs)) attrs['attrs'] = user_type_readonly for g in gs: field_name = name_boolean_group(g.id) if g == group_no_one or g == non_user_group: # make the group_no_one invisible in the form view xml3.append(E.field(name=field_name, invisible="1", **attrs)) else: xml3.append(E.field(name=field_name, **attrs)) xml3.append({'class': "o_label_nowrap"}) if user_type_field_name: user_type_attrs = {'invisible': [(user_type_field_name, '!=', group_employee.id)]} else: user_type_attrs = {} for xml_cat in sorted(xml_by_category.keys(), key=lambda it: it[0]): xml_cat_name = xml_cat[1] master_category_name = (_(xml_cat_name)) xml2.append(E.group(*(xml_by_category[xml_cat]), col="2", string=master_category_name)) xml = E.field( E.group(*(xml1), col="2"), E.group(*(xml2), col="2", attrs=str(user_type_attrs)), E.group(*(xml3), col="4", attrs=str(user_type_attrs)), name="groups_id", position="replace") xml.addprevious(etree.Comment("GENERATED AUTOMATICALLY BY GROUPS")) xml_content = etree.tostring(xml, pretty_print=True, encoding="unicode") new_context = dict(view._context) new_context.pop('install_filename', None) # don't set arch_fs for this computed view new_context['lang'] = None view.with_context(new_context).write({'arch': xml_content})
def _format_post(self, post, task, show_images, render_xhtml, thread_id): """Format post to text and xhtml representations.""" # Text formatting if thread_id is None: url = task["url"] else: url = "%sres/%d.html" % (task["url"], thread_id) if str(thread_id) != post["id"]: post_url = "%s#%s" %(url, post["id"]) else: post_url = url if post["title"]: title = post["title"] + " " else: title = "" if post["author_email"]: email = " <%s>" % post["author_email"] else: email = "" if post["img_src"]: img = "\nFile: %s -(%s) <%s>" % ( post["img_name"], post["img_size"], post["img_src"]) else: img = "" if post["body"]: body = "\n\n" + post["body"] else: body = "" text = u"%s\n%s%s%s%s %s No.%s%s%s" % ( post_url, title, post["author_name"], post["trip_text"], email, post["date"], post["id"], img, body) # XHTML formatting if post["title"]: title = E.span( post["title"], " ", style="font-size: larger; font-weight: bold; color: #CC1105;") else: title = "" if post["author_name"]: if post["author_email"]: author_text = E.a( post["author_name"], href=post["author_email"]) else: author_text = post["author_name"] author = E.span( author_text, style="color: #117743; font-weight: bold;") else: author = "" if post["trip_text"]: if post["trip_email"]: trip_text = E.a(post["trip_text"], href=post["trip_email"]) else: trip_text = post["trip_text"] trip = E.span(trip_text, style="color: #228854;") else: trip = "" if post["img_src"]: img = [ E.br(), "File: ", E.a(post["img_name"], href=post["img_src"]), " - (", E.span(post["img_size"], style="font-style: italic;"), ")"] if show_images: img.extend(( E.br(), E.a(E.img( alt="img", src=post["img_thumb_src"]), href=post["img_src"]))) else: img = () xhtml = E.span( E.br(), title, author, trip, " ", post["date"], " ", E.a("No.", post["id"], href=post_url), *img) xhtml.append(post["body_xhtml"]) if render_xhtml: xhtml = self._to_s(xhtml) return (text, xhtml)
def rollback(self): """ rollback that recent changes """ cmd = E('load-configuration', dict(compare='rollback', rollback="0")) return self.rpc(etree.tostring(cmd))
from lxml.builder import E from lxml import etree as ET Act = "INSERT" page = (E.KPLUSFEED( E.HEADER({'Primary': 'ForwardDeals'}, E.TableName('ForwardDeals', type("S")), E.Action(Act, type("C")), E.DateFormat('DD/MM/YYYY hh:mm:ss', type("S")), E.TradeKast('Y', type("S")), E.ExecCustomProc('Y', type("S")), E.SetDefaultValues('Y', type("S"))), E.PRIMARY( E.ForwardDeals(E.DealStatus('V Valid', type("S")), E.TradeDate('12/12/2019', type("D"))), E.Cpty(E.CptyShortName("CITI"))))) print(ET.tostring(page, pretty_print=True).decode("utf-8"))
def to_parent(self, ctx, cls, inst, parent, name, **kwargs): parent.write(E.pre(pformat(inst)))
def poweroff(self, in_min=0): """ issue a reboot to the device """ cmd = E('request-power-off', E('in', str(in_min))) rsp = self.rpc(etree.tostring(cmd)) return True
def get_xml_element(self, **params): return E.checkOrderResponse(**params)
def _encode_getfields(self, get_cmd, dot): for field_xpath in self._data_dict['get_fields']: dot.append(E(field_xpath))
def xmlify_doc(d): return E.doc(E.int({'name': 'int_field'}, str(d['int_field'])), E.str({'name': 'string_field'}, d['string_field']))
def get_xml_element(self, **params): return E.paymentAvisoResponse(**params)
def generate_netconf_xml(namespace, container, leaf): netconf_filter = etree.tostring(E('filter', E(container, E(leaf), xmlns=namespace)), pretty_print=True).decode() return netconf_filter
def _update_user_groups_view(self): """ Modify the view with xmlid ``base.user_groups_view``, which inherits the user form view, and introduces the reified group fields. """ if self._context.get('install_mode'): # use installation/admin language for translatable names in the view user_context = self.env['res.users'].context_get() self = self.with_context(**user_context) # We have to try-catch this, because at first init the view does not # exist but we are already creating some basic groups. view = self.env.ref('base.user_groups_view', raise_if_not_found=False) if view and view.exists() and view._name == 'ir.ui.view': group_no_one = view.env.ref('base.group_no_one') xml1, xml2 = [], [] xml1.append( E.separator(string=_('Application Accesses'), colspan="2")) for app, kind, gs in self.get_groups_by_application(): # hide groups in categories 'Hidden' and 'Extra' (except for group_no_one) attrs = {} if app.xml_id in ('base.module_category_hidden', 'base.module_category_extra', 'base.module_category_usability'): attrs['groups'] = 'base.group_no_one' if kind == 'selection': # application name with a selection field field_name = name_selection_groups(gs.ids) xml1.append(E.field(name=field_name, **attrs)) xml1.append(E.newline()) else: # application separator with boolean fields app_name = app.name or _('Other') xml2.append( E.separator(string=app_name, colspan="4", **attrs)) for g in gs: field_name = name_boolean_group(g.id) if g == group_no_one: # make the group_no_one invisible in the form view xml2.append( E.field(name=field_name, invisible="1", **attrs)) else: xml2.append(E.field(name=field_name, **attrs)) xml2.append({'class': "o_label_nowrap"}) xml = E.field(E.group(*(xml1), col="2"), E.group(*(xml2), col="4"), name="groups_id", position="replace") xml.addprevious(etree.Comment("GENERATED AUTOMATICALLY BY GROUPS")) xml_content = etree.tostring(xml, pretty_print=True, encoding="unicode") if not view.check_access_rights('write', raise_exception=False): # erp manager has the rights to update groups/users but not # to modify ir.ui.view if self.env.user.has_group('base.group_erp_manager'): view = view.sudo() new_context = dict(view._context) new_context.pop('install_mode_data', None) # don't set arch_fs for this computed view new_context['lang'] = None view.with_context(new_context).write({'arch': xml_content})
def mock_response(): return etree.tostring( E.RecreditRequestResponse( E.Status( "0" ), E.RequesterID( "abcd" ), E.RequestID( "BP123" ), E.CertifiedIntermediary( E.AccountID( "123456" ), E.SerialNumber( "789" ), E.PostageBalance( "76.55" ), E.AscendingBalance( "123.45" ), E.AccountStatus( "A" ), E.DeviceID( "071V00123456" ) ) ) )
from lxml.builder import E from lxml import etree as ET A = E.a I = E.i B = E.b def CLASS(v): # helper function, 'class' is a reserved word return {'class': v} page = (E.html( E.head(E.title("This is a sample document")), E.body( E.h1("Hello!", CLASS("title")), E.p("肖亮", E.B("bold"), "text in it!"), E.p("This is another paragraph, with a ", A("link", href="http://www.python.org"), "."), E.p("Here are some reserved characters: <spam&egg>."), ET.XML("<p>And finally, here is an embedded XHTML fragment.</p>"), ))) page = ET.tounicode(page, pretty_print=True) print(page) with open('text.xml', 'w') as p: p.write(page)
def task(cls, task, **kwargs): return E(task, **{k: cls.convert_attr(v) for k, v in iteritems(kwargs)})
# Testing Config of ACL namespace = 'http://cisco.com/ns/yang/Cisco-IOS-XE-acl' xml_config = etree.tostring( E( 'config', E( 'extended', 'test_acl', E( 'access-list-seq-rule', E('sequence', '10'), # Seq E( 'ace-rule', E('action', 'permit'), # Action E('protocol', 'ip'), # Protocol match E( 'source-choice', E('any') # Src Match ), # Source Choice E( 'destination-choice', E('any') # Dest Match ) # Dest Choice ) # Rule ), # Seq Rule xmlns=namespace) #ACL Name ), pretty_print=True).decode() output = m.edit_config(xml_config) # Testing Loopback config