def outputType(self, uri, graph): self.typesCount += 1 typ = SubElement(self.dom, "owl:Class") typ.set("rdf:about", uri) ext = None for (p, o) in graph.predicate_objects(uri): if p == RDFS.label: l = SubElement(typ, "rdfs:label") l.set("xml:lang", "en") l.text = o elif p == RDFS.comment: c = SubElement(typ, "rdfs:comment") c.set("xml:lang", "en") c.text = Markdown.parse(o) elif p == RDFS.subClassOf: s = SubElement(typ, "rdfs:subClassOf") s.set("rdf:resource", o) elif p == URIRef( "http://schema.org/isPartOf"): #Defined in an extension ext = str(o) elif p == RDF.type and o == URIRef( "http://schema.org/DataType"): #A datatype s = SubElement(typ, "rdfs:subClassOf") s.set("rdf:resource", "http://schema.org/DataType") typ.append(self.addDefined(uri, ext))
def write_instances(self, layer_element, layer): """Write out the instances in a layer""" instances_element = SubElement(layer_element, 'instances') for inst in layer.getInstances(): position = inst.getLocationRef().getExactLayerCoordinates() attrib = { 'o': inst.getObject().getId(), 'x': str(position.x), 'y': str(position.y), 'z': str(position.z), 'r': str(inst.getRotation()), } namespace = inst.getObject().getNamespace() if namespace != self.namespace: attrib['ns'] = inst.getObject().getNamespace() self.namespace = namespace inst_id = inst.getId() if inst_id: attrib['id'] = inst_id if inst_id is not None and inst_id in loaders.data.objects: for key in loaders.data.objects[inst_id]: if key not in attrib and loaders.data.objects[inst_id][key]: print key attrib[key] = str(loaders.data.objects[inst_id][key]) print key, attrib[key] # the local_loader loader sets object_type as type, we have to # correct for that here but really we should fix that there if attrib.get('type'): attrib['object_type'] = attrib['type'] del attrib['type'] instances_element.append(Element('i', attrib))
def execute(self, mappings, source): """Writes the given language code/name mappings to Android XML resource files. source = string indicating source of the data, for example, 'cldr' mappings = list of dictionaries containing mappings""" # In order to be able to to localize a particular, limited set of words across multiple # languages, here we define a list of language codes to support for every resource file # generated. Where localized language names are missing, a place holder is printed. If # ['*'] is specified, then all available language code/name pairs are generated. COVERAGE_LIST = ['*'] # Get language names in English as a dict for inclusion in XML comments english_pairs = {} for entry in mappings: for k, v in entry.iteritems(): if k == 'en': english_pairs = v break for entry in mappings: for k, v in entry.iteritems(): dir = os.path.join(os.path.dirname(__file__), self.get_directory(source) + "../" + source + "-android/values-" + k) if not os.path.exists(dir): os.makedirs(dir) with open(dir + "/arrays.xml", "w") as f: top = Element('resources') if k in english_pairs.keys(): top_comment = ElementTree.Comment(' ' + english_pairs[k].decode('utf-8') + ' (' + k + ') ') else: top_comment = ElementTree.Comment(' ' + k + ' ') top.append(top_comment) child = SubElement(top, 'string-array') child.attrib['name'] = 'languages_all' if '*' not in COVERAGE_LIST: # Iterate through only those codes in COVERAGE_LIST for lang_code in COVERAGE_LIST: if lang_code in english_pairs.keys(): comment = ElementTree.Comment(' ' + lang_code + ' - ' + english_pairs[lang_code].decode('utf-8') + ' ') else: comment = ElementTree.Comment(' ' + lang_code + ' ') child.append(comment) entry = SubElement(child, 'item') if lang_code in v.keys(): entry.text = v[lang_code].decode('utf-8') else: entry.text = "UNDEFINED" else: # Iterate through all available language codes for lang_code, lang_name in sorted(v.iteritems()): if lang_code in english_pairs.keys(): comment = ElementTree.Comment(' ' + lang_code + ' - ' + english_pairs[lang_code].decode('utf-8') + ' ') else: comment = ElementTree.Comment(' ' + lang_code + ' ') child.append(comment) entry = SubElement(child, 'item') entry.text = lang_name.decode('utf-8') f.write(self.prettify(top))
def xml(self): """ Return IPFGraph as XML element """ graph = Element("IPFGraph") block_tree = SubElement(graph, "Blocks") for name in sorted(self.__blocks): row, column = self.get_block_cell(name) block_element = SubElement(block_tree, "Block", {"name":name, "grid_row":str(row), "grid_column":str(column)}) block_element.append(self.__blocks[name].xml()) connection_tree = SubElement(graph, "Connections") for connection in sorted(self.connections): oport = connection._oport() iport = connection._iport() oblock = oport._owner_block() iblock = iport._owner_block() oblock_name = self.get_block_name(oblock) iblock_name = self.get_block_name(iblock) oport_name = oblock.get_port_name(oport) iport_name = iblock.get_port_name(iport) conection_element = SubElement(connection_tree, "Connection") con_output = SubElement(conection_element, "ConnectionOutput", {"block" : oblock_name, "port" : oport_name}) con_input = SubElement(conection_element, "ConnectionInput", {"block" : iblock_name, "port" : iport_name}) return graph
def export(): # 打开Excel文件读取数据 wb = xlrd.open_workbook(r'../0014/student.xls') # 通过名称获取一个工作表 table = wb.sheet_by_name(u'student') data = dict() # 循环行列表数据 for i in range(table.nrows): # 获取整行和整列的值(数组) # print(table.row_values(i)) # 使用行列索引 # print(table.row(i)[2].value) # 获取每一行的数据 row = table.row(i) print(row) value_list = list() key = row[0].value print(key) for i1 in row[1:]: value = i1.value print(value) value_list.append(value) data[key] = value_list print(data) root = Element('root') comment = Comment('学生信息表"id" : [名字, 数学, 语文, 英文]') child = SubElement(root, 'students') child.append(comment) child.text = str(data) tree = ElementTree(root) tree.write('student.xml', encoding='utf8')
def generateXML(self, os): # Structure of document is: # # <DAV:propertyupdate> # <DAV:set> # <<names/values of each property as elements>> # </DAV:set> # <DAV:remove> # <<names of each property as elements>> # </DAV:remove> # </DAV:propertyupdate> # <DAV:propertyupdate> element propertyupdate = Element(davxml.propertyupdate) # <DAV:set> element if self.setprops: set = SubElement(propertyupdate, davxml.set) propel = SubElement(set, davxml.prop) for prop in self.setprops: propel.append(prop) # <DAV:remove> element if self.delprops: remove = SubElement(propertyupdate, davxml.remove) propel = SubElement(remove, davxml.prop) for prop in self.delprops: propel.append(prop) # Now we have the complete document, so write it out (no indentation) xmldoc = BetterElementTree(propertyupdate) xmldoc.writeUTF8(os)
def afterTest(self, stdout, test): duration = time.time() - self.test_start self.total += 1 testcase = SubElement( self.testsuite, 'testcase', { 'classname': ' '.join(self.suite_stack), 'name': test.name, 'time': '%.3f' % duration }) if test.status == 'pass': self.passing += 1 if test.status == 'skip': skipped = SubElement(testcase, 'skipped') self.skipping += 1 elif test.status == 'fail': error = SubElement(testcase, 'error') error.append( CDATA('\n'.join(traceback.format_exception(*test.exc_info)))) self.failing += 1 stdout.flush()
def generate_shaft_door(self, world_ele, x, y, z, yaw, name): model_ele = SubElement(world_ele, 'model') model_ele.set('name', name) door_pose = SubElement(model_ele, 'pose') # tranformation (door_x, door_y) = self.shaft_door_pose x_new = x + door_x * np.cos(yaw) - door_y * np.sin(yaw) y_new = y + door_x * np.sin(yaw) + door_y * np.cos(yaw) yaw_new = yaw + self.motion_axis_orientation door_pose.text = f'{x_new} {y_new} {z} 0 0 {yaw_new}' self.generate_door_link_and_joint(model_ele) floor_thickness = 0.05 ramp_depth = self.gap * 2 ramp_size = [self.width, ramp_depth, floor_thickness] ramp_pose = Element('pose') ramp_pose.text = f'0 0 {-floor_thickness / 2} 0 0 0' model_ele.append( box_link('ramp', ramp_size, ramp_pose, material=lift_material(), bitmask='0x02')) model_ele.append(joint('ramp_joint', 'fixed', 'world', 'ramp')) if self.plugin: self.generate_door_plugin(model_ele, name)
def frab(self): top = Element("schedule") conf = SubElement(top, "conference") SubElement(conf, "title").text = self.title SubElement(conf, "subtitle") SubElement(conf, "venue") SubElement(conf, "city") slot = self.timeslot_minutes() SubElement(conf, "timeslot_duration").text = ("00:%02d:00" % slot) index = 0 for day in self.days(): eod = day + datetime.timedelta(days=1) index += 1 do = SubElement(top, "day", index="%d" % index, date=day.strftime("%Y-%m-%d")) for tent in self.tents: to = tent.frab((day, eod)) if to: do.append(to) return top
def outputType(self, uri, graph): self.typesCount += 1 typ = SubElement(self.dom,"owl:Class") typ.set("rdf:about",uri) ext = None for (p,o) in graph.predicate_objects(uri): if p == RDFS.label: l = SubElement(typ,"rdfs:label") l.set("xml:lang","en") l.text = o elif p == RDFS.comment: c = SubElement(typ,"rdfs:comment") c.set("xml:lang","en") c.text = Markdown.parse(o) elif p == RDFS.subClassOf: s = SubElement(typ,"rdfs:subClassOf") s.set("rdf:resource",o) elif p == URIRef("http://schema.org/isPartOf"): #Defined in an extension ext = str(o) elif p == RDF.type and o == URIRef("http://schema.org/DataType"): #A datatype s = SubElement(typ,"rdfs:subClassOf") s.set("rdf:resource","http://schema.org/DataType") typ.append(self.addDefined(uri,ext))
def export(): # 打开Excel文件读取数据 wb = xlrd.open_workbook(r'../0015/city.xls') # 通过名称获取一个工作表 table = wb.sheet_by_name(u'city') data = dict() # 循环行列表数据 for i in range(table.nrows): # 获取每一行的数据 row = table.row(i) # print(row) key = row[0].value # print(key) for i1 in row[1:]: value = i1.value data[key] = value print(data) root = Element('root') comment = Comment('城市信息') child = SubElement(root, 'cities') child.append(comment) child.text = str(data) tree = ElementTree(root) tree.write('city.xml', encoding='utf8')
def generate_xml(self, root): physics = SubElement(root, "PhysicsObject") for field_name in self.data.__fields__: if 'num' in field_name or 'offset' in field_name: continue if field_name in BCS_PHYSICS_XML_IGNORE: continue xml_name = BCS_PHYSICS_XML_TRANSLATION.get(field_name, field_name).upper() if xml_name.startswith("U_"): value = hex(self[field_name]) elif field_name.startswith("model") and self[field_name] < 10000: value = "10000" else: value = str(self[field_name]) SubElement(physics, xml_name, value=value) # Add file names physics.append(Comment("MODEL, EMM, EMB, EAN, BONE, SCD")) model_names = {} for name in BCS_PHYSICS_XML_NAMES: model_names[name] = get_costume_creator_name(self[name]) SubElement( physics, "STR_28", value= f'{model_names["emd_name"] or "NULL"}, {model_names["emm_name"] or "NULL"}, ' f'{model_names["emb_name"] or "NULL"}, {model_names["ean_name"] or "NULL"}, ' f'{self.bone_name or "NULL"}, {model_names["scd_name"] or "NULL"}')
def addLap(self, act): st = Revolution.isoTimestamp(self.startsec) lap = SubElement(act, 'Lap', {'StartTime': st}) last = len(self.points) - 1 tts = SubElement(lap, 'TotalTimeSeconds') tts.text = str(self.points[last].secs) dist = SubElement(lap, 'DistanceMeters') dist.text = str(self.points[last].dist * 1000) ms = SubElement(lap, 'MaximumSpeed') ms.text = str(Revolution.metersPerSec(self.maxSpeed)) calories = SubElement(lap, 'Calories') calories.text = str(self.points[last].calories) avgheart = SubElement(lap, 'AverageHeartRateBpm') avgheartvalue = SubElement(avgheart, 'Value') avgheartvalue.text = str(self.ttlHeart / (last+1)) maxheart = SubElement(lap, 'MaximumHeartRateBpm') maxheartvalue = SubElement(maxheart, 'Value') maxheartvalue.text = str(self.maxHeart) intensity = SubElement(lap, 'Intensity') intensity.text = 'Active' cadence = SubElement(lap, 'Cadence') cadence.text = str(self.ttlCadence / (last+1)) trigger = SubElement(lap, 'TriggerMethod') trigger.text = 'Manual' lap.append(self.trackElement()) ext = SubElement(lap, 'Extensions') self.LapExtension(ext, 'MaxBikeCadence', self.maxCadence) avgspeed = Revolution.metersPerSec(self.ttlSpeed / (last+1)) self.LapExtension(ext, 'AvgSpeed', avgspeed) avgwatts = self.ttlWatts / (last+1) self.LapExtension(ext, 'AvgWatts', avgwatts) self.LapExtension(ext, 'MaxWatts', self.maxWatts)
def aggregate_test_results(results: ET.SubElement, xml_reports: list): timestamp = None for xml in xml_reports: logger.info(f" Processing: {xml}") try: xml_root = ET.parse(xml).getroot() except ET.ParseError: logger.error(f' {xml} is corrupted and skipped') continue xml_timestamp = xml_root.get("timestamp") if (timestamp is None) or (xml_timestamp < timestamp): timestamp = xml_timestamp for device in xml_root.find("results"): device_results = results.find(device.tag) if device_results is None: results.append(device) else: device_results_report = xml_root.find("results").find(device.tag) for op in device_results_report: if device_results.find(op.tag) is not None: entry = device_results.find(op.tag) for attr_name in device_results.find(op.tag).attrib: if attr_name == "passrate": continue xml_value = int(op.attrib.get(attr_name)) aggregated_value = int(entry.attrib.get(attr_name)) device_results.find(entry.tag).set(attr_name, str(xml_value + aggregated_value)) else: device_results.append(op) return timestamp
class XmlBuilder: def __init__(self, langStr): self.root = Element('root') self.head = SubElement(self.root, 'head') self.head.append(Comment(str(langStr) + '-wiktikonary')) self.body = SubElement(self.root, 'body') self.outStr = None def prettifyXml(self, elem): # Return a pretty-printed XML string for the Element. rough_string = ET.tostring(elem, encoding='utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ") def returnOutstr(self): return self.prettifyXml(self.root) def returnRoot(self): return self.root def clearBody(self): self.body.clear() return
def create_group(self, id, children_ids, started): self._init_communicator() group_el = SubEl(self._resources_el, CIB.GROUP_TAG, {"id": id}) CIB._create_meta_attrs_el(group_el, attrs={ "target-role": CIB.STARTED_ROLE, "ordered": "false", "collocated": "false" }) for child_id in children_ids: resource_el = self._get_primitive_resource_el(child_id) current_group_el = self._get_group_el_by_primitive(child_id) if (current_group_el is None): self._resources_el.remove(resource_el) else: if (CIB._is_last_child(current_group_el, resource_el)): self.remove_loc_constraints_by_resource( current_group_el.get("id")) self._resources_el.remove(current_group_el) else: current_group_el.remove(resource_el) group_el.append(resource_el) self._communicator.modify(self._resources_el)
def is_entailed(self, axiom: OWLAxiom) -> bool: request_element = self._init_request() is_entailed_element = SubElement(request_element, 'IsEntailed') is_entailed_element.set('kb', self.kb_uri) is_entailed_element.append(translate_axiom(axiom)) response = requests.post(self.server_url, tostring(request_element)) # Example response: # <?xml version="1.0" encoding="utf-8"?> # <!DOCTYPE ResponseMessage> # <ResponseMessage # xmlns="http://www.owllink.org/owllink#" # xml:base="http://www.w3.org/2002/07/owl#" # xmlns:owl="http://www.w3.org/2002/07/owl#" # xmlns:xsd="http://www.w3.org/2001/XMLSchema#"> # # <BooleanResponse result="false"/> # </ResponseMessage> etree = fromstring(response.content) response_elem = \ etree.find('.//{http://www.owllink.org/owllink#}BooleanResponse') is_entailed = response_elem.attrib['result'].lower() == 'true' return is_entailed
def convert(geostyler): global _warnings _warnings = [] attribs = { "version": "1.0.0", "xsi:schemaLocation": "http://www.opengis.net/sld StyledLayerDescriptor.xsd", "xmlns": "http://www.opengis.net/sld", "xmlns:ogc": "http://www.opengis.net/ogc", "xmlns:xlink": "http://www.w3.org/1999/xlink", "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance" } root = Element("StyledLayerDescriptor", attrib=attribs) namedLayer = SubElement(root, "NamedLayer") layerName = SubElement(namedLayer, "Name") layerName.text = geostyler["name"] userStyle = SubElement(namedLayer, "UserStyle") userStyleTitle = SubElement(userStyle, "Title") userStyleTitle.text = geostyler["name"] featureTypeStyle = SubElement(userStyle, "FeatureTypeStyle") if "transformation" in geostyler: featureTypeStyle.append(processTransformation(geostyler["transformation"])) for rule in geostyler.get("rules", []): featureTypeStyle.append(processRule(rule)) sldstring = ElementTree.tostring(root, encoding='utf8', method='xml').decode() dom = minidom.parseString(sldstring) return dom.toprettyxml(indent=" "), _warnings
def addLap(self, act): st = Revolution.isoTimestamp(self.startsec) lap = SubElement(act, 'Lap', {'StartTime': st}) last = len(self.points) - 1 tts = SubElement(lap, 'TotalTimeSeconds') tts.text = str(self.points[last].secs) dist = SubElement(lap, 'DistanceMeters') dist.text = str(self.points[last].dist * 1000) ms = SubElement(lap, 'MaximumSpeed') ms.text = str(Revolution.metersPerSec(self.maxSpeed)) calories = SubElement(lap, 'Calories') calories.text = str(self.points[last].calories) avgheart = SubElement(lap, 'AverageHeartRateBpm') avgheartvalue = SubElement(avgheart, 'Value') avgheartvalue.text = str(self.ttlHeart / (last + 1)) maxheart = SubElement(lap, 'MaximumHeartRateBpm') maxheartvalue = SubElement(maxheart, 'Value') maxheartvalue.text = str(self.maxHeart) intensity = SubElement(lap, 'Intensity') intensity.text = 'Active' cadence = SubElement(lap, 'Cadence') cadence.text = str(self.ttlCadence / (last + 1)) trigger = SubElement(lap, 'TriggerMethod') trigger.text = 'Manual' lap.append(self.trackElement()) ext = SubElement(lap, 'Extensions') self.LapExtension(ext, 'MaxBikeCadence', self.maxCadence) avgspeed = Revolution.metersPerSec(self.ttlSpeed / (last + 1)) self.LapExtension(ext, 'AvgSpeed', avgspeed) avgwatts = self.ttlWatts / (last + 1) self.LapExtension(ext, 'AvgWatts', avgwatts) self.LapExtension(ext, 'MaxWatts', self.maxWatts)
def export_node(self, parent, node): # import pdb; pdb.set_trace() files = [] nodetag = SubElement(parent, "node", dict(id=str(node.pk), tree_path=node.tree_path)) for content in node.contentbase.all(): ## transform the baseclass into the actual instance content = content.content() spoke = content.spoke() type = spoke.model.get_name() xmlcontent = SubElement(nodetag, "content", dict(slug=node.slug(content.language), type=type)) contentxml, files = spoke.serializer().serialize(spoke) xmlcontent.append(contentxml) children = SubElement(nodetag, "children") for child in node.children(): files += self.export_node(children, child) return files
def create_proppatch(setprops, delprops, namespaces=None): """Construct and return XML string for PROPPATCH. setprops -- Mapping with properties to set. delprops -- Iterable with element names to remove. namespaces -- Mapping (prefix->namespace) with additional namespaces, if necessary. """ # RFC 2518, 12.13 propertyupdate XML element # <!ELEMENT propertyupdate (remove | set)+ > propertyupdate = Element("propertyupdate", _NS) if namespaces: _addnamespaces(propertyupdate, namespaces) # RFC 2518, 12.13.2 set XML element # <!ELEMENT set (prop) > if setprops: set_ = SubElement(propertyupdate, "set") prop = SubElement(set_, "prop") items_iterator = setprops.iteritems() if PYTHON2 else setprops.items() for (propname, propvalue) in sorted(items_iterator): if isinstance(propvalue, STRING_TYPE): _prop = SubElement(prop, propname) _prop.text = propvalue else: prop.append(propvalue) # RFC 2518, 12.13.1 set XML element # <!ELEMENT remove (prop) > if delprops: remove = SubElement(propertyupdate, "remove") prop = SubElement(remove, "prop") for propname in sorted(delprops): _prop = SubElement(prop, propname) return tostring(propertyupdate, "utf-8")
def generateXML(self, os): # Structure of document is: # # <DAV:propertyupdate> # <DAV:set> # <<names/values of each property as elements>> # </DAV:set> # <DAV:remove> # <<names of each property as elements>> # </DAV:remove> # </DAV:propertyupdate> # <DAV:propertyupdate> element propertyupdate = Element(davxml.propertyupdate) # <DAV:set> element if self.setprops: set = SubElement(propertyupdate, davxml.set) propel = SubElement(set, davxml.prop) for prop in self.setprops: propel.append(prop) # <DAV:remove> element if self.delprops: remove = SubElement(propertyupdate, davxml.remove) propel = SubElement(remove, davxml.prop) for prop in self.delprops: propel.append(prop) # Now we have the complete document, so write it out (no indentation) xmldoc = BetterElementTree(propertyupdate) xmldoc.writeUTF8(os)
def adjust_visual_scenes(self): logging.info('Adjusting Visual Scenes.') scenes = self.root.find('library_visual_scenes') if scenes is None: logging.error('No scenes.') return vis_scene = scenes[0] root_nodes = list(vis_scene) logging.info('Creating CryExport Node.') cryexportnode = SubElement(vis_scene, 'node') cryexportnode.attrib['id'] = 'CryExportNode_{0}'.format(self.config['scenename']) extra = SubElement(cryexportnode, 'extra') tech = SubElement(extra, 'technique', profile='CryEngine') props = SubElement(tech, 'properties') ft = 'fileType={0}'.format(self.config['filetype']) flags = [ft] if self.config['donotmerge']: flags.append('DoNotMerge') if self.config['customnormals']: flags.append('CustomNormals') if self.config['f32']: flags.append('UseF32VertexFormat') props.text = '\n\t\t'.join(flags) logging.info('Applied flags "{0}" to CryExport Node.'.format(' '.join(flags))) # Remove nodes. for node in root_nodes: vis_scene.remove(node) cryexportnode.append(node) logging.info('Reparented nodes.') self.recursive_adjust_nodes(cryexportnode) logging.info('Finished adjusting Visual Scenes.')
def append_datastrip_structure(datastrip: Element): """ Create the structure for DATASTRIP folder as defined in 'S2_PDI_Level-2A_Datastrip_Structure.xsd' and appends it to the datastrip element of the xml tree :param datastrip: Element for the DATASTRIP folder :return: """ datastrip_folder = SubElement(datastrip, 'DATASTRIP_NAME', attrib={'type': 'folder'}) datastrip_folder.append( Comment( 'Naming convention from https://sentinel.esa.int/documents/247904/685211/Sentinel-2-Products-Specification-Document at p74, p438' )) ds_xml = SubElement(datastrip_folder, 'DataStrip_Metadata_File', attrib={'type': 'file'}) qi_data = SubElement(datastrip_folder, 'QI_DATA', attrib={'type': 'folder'}) oqlc = SubElement(qi_data, 'OLQC', attrib={'type': 'file'}) oqlc.append(Comment('OLQC reports XML formatted'))
def main(argv): global lang lang = argv[1] if len(argv) > 1 else 'none' if lang == 'en': outsvg = codecs.open(getScriptLoc() + '/../../public_html/en/img/droughtMovingAverage.svg','w+', 'utf-8') elif lang == 'es': outsvg = codecs.open(getScriptLoc() + '/../../public_html/es/img/droughtMovingAverage.svg','w+', 'utf-8') else: print 'You must specify language (en or es)' return svg = Element('svg') svg.set('xmlns', 'http://www.w3.org/2000/svg') svg.set('xmlns:xlink', 'http://www.w3.org/1999/xlink') svg.set('viewBox', '0 0 600 320') svg.set('preserveAspectRatio', 'xMinYMin meet') global css css = SubElement(svg, 'style') css.set('type', 'text/css') css.text = '' css.text += 'text {font-family: Sans-Serif; pointer-events: none ;}' css.text += '.linebox' + ':hover' + ' { opacity : .25 }' script = SubElement(SubElement(svg,'body'), 'script') scriptdat = '' scriptdat += 'window.onload = function() {drawLines();};' scriptdat += 'function drawLines() {line1 = document.getElementById("pline1");points1 = line1.getAttribute("points");line1.setAttribute("points", "");pointl1 = points1.split(" ");tpoints1 = [];allpoints1 = "";i21 = 0;for(i11 = 0; i11 < pointl1.length; i11++){allpoints1 += pointl1[i11] + " ";tpoints1[i11] = allpoints1;window.setTimeout(function() {line1.setAttribute("points", tpoints1[i21]); i21++;}, i11*25);} line1.setAttribute("points", tpoints1[i21] + "0,0"); line2 = document.getElementById("pline2");points2 = line2.getAttribute("points");line2.setAttribute("points", "");pointl2 = points2.split(" ");tpoints2 = [];allpoints2 = "";i22 = 0;for(i12 = 0; i12 < pointl2.length; i12++){allpoints2 += pointl2[i12] + " ";tpoints2[i12] = allpoints2;window.setTimeout(function() {line2.setAttribute("points", tpoints2[i22]); i22++;}, i12*25);}}' script.append(Comment(' --><![CDATA[' + scriptdat.replace(']]>', ']]]]><![CDATA[>') + ']]><!-- ')) main = SubElement(svg, 'g') graph = SubElement(main, 'g') graph.set('transform', 'translate(65 10)') renderGraph(graph, getScriptLoc() + '/../../src_data/flow10yrProcessed.csv') renderLabels(main) outsvg.truncate() outsvg.write(fixIndentation(svg)) outsvg.close()
def adjust_visual_scenes(self): logging.info('Adjusting Visual Scenes.') scenes = self.root.find('library_visual_scenes') if scenes is None: logging.error('No scenes.') return vis_scene = scenes[0] root_nodes = list(vis_scene) logging.info('Creating CryExport Node.') cryexportnode = SubElement(vis_scene, 'node') cryexportnode.attrib['id'] = 'CryExportNode_{0}'.format( self.config['scenename']) extra = SubElement(cryexportnode, 'extra') tech = SubElement(extra, 'technique', profile='CryEngine') props = SubElement(tech, 'properties') ft = 'fileType={0}'.format(self.config['filetype']) flags = [ft] if self.config['donotmerge']: flags.append('DoNotMerge') if self.config['customnormals']: flags.append('CustomNormals') if self.config['f32']: flags.append('UseF32VertexFormat') props.text = '\n\t\t'.join(flags) logging.info('Applied flags "{0}" to CryExport Node.'.format( ' '.join(flags))) # Remove nodes. for node in root_nodes: vis_scene.remove(node) cryexportnode.append(node) logging.info('Reparented nodes.') self.recursive_adjust_nodes(cryexportnode) logging.info('Finished adjusting Visual Scenes.')
def genResultXml(resultList, device, Start, End): try: print "Generate test.result.xml ---------------->Start" tree = ElementTree() root = Element("test_definition") tree._setroot(root) env = Element("environment", {"build_id":"","device_id":"","device_name":"","host":"",\ "lite_version":"","manufacturer":"","resolution":"","screen_size":""}) root.append(env) #summary element summary = Element("summary", {"test_plan_name":""}) root.append(summary) tStart = SE(summary, "start_at") tEnd = SE(summary, "end_at") tStart.text = Start tEnd.text = End #suite element suite = SE(root, "suite", {"category":"Runtime_Core","launcher":"xwalk",\ "name":"wrt-manifest-android-tests"}) setPositive = SE(suite, "set", {"name":"positive","set_debug_msg":""}) setNegitive = SE(suite, "set", {"name":"negative","set_debug_msg":""}) #testcase element for case in resultList: setElement = setPositive if case["set"] == "negative": setElement = setNegitive pur = "Check if packaged web application can be installed/launched/uninstalled successfully" testcase = SE(setElement, "testcase", {"component":"Runtime Core",\ "execution_type":"auto","id":case["id"],"purpose":pur,"result":case["result"]}) desc = SE(testcase, "description") entry = Element("test_script_entry") entry.text = case["entry"].decode("utf-8") desc.append(entry) resultInfo = SE(testcase, "result_info") actualResult = SE(resultInfo, "actual_result") actualResult.text = case["result"] caseStart = SE(resultInfo, "start") caseStart.text = case["start"] caseEnd = SE(resultInfo, "end") caseEnd.text = case["end"] stdOut = SE(resultInfo, "stdout") if case["result"] == "FAIL": stdOut.text = "[message]\n" + case["message"].decode("utf-8") else: stdOut.text = "[message]" SE(resultInfo, "stderr") tree.write(ConstPath + "/device_" + device + "/report/wrt-manifest-android-tests.xml") updateXmlTitle(ConstPath + "/device_" + device + "/report/wrt-manifest-android-tests.xml",'<?xml version="1.0" encoding="UTF-8"?>\n<?xml-stylesheet type="text/xsl" href="./style/testresult.xsl"?>\n<?xml-stylesheet type="text/xsl" href="testresult.xsl"?>\n') print "Generate test.result.xml ---------------->O.K" except Exception,e: print Exception,":",e print "Generate test.result.xml ---------------->Error" sys.exit(1)
def EmitXML(self): dvd_elem = Element('dvd', attrib=dict(folder=str(self.folder), series=str(self.series), season=str(self.season))) titles_elem = SubElement(dvd_elem, 'titles') for title in self.titles: titles_elem.append(title.EmitXML()) return dvd_elem
def to_xml(self) -> Element: xml_map = Element('sfm_map') xml_head = SubElement(xml_map, 'head') for name, value in [ ('name', self.name), ('version', self.version), ('tileset', self.block_0_graphics.type_id), ('tileset2', self.block_1_graphics.type_id), ('bg', self.background_graphics.type_id), ('spikes', self.spike_graphics.type_id), ('width', self.get_pixel_width()), ('height', self.get_pixel_height()), ('colors', None), # handled later ('scroll_mode', int(self.screen_lock)), ('music', self.music_id), ('num_objects', len(self.objects)), ]: xml_head_subelement = SubElement(xml_head, name) xml_head_subelement.text = str(value) colors_string = '' def colors_string_append_integer(x: int): nonlocal colors_string colors_string += struct.pack('i', x).hex().upper() def colors_string_append_float(x: float): nonlocal colors_string colors_string += struct.pack('d', x).hex().upper() colors_string_append_integer(0x25a) # probably 2d array identifier colors_string_append_integer(6) # array height colors_string_append_integer(4) # array width for get_inverted_flag in (False, True): for hsv_index in range(3): for graphics_data in ( self.block_0_graphics, self.background_graphics, self.spike_graphics, self.block_1_graphics, ): colors_string_append_integer(0) if get_inverted_flag: colors_string_append_float( 1.0 if graphics_data. color_hsv_inverted[hsv_index] else 0.0) else: colors_string_append_float( graphics_data.color.as_hsv_tuple()[hsv_index]) xml_head.find('colors').text = colors_string xml_objects = SubElement(xml_map, 'objects') for level_object in self.objects: xml_objects.append(level_object.to_xml()) return xml_map
def menuItemCoursesXML(): courses = db.getAllCourses() xml = Element('restaurants') child = SubElement(xml, 'courses') for course in courses: child.append(course.serialize_xml) return xmlResponse(xml)
def _saveFactories(self, factories): element = Element("factories") sources = SubElement(element, "sources") for factory in factories: if isinstance(factory, SourceFactory): source_element = self._saveSource(factory) sources.append(source_element) return element
def to_xml(self, parent): #Remove any keys with value None xml_attribs = {key: str(value) for key, value in self.attribs.iteritems() if value != None} #XML elment representing this object elem = SubElement(parent, self.type, xml_attribs) #VPR's xml parser is very picky, it does not allow mixing the ordering of xml tags # This works: # <!--- This ordering is ok, all of the direct tags finish # before the complete tags start --> # <direct name='direct1" ... /> # <direct name='direct2" ... /> # <complete name='complete1" ... /> # # This does NOT works: # <!--- The complete tags start before the direct tags have finished # this will cause a segfault in the architecture parser --> # <direct name='direct1" ... /> # <complete name='complete1" ... /> # <direct name='direct2" ... /> # # Therefore sort all the child elements by type and add them to the tree in order children_by_type = {} for child in self.children: if child.type not in children_by_type: #New type add a list for it children_by_type[child.type] = [] #Add the child to its type list children_by_type[child.type].append(child) #Attach children finishing each type before starting the next (builds xml tree) # For readability purposes preferentially process the types in the following order preferred_order = ['input', 'output', 'clock', 'T_setup', 'T_clock_to_Q', 'pb_type', 'interconnect', 'complete', 'mux', 'direct'] for type in preferred_order: if type in children_by_type: for child in children_by_type[type]: child.to_xml(elem) #This type has been processed, so delete it # This allows us to still process any items # not in the preferred_order list, without # repeating any types that ARE in the # preferred_order list del children_by_type[type] #Catch any types not in the preferred_order list for type, child_type_list in children_by_type.iteritems(): for child in child_type_list: child.to_xml(elem) #Add a comment attribute if self.comment != None: elem.append(Comment(self.comment)) return elem
def menuItemCoursesXML(): courses = db.getAllCourses() xml = Element('restaurants') child = SubElement(xml, 'courses') for course in courses: child.append(course.serialize_xml) return xmlResponse(xml)
def build_from_words(self, words, encoding="utf-8"): if isinstance(words, str): self.build(words) elif isinstance(words, list): flag = "seg" assert len(words) > 0 word = words[0] if isinstance(word, str): flag = "seg" elif (isinstance(word, list) and len(word) == 2 and isinstance(word[0], str) and isinstance(word[1], str)): flag = "pos" elif (isinstance(word, tuple) and len(word) == 2 and isinstance(word[0], str) and isinstance(word[1], str)): flag = "pos" else: flag = "unknown" self.xml4nlp = Element('xml4nlp') self.note = SubElement(self.xml4nlp, 'note') self.doc = SubElement(self.xml4nlp, 'doc') para = SubElement(self.doc, 'para') sent = SubElement(para, 'sent') para.set("id", "0") sent.set("id", "0") self._clean_note() if flag == "seg": for id, word in enumerate(words): sent.append( Element('word', { 'id': ('%d' % id), 'cont': word.decode(encoding), })) sent.set('cont', ("".join(words)).decode(encoding)) self.set_word_on_note() elif flag == "pos": for id, wordpos in enumerate(words): word, pos = wordpos sent.append( Element( 'word', { 'id': ('%d' % id), 'cont': word.decode(encoding), 'pos': pos, })) sent.set('cont', ("".join([word[0] for word in words])).decode(encoding)) self.set_pos_on_note() self.dom = self.xml4nlp
def _saveFactories(self, factories): element = Element("factories") sources = SubElement(element, "sources") for factory in factories: if isinstance(factory, SourceFactory): source_element = self._saveSource(factory) sources.append(source_element) return element
def phyloxml(self, **kwargs): """ Returns the root element of UniProt SIFt cluster tree in PhyloXML format. """ root = Element('phyloxml') phylogeny = SubElement(root, 'phylogeny') phylogeny.set('rooted', 'true') # rendering options render = SubElement(phylogeny, 'render') parameters = SubElement(render, 'parameters') circular = SubElement(parameters, 'circular') buffer_radius = SubElement(circular, 'bufferRadius') buffer_radius.text = kwargs.get(str('buffer_radius'),'0.4') # charting options for this tree charts = SubElement(render, 'charts') # create internal arcs in the tree to display the compound class: drug, # endogenous, etc. interaction = SubElement(charts, 'interaction') interaction.attrib = {'type': 'binary', 'thickness': '10', 'isInternal': 'true', 'bufferInner': '0'} # binding site property binary arcs bindingsite = SubElement(charts, 'bindingsite') bindingsite.attrib = {'type': 'binary', 'thickness': '7.5'} # ligand efficiency bar charts activity = SubElement(charts, 'activity') activity.attrib = {'type': 'bar', 'fill':'#000', 'width':'0.4'} # styling of elements: charts, arcs, backgrounds styles = SubElement(render, 'styles') drugtarget = SubElement(styles, 'drugtarget', {'fill': '#75BBE4', 'stroke':'#DDD'}) enzymecmpd = SubElement(styles, 'enzymecmpd', {'fill': '#DEF1CC', 'stroke':'#DDD'}) bar_chart = SubElement(styles, 'barChart', {'fill':'#999', 'stroke-width':'0'}) # chemical component types appdrug = SubElement(styles, 'appdrug', {'fill': '#3296CB', 'stroke':'#3296CB'}) drug = SubElement(styles, 'drug', {'fill': '#75BBE4', 'stroke':'#75BBE4'}) lead = SubElement(styles, 'lead', {'fill': '#A9D6F0', 'stroke':'#A9D6F0'}) druglike = SubElement(styles, 'druglike', {'fill': '#CDE9F4', 'stroke':'#CDE9F4'}) solvent = SubElement(styles, 'solvent', {'fill': '#FFFACD', 'stroke':'#FFFACD'}) heteropeptide = SubElement(styles, 'heteropeptide', {'fill': '#FBD5A5', 'stroke':'#FBD5A5'}) nucleotide = SubElement(styles, 'nucleotide', {'fill': '#DEF1CC', 'stroke':'#DEF1CC'}) # binding site properties mutated = SubElement(styles, 'mutated', {'fill': '#E75559', 'stroke':'#DDD'}) modified = SubElement(styles, 'modified', {'fill': '#F98892', 'stroke':'#DDD'}) nonstd = SubElement(styles, 'nonstd', {'fill': '#FDCDD7', 'stroke':'#DDD'}) clade = SubElement(phylogeny, 'clade') clade.append(self._clade()) return root
def data2xml(self, datas): self.savedata = datas fps = Element('fps') fps.attrib = {'verdion': '1.2'} self.now._setroot(fps) item = SubElement(fps, 'item') SubElement(item, 'title').text = datas['title'] time_limit = SubElement(item, 'time_limit') time_limit.attrib = {'unit': 's'} time_limit.text = '1' memory_limit = SubElement(item, 'memory_limit') memory_limit.attrib = {'unit': 'mb'} memory_limit.text = '64' all = datas['src_num'] print 'all of image :', all i = 0 print datas while i != all: img = SubElement(item, 'img') src = SubElement(img, 'src') src.text = datas['src'][i] base64 = SubElement(img, 'base64') base64.text = datas['base64'][i] i = i + 1 SubElement(item, 'description').text = datas['description'] SubElement(item, 'input').text = datas['input'] SubElement(item, 'output').text = datas['output'] sample_input = SubElement(item, 'sample_input') data = CDATA(datas['sample_input']) sample_input.append(data) sample_output = SubElement(item, 'sample_output') data = CDATA(datas['sample_output']) sample_output.append(data) test_input = SubElement(item, 'test_input') data = CDATA(datas['sample_input']) test_input.append(data) test_output = SubElement(item, 'test_output') data = CDATA(datas['sample_output']) test_output.append(data) # SubElement(item,'test_input').append(CDATA(datas['sample_input'])) # SubElement(item,'test_output').append(CDATA(datas['sample_output'])) solution = SubElement(item, 'solution') data = CDATA(datas['solution']) solution.append(data) solution.attrib = {'language': 'C++'} SubElement(item, 'hint').text = datas['hint'] SubElement( item, 'source').text = datas['source'] + '(POJ' + ' ' + datas['ID'] + ')' # dump(indent(fps)) self.save(datas)
def buildSoapResponse(response, body): # construct the soap response, and serialize it envelope = Element('{%s}Envelope' % cocy.soaplib.ns_soap_env) # body soap_body = SubElement(envelope, '{%s}Body' % cocy.soaplib.ns_soap_env) soap_body.append(body) response.headers["Content-Type"] = "text/xml; charset=utf-8" return "<?xml version='1.0' encoding='utf-8'?>" + \ ElementTree.tostring(envelope, encoding="utf-8")
def get_xml(self, data): root = Element('root') student = SubElement(root, 'students') student.append(Comment('学生信息表 "id" : [名字, 数学, 语文, 英文]')) # student. print(data) student.text = data xml_final = ElementTree(root) # print(xml_final) return xml_final
def _perform_operation(self, func_name, oper): base = Element(soap_name('Envelope')) base.attrib[soap_name('encodingStyle')] = \ "http://schemas.xmlsoap.org/soap/encoding/" body = SubElement(base, soap_name('Body')) body.append(oper) xml_str = '<?xml version="1.0" encoding="UTF-8" ?>\n' + \ ET.tostring(base) return self._send_request(func_name, xml_str)
def get_xml(self, data): root = Element('root') student = SubElement(root, 'students') student.append(Comment('学生信息表 "id" : [名字, 数学, 语文, 英文]')) # student. print(data) student.text = data xml_final = ElementTree(root) # print(xml_final) return xml_final
def genResultXml(): try: print "Generate test.result.xml ---------------->Start" tree = ElementTree() root = Element("test_definition") tree._setroot(root) env = Element("environment", {"build_id":"","device_id":"","device_name":"","host":"",\ "lite_version":"","manufacturer":"","resolution":"","screen_size":""}) root.append(env) #summary element summary = Element("summary", {"test_plan_name":""}) root.append(summary) tStart = SE(summary, "start_at") tEnd = SE(summary, "end_at") tStart.text = Start tEnd.text = End #suite element suite = SE(root, "suite", {"category":"Runtime_Core","launcher":"xwalk",\ "name":"wrt-manifest-android-tests"}) setPositive = SE(suite, "set", {"name":"positive","set_debug_msg":""}) setNegitive = SE(suite, "set", {"name":"negitive","set_debug_msg":""}) #testcase element for case in ResultList: setElement = setPositive if case["set"] == "negative": setElement = setNegitive pur = "Check if packaged web application can be installed/launched/uninstalled successfully" testcase = SE(setElement, "testcase", {"component":"Runtime Core",\ "execution_type":"auto","id":case["id"],"purpose":pur,"result":case["result"]}) desc = SE(testcase, "description") entry = Element("test_script_entry") entry.text = case["entry"].decode("utf-8") desc.append(entry) resultInfo = SE(testcase, "result_info") actualResult = SE(resultInfo, "actual_result") actualResult.text = case["result"] caseStart = SE(resultInfo, "start") caseStart.text = case["start"] caseEnd = SE(resultInfo, "end") caseEnd.text = case["end"] SE(resultInfo, "stdout") SE(resultInfo, "stderr") tree.write(ConstPath + "/report/wrt-manifest-android-tests.xml") updateXmlTitle(ConstPath + "/report/wrt-manifest-android-tests.xml",'<?xml version="1.0" encoding="UTF-8"?>\n<?xml-stylesheet type="text/xsl" href="./style/testresult.xsl"?>\n<?xml-stylesheet type="text/xsl" href="testresult.xsl"?>\n') print "Generate test.result.xml ---------------->O.K" except Exception,e: print Exception,":",e print "Generate test.result.xml ---------------->Error" sys.exit(1)
def generate_users_per_ward(self, ward, beds_per_ward): """Create users assigned to wards or beds.""" # Create root element root = Element('openerp') # Create data inside root element data = SubElement(root, 'data', {'noupdate': '1'}) for role, schema in self.users_schema.iteritems(): # Initialise some variable to generate data for the current ward users_per_ward = schema.get('per_ward') if users_per_ward: groups_id = "[(4, ref('nh_clinical.{0}'))]".format( self.groups[role]) category_id = "[(4, ref('nh_clinical.{0}'))]".format( self.categories[role]) first_name_generator = self.names_generators.get(role) beds_per_user = beds_per_ward / users_per_ward # Initialise the generator for every users' role, # so it will supply sequential numbers coherently to all users. beds_number_generator = self.get_beds_number_generator( beds_per_ward) # Add a comment to divide XML in sections by role users_role_comment = Comment(' Ward {0}: {1} '.format( ward.upper(), role)) data.append(users_role_comment) # Create user assigned to a specific ward (or beds). for _ in xrange(users_per_ward): if role in self.assignable_to_ward: location_ids = "[[6, False, " \ "[ref('nhc_def_conf_location_w{}')]" \ "]]".format(ward) elif role in self.assignable_to_bed: # Retrieve sequential numbers # from the beds number generator, # only for a very limited number of times # (equal to number of beds per user). # # Use these sequential numbers # to format strings about locations. bed_list = ','.join( ["ref('nhc_def_conf_location_w{}_b{}')".format( ward, next(beds_number_generator)) for _ in xrange(beds_per_user)] ) location_ids = "[[6, False, [{0}]]]".format(bed_list) else: location_ids = "[[6, False, []]]" self.build_user_data(data, role, first_name_generator, groups_id, category_id, location_ids) return root
def __init__(self, # oauth parameters - if absent, integration will prevent # till users from performing any actions that would # require Xero callouts consumer_key=None, private_key=None, # Invoices will be created to the following contact ID: sales_contact_id=None, # Invoices will be created with a reference using the # following template: reference_template="Session {session.id}", # Use this tracking category on all relevant entries tracking_category_name=None, tracking_category_value=None, # Mark the invoice as Due in the following number of days: due_days=7, # Add tillweb link when an invoice is created tillweb_base_url=None, # Set the branding theme branding_theme_id=None, # Specify the Xero organisation's ShortCode shortcode=None, # Use this account for till discrepancies discrepancy_account=None, # Only start sending totals to Xero on or after this date start_date=None): XeroSessionHooks(self) XeroDeliveryHooks(self) if consumer_key and private_key: self.oauth = OAuth1( consumer_key, resource_owner_key=consumer_key, rsa_key=private_key, signature_method=SIGNATURE_RSA, signature_type=SIGNATURE_TYPE_AUTH_HEADER) else: self.oauth = None if sales_contact_id: self.contact = Element("Contact") self.contact.append(_textelem("ContactID", sales_contact_id)) else: self.contact = None if tracking_category_name and tracking_category_value: self.tracking = Element("Tracking") tc = SubElement(self.tracking, "TrackingCategory") tc.append(_textelem("Name", tracking_category_name)) tc.append(_textelem("Option", tracking_category_value)) else: self.tracking = None self.reference_template = reference_template self.due_days = datetime.timedelta(days=due_days) self.tillweb_base_url = tillweb_base_url self.branding_theme_id = branding_theme_id self.shortcode = shortcode self.discrepancy_account = discrepancy_account self.start_date = start_date
def toCycloneDX(self): components = self.makeCycloneDXRepresentationOfNode() bom = Element("bom") bom.set("version", "1") bom.set("xmlns", "http://cyclonedx.org/schema/bom/1.0") componentsholder = SubElement(bom, "components") componentsholder.append(components) return tostring(bom)
def __init__(self, operator, queries): super().__init__() self.query = Element("orgPdbCompositeQuery") for i, q in enumerate(queries): refinement = SubElement(self.query, "queryRefinement") ref_level = SubElement(refinement, "queryRefinementLevel") ref_level.text = str(i) if i != 0: conj_type = SubElement(refinement, "conjunctionType") conj_type.text = operator refinement.append(q.query)
def build_from_words(self, words, encoding="utf-8"): if isinstance(words, str): self.build(words) elif isinstance(words, list): flag = "seg" assert len(words) > 0 word = words[0] if isinstance(word, str): flag = "seg" elif (isinstance(word, list) and len(word) == 2 and isinstance(word[0], str) and isinstance(word[1], str)): flag = "pos" elif (isinstance(word, tuple) and len(word) == 2 and isinstance(word[0], str) and isinstance(word[1], str)): flag = "pos" else: flag = "unknown" self.xml4nlp = Element('xml4nlp') self.note = SubElement(self.xml4nlp, 'note') self.doc = SubElement(self.xml4nlp, 'doc') para = SubElement(self.doc, 'para') sent = SubElement(para, 'sent') para.set("id", "0") sent.set("id", "0") self._clean_note() if flag == "seg": for id, word in enumerate(words): sent.append(Element('word', { 'id': ('%d' % id), 'cont': word.decode(encoding),})) sent.set('cont', ("".join(words)).decode(encoding)) self.set_word_on_note() elif flag == "pos": for id, wordpos in enumerate(words): word, pos = wordpos sent.append(Element('word', { 'id': ('%d' % id), 'cont' : word.decode(encoding), 'pos' : pos,})) sent.set('cont', ("".join([word[0] for word in words])).decode(encoding)) self.set_pos_on_note() self.dom = self.xml4nlp
def data2xml(self,datas): self.savedata=datas fps=Element('fps') fps.attrib={'verdion':'1.2'} self.now._setroot(fps) item=SubElement(fps,'item') SubElement(item,'title').text=datas['title'] time_limit=SubElement(item,'time_limit') time_limit.attrib={'unit':'s'} time_limit.text='1' memory_limit=SubElement(item,'memory_limit') memory_limit.attrib={'unit':'mb'} memory_limit.text='64' all=datas['src_num'] print 'all of image :',all i=0 print datas while i!=all: img=SubElement(item,'img') src=SubElement(img,'src') src.text=datas['src'][i] base64=SubElement(img,'base64') base64.text=datas['base64'][i] i=i+1 SubElement(item,'description').text=datas['description'] SubElement(item,'input').text=datas['input'] SubElement(item,'output').text=datas['output'] sample_input=SubElement(item,'sample_input') data=CDATA(datas['sample_input']) sample_input.append(data) sample_output=SubElement(item,'sample_output') data=CDATA(datas['sample_output']) sample_output.append(data) test_input=SubElement(item,'test_input') data=CDATA(datas['sample_input']) test_input.append(data) test_output=SubElement(item,'test_output') data=CDATA(datas['sample_output']) test_output.append(data) # SubElement(item,'test_input').append(CDATA(datas['sample_input'])) # SubElement(item,'test_output').append(CDATA(datas['sample_output'])) solution=SubElement(item,'solution') data=CDATA(datas['solution']) solution.append(data) solution.attrib={'language':'C++'} SubElement(item,'hint').text=datas['hint'] SubElement(item,'source').text=datas['source']+'(POJ'+' '+datas['ID']+')' # dump(indent(fps)) self.save(datas)
def _saveTrack(self, track): element = Element("track") stream_element = self._saveStream(track.stream) element.append(stream_element) track_objects = SubElement(element, "track-objects") for track_object in track.track_objects: track_object_element = self._saveTrackObject(track_object) track_objects.append(track_object_element) return element
def call(self, action, request): # build SOAP envelope envelope = Element(NS_SOAP_ENV + "Envelope") body = SubElement(envelope, NS_SOAP_ENV + "Body") body.append(request) response = self.__client.do_request( tostring(envelope), extra_headers=[("SOAPAction", action)], parser = parseSOAPRPC, ) return response
def buildSoapResponse(response, body): # construct the soap response, and serialize it envelope = Element('{%s}Envelope' % cocy.soaplib.ns_soap_env) # body soap_body = SubElement(envelope, '{%s}Body' % cocy.soaplib.ns_soap_env) soap_body.append(body) writer = StringIO() response.headers["Content-Type"] = "text/xml; charset=utf-8" writer.write("<?xml version='1.0' encoding='utf-8'?>") ElementTree(envelope).write(writer, encoding="utf-8") return writer.getvalue()
def collision(name, pose, size, bitmask=None): collision_ele = Element('collision') collision_ele.set('name', name) if pose is not None: collision_ele.append(pose) collision_geometry_ele = SubElement(collision_ele, 'geometry') collision_geometry_ele.append(box(size)) if bitmask: collision_ele.append(collide_bitmask(bitmask)) return collision_ele
def writeTM(stateMech, filename): if filename[-4:] != '.txt': raise Exception('This needs to have a .txt extension to work!') return f = open(filename[:-4] + 'jflap.jff', 'w') root = Element('structure') mechType = SubElement(root, 'type') mechType.text = 'turing' automaton = SubElement(root, 'automaton') automaton.append(Comment('The list of states.')) counter = 0 nodeDict = {} for node in stateMech.nodeL: state = SubElement(automaton, 'block', id = str(counter), name = node.name) tag = SubElement(state, 'tag') tag.text = 'Machine' + str(counter) xCoor = SubElement(state, 'x') xCoor.text = str(math.floor(random() * 1000) * 1.0) yCoor = SubElement(state, 'y') yCoor.text = str(math.floor(random() * 1000) * 1.0) if node.initial: SubElement(state, 'initial') if node.accepting: SubElement(state, 'final') nodeDict[node.name] = str(counter) counter += 1 for edge in stateMech.edgeL: transition = SubElement(automaton, 'transition') fromNode = SubElement(transition, 'from') toNode = SubElement(transition, 'to') read = SubElement(transition, 'read') write = SubElement(transition, 'write') move = SubElement(transition, 'move') fromNode.text = nodeDict[edge.fromNode.name] toNode.text = nodeDict[edge.intoNode.name] readVal = edge.readVal writeVal = edge.writeVal move.text = edge.action if readVal != lambdaChar: read.text = readVal if writeVal != lambdaChar: write.text = writeVal prettyRoot = prettify(root) #print(addCorrectHeader(prettyRoot)) f.write(addCorrectHeader(prettyRoot)) f.close()
def genResultXml(): try: tree = ElementTree() root = Element("test_definition") tree._setroot(root) env = Element("environment", {"build_id":"","device_id":"","device_name":"","host":"",\ "lite_version":"","manufacturer":"","resolution":"","screen_size":""}) root.append(env) #summary element summary = Element("summary", {"test_plan_name":""}) root.append(summary) tStart = SE(summary, "start_at") tEnd = SE(summary, "end_at") tStart.text = Start tEnd.text = End #suite element suite = SE(root, "suite", {"category":"Crosswalk_Packer_Tool","launcher":"xwalk",\ "name":"wrt-packertool-android-tests"}) setPositive = SE(suite, "set", {"name":"positive","set_debug_msg":""}) setNegitive = SE(suite, "set", {"name":"negitive","set_debug_msg":""}) #testcase element for case in ResultList: setElement = setPositive if case["set"] == "negative": setElement = setNegitive pur = "Check if packer tool work properly" testcase = SE(setElement, "testcase", {"component":"Crosswalk Packer Tool",\ "execution_type":"auto","id":case["id"],"purpose":pur,"result":case["result"]},) desc = SE(testcase, "description") entry = Element("test_script_entry") entry.text = "pack command: " + case["entry"].decode("utf-8") desc.append(entry) resultInfo = SE(testcase, "result_info") actualResult = SE(resultInfo, "actual_result") actualResult.text = case["result"] caseStart = SE(resultInfo, "start") caseStart.text = case["start"] caseEnd = SE(resultInfo, "end") caseEnd.text = case["end"] SE(resultInfo, "stdout") SE(resultInfo, "stderr") tree.write(ConstPath + "/report/wrt-packertool-android-tests.xml") updateXmlTitle(ConstPath + "/report/wrt-packertool-android-tests.xml",'<?xml version="1.0" encoding="UTF-8"?>\n<?xml-stylesheet type="text/xsl" href="./style/testresult.xsl"?>\n<?xml-stylesheet type="text/xsl" href="testresult.xsl"?>\n') print "Generate test.result.xml file ------------------------->O.K" except Exception,e: print Exception,"Generate test.result.xml error:",e
def patient_to_xml(patient): container_node = Element('Container') lab_orders_node = SubElement(container_node, 'LabOrders') lab_orders = SDALabOrder.query\ .join(SDALabOrder.sda_bundle)\ .filter(SDABundle.patient == patient)\ .all() for lab_order in lab_orders: lab_orders_node.append(lab_order_to_xml(lab_order)) return container_node
def _get_tracking(self, department): tracking = [] if self.tracking_category_name and self.tracking_category_value: tracking.append((self.tracking_category_name, self.tracking_category_value)) if department and self.department_tracking_category_name: v = self._tracking_for_department(department) if v: tracking.append((self.department_tracking_category_name, v)) if tracking: t = Element("Tracking") for name, option in tracking: tc = SubElement(t, "TrackingCategory") tc.append(_textelem("Name", name)) tc.append(_textelem("Option", option)) return t
def _format_content(self, article, news_item, nitf): """ Adds the content set to the xml :param dict article: :param Element newsItem: :param Element nitf: """ content_set = SubElement(news_item, 'contentSet') if article[ITEM_TYPE] == CONTENT_TYPE.PREFORMATTED: SubElement(content_set, 'inlineData', attrib={'contenttype': 'text/plain'}).text = self.append_body_footer(article) elif article[ITEM_TYPE] in [CONTENT_TYPE.TEXT, CONTENT_TYPE.COMPOSITE]: inline = SubElement(content_set, 'inlineXML', attrib={'contenttype': 'application/nitf+xml'}) inline.append(nitf)
def change_nics_settings(self, op_add = True, vniclist = None): """ Add/Delete nics for vm. """ xml = self._XMLDesc(VIR_DOMAIN_XML_SECURE) tree = ElementTree.fromstring(xml) devices_node = tree.find('devices') vniclist_temp = [] for device_item in devices_node.findall('hostdev'): src_addr = device_item.find('source/address') if src_addr is not None: src_bus = src_addr.get("bus") src_slot = src_addr.get("slot") src_function = src_addr.get("function") src_item = str(src_bus + ":" + src_slot + "." + src_function).replace("0x", "") if not op_add: if src_item in vniclist: vniclist_temp.append(src_item) devices_node.remove(device_item) else: vniclist_temp.append(src_item) devices_node.remove(device_item) if not op_add: util.del_vfs_fro_vm(vniclist_temp) else: vniclist_temp.extend(vniclist) hostdev_attr = {'mode' : 'subsystem', 'type' : 'pci', 'managed' : 'yes' } for vf in vniclist_temp: element = Element('hostdev', hostdev_attr) source = SubElement(element, 'source') address = Element('address') self.make_pci_attribute(address, vf) source.append(address) address_hostdev = SubElement(element, 'address') self.make_pci_bus_attribute(address_hostdev, vniclist_temp.index(vf)) #element.append(address_hostdev) devices_node.append(element) address_hostdev = None util.add_vfs_for_vm(vniclist) new_xml = ElementTree.tostring(tree) self._defineXML(new_xml) return self._XMLDesc(VIR_DOMAIN_XML_SECURE)
def _create_nav(self): """ Create a new style TOC file ('nav' file): ``nav.xhtml``. """ full_nav = True if len(self.document.nav_toc) != 0 else False final_nav_header = NAV % (NAV_CSS_NO_NUMBERING if full_nav else NAV_CSS_NUMBERING) # Setting the default namespace; this is important when the file is generated ET.register_namespace('', "http://www.w3.org/1999/xhtml") ET.register_namespace('epub', "http://www.idpf.org/2007/ops") nav = ElementTree(ET.fromstring(final_nav_header)) # Set the title title = nav.findall(".//{http://www.w3.org/1999/xhtml}title")[0] title.text = self.document.title + " - Table of Contents" # Set the date date = nav.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='date']")[0] date.set("content", self.document.date.strftime(DATE_FORMAT_STRING)) # # The landmark part of the nav file has to be changed; there is no explicit cover page # li_landmark = nav.findall(".//{http://www.w3.org/1999/xhtml}a[@href='cover.xhtml']")[0] # li_landmark.set("href", "Overview.xhtml") navMap = nav.findall(".//{http://www.w3.org/1999/xhtml}nav[@id='toc']")[0] h2 = SubElement(navMap, "{http://www.w3.org/1999/xhtml}h2") h2.text = "Table of Contents" ol = SubElement(navMap, "{http://www.w3.org/1999/xhtml}ol") li = SubElement(ol, "{http://www.w3.org/1999/xhtml}li") a = SubElement(li, "{http://www.w3.org/1999/xhtml}a") a.set("href", "cover.xhtml") a.text = "Cover" a.set("class", "toc") if full_nav: for toc_entry in self.document.nav_toc: ol.append(toc_entry) else: for toc_entry in self.document.toc: li = SubElement(ol, "{http://www.w3.org/1999/xhtml}li") a = SubElement(li, "{http://www.w3.org/1999/xhtml}a") a.set("href", toc_entry.href) a.text = toc_entry.short_label a.set("class", "toc") self.book.write_element('nav.xhtml', nav)