def testcase_XML(webappName): tree = ElementTree() tree.parse(const.path + "/tests.result.xml") root = tree.getroot() lst_node = root.getiterator("set") for node in lst_node: SubElement( node, "testcase", { "component": "core", "purpose": "Check if Packaged Web Application can be installed/launch/uninstall successfully", "execution_type": "auto", "id": webappName, }, ) cnode = root.getiterator("testcase") desnode = cnode[-1] SubElement(desnode, "description") entrynode = desnode[0] SubElement(entrynode, "test_script_entry", {"test_script_expected_result": "0"}) entryentrynode = root.getiterator("test_script_entry") entr = entryentrynode[-1] entr.text = ( "app_user@/opt/usr/media/tct/opt/wrt-manifest-tizen-tests/appinstall.sh " + webappName + "." + Pack_Type ) tree.write(const.path + "/tests.result.xml")
def writeFile(path, element, verbose=False): if verbose: if os.path.exists(path): # TODO Determine if the element has not changed print("## Overwrite existing file: ", path) else: print("@@ Creating new file: ", path) # Get the namespace of this element namespace = element.getNamespace() # Register this namespace with the parser as the default namespace xml.etree.ElementTree.register_namespace('', namespace) e = element.getElement() # Fix up the element so it will print nicely OvalDocument.indent(e) # Create a new ElementTree with this element as the root tree = ElementTree(e) # And finally, write the full tree to a file including the xml declaration parent = os.path.dirname(path) if not os.path.isdir(parent): try : os.makedirs(parent, 0o755, True) except: return False tree.write(path, "UTF-8", True) # xml.etree.ElementTree.dump(tree) return True
def determine_subtype_element(in_file, delete_extra = True): hits = defaultdict(int) try: tree = ElementTree(file = in_file) for it in tree.getiterator('Iteration'): hit_list = it.getiterator('Hit') if len(hit_list) > 0: hit = hit_list[0].find('Hit_def').text hits[hit.split('_')[1]] += 1 if delete_extra: for hit in hit_list[1:]: hit.clear() if delete_extra: tree.write(in_file) except ExpatError: return None count = sum(hits.values()) if count < 5: return None elif all([x < count*0.6 for x in hits.values()]): print 'too heterogenus %s' % ','.join(map(str,hits.items())) return None else: for key, val in hits.items(): if val > count*0.6: return key
def insert_to_Summary(sumaryfile,total_case,pass_case,pass_rate,fail_case,fail_rate,block_case,block_rate): try: tree = ElementTree() tree.parse(sumaryfile) root = tree.getroot() ntotal_case = root.getiterator("total_case") ntotal_case[0].text = str(total_case) npass_case = root.getiterator("pass_case") npass_case[0].text = str(pass_case) npass_case_rate = root.getiterator("pass_rate") npass_case_rate[0].text = str(pass_rate) nfail_case = root.getiterator("fail_case") nfail_case[0].text = str(fail_case) nfail_case_rate = root.getiterator("fail_rate") nfail_case_rate[0].text = str(fail_rate) nblock_case = root.getiterator("block_case") nblock_case[0].text = str(block_case) nblock_case_rate = root.getiterator("block_rate") nblock_case_rate[0].text = str(block_rate) test_end_time = datetime.now().strftime('%m-%d-%H:%M:%S') ntest_start_time = root.getiterator("start_at") ntest_start_time[0].text = str(test_start_time) ntest_end_time = root.getiterator("end_at") ntest_end_time[0].text = str(test_end_time) device_id_get = root.getiterator("environment") device_id_get[0].set("device_id",Device_Ip) tree.write(sumaryfile) except Exception,e: print Exception,"Insert to report/summart.xml -------------------------> error:",e
def result_manifest_XML(result_manifest_xml_file_path,webappFile,auto_Result,manifest_cont): try: tree = ElementTree() tree.parse(result_manifest_xml_file_path + "/result/" + webappFile) root = tree.getroot() rset = root.getchildren() for mset in rset: testcase = mset.findall("set") testcase[0].set("name",Test_Flag) for mtestcase in testcase: cnode = mtestcase.getiterator("testcase") if (len(cnode)==1): auto_result = root.getiterator("auto_result") #auto_result = cnode.getiterator("auto_result") auto_result[0].text = auto_Result else: if (len(cnode)==0): SubElement(mtestcase,"testcase", {'component':'Runtime Core','purpose':'Check if packaged web application can be installed/launched/uninstalled successfully','execution_type' : 'auto', 'id' : webappFile.split(".")[0]}) result_node = mtestcase.find("testcase") SubElement(result_node,"auto_result") SubElement(result_node,"testcommand") auto_node = result_node.find("auto_result") auto_node.text = auto_Result testcommand_node = result_node.find("testcommand") testcommand_node.text = manifest_cont.decode("utf-8") tree.write(result_manifest_xml_file_path + "/result/" + webappFile) except Exception,e: print Exception,"Generate manifest.xml error:",e
def creating_xml(file1,file2,path_for_reference_xsd, xsd_path,schema_url,outputfile): value_list,template_id,templatestring,last_value1=test(file1,file2,path_for_reference_xsd, xsd_path) root=Element("template") p=templatestring.split("-",1)[1] tree=ElementTree(root) root.set("xsi:schemaLocation","https://appliedbroadband.com/ipdr/template_block template_block.xsd") root.set("xmlns","https://appliedbroadband.com/ipdr/template_block") root.set("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance") templateId=Element("templateId") schemaName=Element("schemaName") typeName=Element("typeName") root.append(templateId) root.append(schemaName) root.append(typeName) templateId.text=str(template_id) schemaName.text=str(schema_url)+str(last_value1) typeName.text=str(templatestring)+":"+str(templatestring.split("-",1)[1]) for i in value_list: field=Element("field") root.append(field) typeId=Element("typeId") fieldId=Element("fieldId") fieldName=Element("fieldName") isEnabled=Element("isEnabled") field.append(typeId) field.append(fieldId) field.append(fieldName) field.append(isEnabled) typeId.text=str(i[0]) fieldId.text=str(i[1]) fieldName.text=str(i[2]) isEnabled.text=str(i[3]) print Etree.tostring(root) tree.write(open(r'%s'%outputfile,"w+"))
def as_xml(self): """XML representation of the error to be used in HTTP response. This XML format follows the IIIF Image API v1.0 specification, see <http://iiif.io/api/image/1.0/#error> """ # Build tree spacing = ("\n" if (self.pretty_xml) else "") root = Element('error', {'xmlns': I3F_NS}) root.text = spacing e_parameter = Element('parameter', {}) e_parameter.text = self.parameter e_parameter.tail = spacing root.append(e_parameter) if (self.text): e_text = Element('text', {}) e_text.text = self.text e_text.tail = spacing root.append(e_text) # Write out as XML document to return tree = ElementTree(root) xml_buf = io.BytesIO() if (sys.version_info < (2, 7)): tree.write(xml_buf, encoding='UTF-8') else: tree.write(xml_buf, encoding='UTF-8', xml_declaration=True, method='xml') return(xml_buf.getvalue().decode('utf-8'))
def generate_xml_semcor(tokens,final_results): my_xml = Element('text') ## Root my_xml.tail = my_xml.text = '\n' previous_sent = None sent_ele = None for token_id, token, pos, lemma, num_sentence in tokens: guess = final_results.get(token_id) if previous_sent is None: sent_ele = Element('sent',{'sent_num':str(num_sentence)}) elif num_sentence != previous_sent: sent_ele.tail = sent_ele.text ='\n' my_xml.append(sent_ele) sent_ele = Element('sent',{'s_num':str(num_sentence)}) wf_ele = Element('wf',{'id':token_id,'lemma':lemma, 'pos':pos}) wf_ele.text = token if guess is not None: wf_ele.set('sense_label',str(guess[0])) wf_ele.set('sense_confidence',str(round(guess[1],4))) wf_ele.tail = '\n' previous_sent = num_sentence sent_ele.append(wf_ele) sent_ele.tail = sent_ele.text = '\n' my_xml.append(sent_ele) ## append the last one my_tree = ElementTree(element=my_xml) my_tree.write(sys.stdout, encoding="UTF8")
def updatetrafficlights(self): tree = ElementTree() tree.parse(self.trafficsignaldataxml) #Get traffic light states #format: ['202305458', 'grygrygrygrygrygry'], ['202305472', 'gGGGgGGGGgGGGgGGGG']]} trafficlights = self.getTrafficLightValues() for trafficlight in trafficlights: trafficlightID = trafficlight[0] linklights = list(trafficlight[1]) for link_index in range(len(linklights)): items = tree.findall('trafficlight') for item in items: # Remove letter g from links purestr = str(item.attrib['link_index']).replace("g", "") link_indexes = purestr.split("!") # if the traffic light id matches if str(item.attrib['intersection_id']) == trafficlightID: # if link index is in the link_indexes if str(link_index) in link_indexes: item.attrib['state'] = getTrafficLightState(linklights[link_index]) #logging.info({"id":trafficlight,"intersection id":trafficlightID,"link index":link_index, "state":getTrafficLightState(linklights[link_index])}) tree.write(self.trafficsignaldataxml)
def update_show_indexer_metadata(self, show_obj): if self.show_metadata and show_obj and self._has_show_metadata(show_obj): sickrage.srLogger.debug( "Metadata provider " + self.name + " updating show indexer info metadata file for " + show_obj.name) nfo_file_path = self.get_show_file_path(show_obj) try: with io.open(nfo_file_path, 'rb') as xmlFileObj: showXML = ElementTree(file=xmlFileObj) indexerid = showXML.find('id') root = showXML.getroot() if indexerid is not None: indexerid.text = str(show_obj.indexerid) else: SubElement(root, "id").text = str(show_obj.indexerid) # Make it purdy indentXML(root) showXML.write(nfo_file_path, encoding='UTF-8') chmodAsParent(nfo_file_path) return True except IOError as e: sickrage.srLogger.error( "Unable to write file to " + nfo_file_path + " - are you sure the folder is writable? {}".format(e.message))
def genSummaryXml(): try: tree = ElementTree() root = Element("result_summary", {"plan_name":""}) tree._setroot(root) env = SE(root,"environment",{"build_id":"","cts_version":"","device_id":"","device_model":"","device_name":"","host":"","resolution":"","screen_size":"","manufacturer":""}) summary = SE(root, "summary") startTime = SE(summary, "start_at") endTime = SE(summary, "end_at") startTime.text = Start endTime.text = End suite = SE(root, "suite", {"name":"wrt-packertool-android-tests"}) total_case = SE(suite, "total_case") total_case.text = str(totalNum) pass_case = SE(suite, "pass_case") pass_case.text = str(passNum) pass_rate = SE(suite, "pass_rate") pass_rate.text = str(float(passNum) / totalNum * 100) fail_case = SE(suite, "fail_case") fail_case.text = str(failNum) fail_rate = SE(suite, "fail_rate") fail_rate.text = str(float(failNum) / totalNum * 100) SE(suite, "block_case") SE(suite, "block_rate") SE(suite, "na_case") SE(suite, "na_rate") tree.write(ConstPath + "/report/summary.xml") updateXmlTitle(ConstPath + "/report/summary.xml",'<?xml version="1.0" encoding="UTF-8"?>\n<?xml-stylesheet type="text/xsl" href="./style/summary.xsl"?>\n') print "Generate summary.xml file ------------------------->O.K" except Exception,e: print Exception,"Generate summary.xml error:",e
def remove_input_from_fjr(self, list_of_good_files): """ to remove the input file from fjr in the case of problem with lfn """ from xml.etree.ElementTree import ElementTree, Element new_good_list = [] no_inp_dir = self.fjrDirectory + 'no_inp' if not os.path.isdir(no_inp_dir): try: os.mkdir(no_inp_dir) print "no_inp_dir = ", no_inp_dir except: print "problem during no_inp_dir creation: ", no_inp_dir for file in list_of_good_files: name_of_file = os.path.basename(file) #print "name_of_file = " , name_of_file oldxmlfile = ElementTree() oldxmlfile.parse(file) newxmlfile = ElementTree(Element(oldxmlfile.getroot().tag)) self.recurse(oldxmlfile.getroot(), newxmlfile.getroot()) new_good_file = no_inp_dir + '/' + name_of_file newxmlfile.write(new_good_file) new_good_list.append(new_good_file) print "new_good_list = ", new_good_list return new_good_list
class XmlWriter(): def __init__(self): self.tree = ElementTree() self.root = Element('poem') self.tree._setroot(self.root) print "##################" print locals() print "##################" def addItem(self,map): if map != None: item = Element("item", {'id' : map['id'], 'name' : map['name'], 'poet':map['poet'], 'type':map['type']}) SubElement(item,'value').text = map['value'] SubElement(item,'remark').text = map['remark'] SubElement(item,'translation').text = map['translation'] SubElement(item,'analysis').text = map['analysis'] self.root.append(item) def write(self,path): if path != None: dump(self.indent(self.root)) self.tree.write(path,'utf-8') def indent(self,elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for e in elem: self.indent(e, level+1) if not e.tail or not e.tail.strip(): e.tail = i if level and (not elem.tail or not elem.tail.strip()): elem.tail = i return elem
def etree_replace_text(filename, path, text): from xml.etree.ElementTree import ElementTree tree = ElementTree(file=filename) node = tree.find(path) if node != None: node.text = text tree.write(filename, encoding='UTF-8', xml_declaration=True) #(, short_empty_elements=False)
def generateConfigFile(app_store, app_ver, app_description): xml = ElementTree() update = Element('update') xml._setroot(update) SubElement(update,'version').text = app_ver SubElement(update,'name').text = 'cleanspace' app_name = 'cleanspace_' + app_ver + '.apk' url = 'http://thelinkit.com/photoclean/update/android/%s/%s'% (app_store,app_name) url.join('</url>') testurl = 'http://thelinkit.com/photoclean/update/android/%s/test/%s'% (app_store,app_name) testurl.join('</testurl>') SubElement(update,'url').text = url SubElement(update,'testurl').text = testurl SubElement(update,'description').text = app_description path = "./bin/" + app_store; if not os.path.isdir(path): os.mkdir(path) if not os.path.isdir(path +'/test'): os.mkdir(path + '/test') testpath = path + '/test/update.xml' path += '/update.xml' xml.write(path,'utf-8'); xml.write(testpath,'utf-8');
def dump(self, file_or_filename): root = Element( 'VTKFile', attrib={ 'type': self.type, 'version': self.version, 'byte_order': self.byte_order, 'compressor': self.compressor }) collection = SubElement( root, 'Collection') for dataset in self.datasets: SubElement( collection, 'DataSet', attrib={ 'file': str(dataset.file), 'timestep': str(dataset.timestep), 'group': str(dataset.group), 'part': str(dataset.part) }) tree = ElementTree(root) tree.write(file_or_filename)
def write_to_xml(): ''' int: rpm # Nr of rpm str: action # Aktion could be stop or start str: time # Time when action occurred https://www.youtube.com/watch?v=OAfeQuNhcps ''' from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import Element # import xml.etree.ElementTree as etree root = Element('Action') tree = ElementTree(root) skruv = Element('Skruv') root.append(skruv) # return skruv # def send_to_xmlfile(skruv, action, time, rpm): skruv.text = str('786234876') root.set('start', '13:26:65') skruv.text = str('5467490') root.set('start', '13:35:65') # print etree.tostring(root) tree.write(open(r'/tmp/oneWire.xml', 'w'))
def resources_as_xml(self, resources, num_resources=None, capabilities=None): """Return XML for a set of resources in sitemap format resources is either an iterable or iterator of Resource objects. If num_resources is not None then only that number will be written before exiting. """ # will include capabilities if allowed and if there are some namespaces = { 'xmlns': SITEMAP_NS, 'xmlns:rs': RS_NS } if ( capabilities is not None and len(capabilities)>0 ): namespaces['xmlns:xhtml'] = XHTML_NS root = Element('urlset', namespaces) if (self.pretty_xml): root.text="\n" if ( capabilities is not None and len(capabilities)>0 ): self.add_capabilities_to_etree(root,capabilities) # now add the entries from either an iterable or an iterator for r in resources: e=self.resource_etree_element(r) root.append(e) if (num_resources is not None): num_resources-=1 if (num_resources==0): break # have tree, now serialize tree = ElementTree(root); xml_buf=StringIO.StringIO() if (sys.version_info < (2,7)): tree.write(xml_buf,encoding='UTF-8') else: tree.write(xml_buf,encoding='UTF-8',xml_declaration=True,method='xml') return(xml_buf.getvalue())
def writeLightData(pathToXML = ''): """ Function to write out LightSetting """ ## now process the data into the xml tree root = Element('Lights') tree = ElementTree(root) lightSettingsData = _RecordLightSetting() lightData = _RecordLight() lightSettingsName = Element('LightSetting') root.append(lightSettingsName) lightName = Element('Light') root.append(lightName) for eachLightKey, eachLightValue in lightData.items(): newLightName = SubElement(lightName, str(eachLightKey)) for eachAttr , eachValue in eachLightValue.items(): lightType = SubElement(newLightName, eachAttr, value = str(eachValue)) for eachlayer , eachlayerValue in lightSettingsData.items(): passName = SubElement(lightSettingsName, str(eachlayer)) for eachSetKey , eachSetValue in eachlayerValue.items(): passType = SubElement(passName, eachSetKey, value = str(eachSetValue)) tree.write(open(pathToXML, 'w'), encoding="utf-8")
def _write_xml(self, fp, **backend_device_args): if not os.path.exists(self._DEFAULT_XML_TEMPLATE_PATH): print_or_raise("XML file template %s not exists,can't load defult " "params." % self._DEFAULT_XML_TEMPLATE_PATH, ScriptInnerError) mgnt_ip = backend_device_args['management_ips'][0] data_ips = backend_device_args['data_ips'] user_name = backend_device_args['user_name'] user_pwd = backend_device_args['user_pwd'] pool = backend_device_args['pools'][0] xml_fp = fp tree = ElementTree() elements = tree.parse(self._DEFAULT_XML_TEMPLATE_PATH) self.update_xml_node(elements, "EternusIP", mgnt_ip) self.update_xml_node(elements, "EternusUser", user_name) self.update_xml_node(elements, "EternusPassword", user_pwd) self.update_xml_node(elements, "EternusPool", pool) self.update_xml_node(elements, "EternusSnapPool", pool) root = tree.getroot() map(root.remove, root.findall("EternusISCSIIP")) for ip in data_ips: element = Element("EternusISCSIIP") element.text = ip element.tail = "\n" root.insert(4, element) # root.append(element) tree.write(xml_fp, encoding="utf-8", xml_declaration=True)
def writePluginConfigs(channel, targetFilePath): targetTree = None targetRoot = None pluginNodes = None targetTree = ElementTree() targetRoot = Element('plugins') targetTree._setroot(targetRoot) if 'plugins' in channel: for plugin in channel['plugins']: typeTag = 'plugin' typeName = plugin['name'] typeVal = plugin['type'] pluginNode = SubElement(targetRoot, typeTag) pluginNode.set('name', typeName) pluginNode.set('type', typeVal) # write third plugin info thirdPlugins = channel.get('third-plugins') if thirdPlugins != None and len(thirdPlugins) > 0: for cPlugin in thirdPlugins: if 'plugins' in cPlugin and cPlugin['plugins'] != None and len(cPlugin['plugins']) > 0: for plugin in cPlugin['plugins']: typeTag = 'plugin' typeName = plugin['name'] typeVal = plugin['type'] pluginNode = SubElement(targetRoot, typeTag) pluginNode.set('name', typeName) pluginNode.set('type', typeVal) targetTree.write(targetFilePath, 'UTF-8')
def modify_serverxml(serverxml, port, docbase): try: tree = ElementTree() tree.parse(serverxml) serverElem = tree.findall(".") for s in serverElem: s.set("port", str(int(port)+1)); connectors = tree.findall("Service/Connector") for c in connectors: if c.get("port") == "8080": c.set("port", port) continue if c.get("port") == "8009": c.set("port", str(int(port)+2)) continue hosts = tree.findall("Service/Engine/Host") for h in hosts: if h.get("name") == "localhost": context_properties={'docBase':docbase, 'path':'', 'reloadable':'false'} context = Element("Context", context_properties) h.append(context) break tree.write(serverxml, encoding='utf-8', xml_declaration=True) return 0 except: return 1
def createProfile(username, directory='profiles/'): if username == "" or username == None: return False treeP = ElementTree() root = Element("root") name = Element("name") name.text = username root.append(name) levels = Application.getDirectories("levels") for level_name in levels: nivel = Element("level") nivel.set("id", level_name) puzzles = Application.getFiles("levels/"+level_name) for puzzle in puzzles: if "_top" in puzzle: continue pz = Element("puzzle") pz.set("id", puzzle) pz.text = "0" nivel.append(pz) root.append(nivel) treeP._setroot(root) treeP.write(directory+username+".xml") return True
def updateTopFile(directory, filename, user, score, top_n = 5): if not Application.existsFile(directory, filename): Application.createTopFile(directory, filename, top_n) pla = Application.getTopPlayers(directory, filename) t = [f for f in pla if f[0]==user and int(f[1])>score] if len(t) == 0: return False treeP = ElementTree() treeP.parse(directory+filename+".xml") root = treeP.getroot() new_root = Element("top_scores") ranks = root.findall("rank") top = min([top_n, len(ranks)]) score_i = int(ranks[0].text) score_f = int(ranks[top-1].text) ins = False for i in range(top): if score <= int(ranks[i].text) or (ranks[i].attrib["user"] == "__EMPTY__"): tmp = Element("rank") tmp.set("user", user) tmp.text = str(score) new_root.append(tmp) ins = True break else: new_root.append(ranks[i]) for j in range(i,top - 1): new_root.append(ranks[j]) treeP2 = ElementTree() treeP2._setroot(new_root) treeP2.write(directory+filename+".xml") return ins
def inventory_as_xml(self, inventory, entries=None, include_capabilities=True): """Return XML for an inventory in sitemap format If entries is specified then will write a sitemap that contains only the specified entries from the inventory. """ # will include capabilities if allowed and is there are some include_capabilities = include_capabilities and (len(inventory.capabilities)>0) namespaces = { 'xmlns': SITEMAP_NS, 'xmlns:rs': RS_NS } if (include_capabilities): namespaces['xmlns:atom'] = ATOM_NS root = Element('urlset', namespaces) if (self.pretty_xml): root.text="\n" if (include_capabilities): self.add_capabilities_to_etree(root,inventory.capabilities) if (entries is None): entries=inventory.resource_uris() for r in entries: e=self.resource_etree_element(inventory.resources[r]) if (self.pretty_xml): e.tail="\n" root.append(e) tree = ElementTree(root); xml_buf=StringIO.StringIO() if (sys.version_info < (2,7)): tree.write(xml_buf,encoding='UTF-8') else: tree.write(xml_buf,encoding='UTF-8',xml_declaration=True,method='xml') return(xml_buf.getvalue())
def saveScore(username, level, puzzle, score): retVal = "NOT_FOUND" scores_tuplas = [] treeP = ElementTree() treeP.parse("profiles/"+username+".xml") root = treeP.getroot() levels = root.findall("level") for level_ in levels: if level_.attrib["id"] == level: for i in level_.iter("puzzle"): if i.attrib["id"] == str(puzzle): if i.text == "0": i.text = str(score) retVal = "FIRST_TIME" elif int(i.text)>int(score): i.text = str(score) retVal = "BETTER" elif int(i.text)<int(score): retVal = "NOT_BETTER" else: retVal = "EQUAL" break treeP.write("profiles/" + username + ".xml") return retVal
def dumpGEXF(self,targetfp,projectName): self.ensureDumpBase() tb=TreeBuilder() tb.start("gexf",{"xmlns":"http://www.gexf.net/1.2draft","version":"1.2"}) tb.start("meta",{"lastmodifieddate":str(datetime.datetime.now())}) tb.start("creator",{}) tb.data("LAVI Collector") tb.end("creator") tb.start("description",{}) tb.data(projectName) tb.end("description") tb.end("meta") tb.start("graph",{"mode":"dynamic","start":formatTstamp(self.mint),"end":formatTstamp(self.maxt)}) tb.start("nodes",{}) for id,email,mint,maxt in self.nodesIterator(): tb.start("node",{"id":id,"label":email,"start":formatTstamp(mint),"end":formatTstamp(maxt)}) tb.end("node") tb.end("nodes") tb.start("edges",{}) for id,sender,rec,tstamp in self.edgesIterator(): tb.start("edge",{"id":id, "source":sender,"target":rec,"start":formatTstamp(tstamp),"end":formatTstamp(tstamp)}) tb.end("edge") tb.end("edges") tb.end("graph") tb.end("gexf") et=ElementTree(tb.close()) et.write(targetfp, encoding="UTF-8")
def emit(self, removal = False): u""" インデックスファイルを更新する. """ self.lock.acquire() try: doc = None if os.path.isfile(self.filename): doc = ElementTree(file = self.filename) else: root = Element("index") doc = ElementTree(root) index = -1 for i, e in enumerate(doc.findall("live")): if e.get("server", "") == self.server_address: index = i doc.getroot().remove(e) if self.on_list: doc.getroot().insert(index, self.live_element()) f = open(self.filename, "w") f.write('<?xml version="1.0" encoding="%s"?>\n' % self.encoding) doc.write(f, self.encoding) f.close() finally: self.lock.release()
def CreateConfigurationXML(): """ Create the Configuration XML """ togglFilename = GetTogglXMLFilename() element = Element("toggl") tree = ElementTree(element) tree.write(togglFilename) return tree
def build_function(target, source, env): target = str(target[0]) # Create package build dir if target[-4:] != '.zip': raise Exception, 'Expected .zip in package name' build_dir = target[:-4] # Remove .zip if os.path.exists(build_dir): shutil.rmtree(build_dir) # Make dirs contents_dir = os.path.join(build_dir, 'Contents') packages_dir = os.path.join(contents_dir, 'Packages') resources_dir = os.path.join(contents_dir, 'Resources') for d in (contents_dir, packages_dir, resources_dir): os.makedirs(d, 0775) # Load package info pkg_info = [] packages = env.get('distpkg_packages', []) for p in packages: infofile = os.path.join(p, 'Contents/Info.plist') if os.path.exists(infofile): pkg_info.append(plistlib.readPlist(infofile)) else: raise Exception, 'Missing %s' % infofile # Create distribution.dist root = Element('installer-script', {'minSpecVersion': '1.0'}) SubElement( root, 'options', { 'rootVolumeOnly': 'false' if env.get('distpkg_root_volume_only', False) else 'true', 'allow-external-scripts': 'yes' if env.get('distpkg_allow_external_scripts', False) else 'no', 'customize': env.get('distpkg_customize', 'allow'), }) SubElement(root, 'title').text = env.get('summary') for key in 'background colclusion license readme welcome'.split(): if 'distpkg_' + key in env: SubElement(root, key, {'file': env.get('distpkg_' + key)}) outline = SubElement(root, 'choices-outline') for i in range(len(pkg_info)): info = pkg_info[i] id = info['CFBundleIdentifier'] choice_id = id + '.choice' SubElement(outline, 'line', {'choice': choice_id}) choice = SubElement( root, 'choice', { 'id': choice_id, 'title': id, 'description': '', 'start_visible': 'true', 'start_selected': 'true', }) SubElement(choice, 'pkg-ref', {'id': id}) pkg_path = 'file:./Contents/Packages/' + os.path.basename(packages[i]) pref = SubElement( root, 'pkg-ref', { 'id': id, 'installKBytes': str(info['IFPkgFlagInstalledSize']), 'version': info['CFBundleShortVersionString'], }).text = pkg_path tree = ElementTree(root) f = None try: f = open(contents_dir + '/distribution.dist', 'w') tree.write(f, 'utf-8') finally: if f is not None: f.close() # Install files env.InstallFiles('distpkg_resources', resources_dir) env.InstallFiles('distpkg_packages', packages_dir, perms=0) # Zip results env.ZipDir(target, build_dir)
SubElement(B5, "depth").text = baseInfo['size/depth'] #"3" A1.append(B5) # SubElement(A1,"folder").text=str(width[i]) # SubElement(A1,"filename").text=str(height[i]) # SubElement(A1,"path").text="3" for idx_f_2, oject_2 in enumerate(objects_2): if oject_2['name'] == "background": continue BBobj = create_node('object', {}, "") SubElement(BBobj, "name").text = oject_2['name'] SubElement(BBobj, "pose").text = 'Unspecified' SubElement(BBobj, "truncated").text = '0' SubElement(BBobj, "difficult").text = '0' # SubElement(BBobj,"score").text=oject_2['score'] # SubElement(BBobj,"region").text=oject_2['region'] # SubElement(BBobj,"label_des").text=oject_2['label_des'] # SubElement(BBobj,"imageptr").text=oject_2['imageptr'] child5 = SubElement(BBobj, "bndbox") # child1= create_node('name',{},obj['name']) SubElement(child5, "xmin").text = str(oject_2["bbox"][0]) SubElement(child5, "ymin").text = str(oject_2["bbox"][1]) SubElement(child5, "xmax").text = str(oject_2["bbox"][2]) SubElement(child5, "ymax").text = str(oject_2["bbox"][3]) A1.append(BBobj) print out_xmldir + "/" + basename_2 + ".xml" four_root.write(out_xmldir + "/" + basename_2 + ".xml", encoding="utf-8", xml_declaration=False) #plt.show()
middlename = None lastname = None some_names = name.split(' ') if len(some_names) == 2: firstname = some_names[1] lastname = some_names[0][:-1] middlename = None elif len(some_names) == 3: (firstname, middlename, lastname) = some_names lastname = lastname[:-1] root_e = SubElement(topmost_e, "PHONE") name_e = SubElement(root_e, "NAME") if firstname is not None: first_e = SubElement(name_e, "FIRST") first_e.text = firstname if middlename is not None: middle_e = SubElement(name_e, "MIDDLE") middle_e.text = middlename if lastname is not None: last_e = SubElement(name_e, "LAST") last_e.text = lastname office_e = SubElement(root_e, "OFFICE") office_e.text = office phone_e = SubElement(root_e, "PHONE") phone_e.text = phone email_e = SubElement(root_e, "EMAIL") email_e.text = email tree.write(f)
def create_xml(num_of_objects, labels, dimensions): #create file #open('/home/creaton/yolo_test2/xml_files/' + str(image_name) + str(index) + '.xml', "w+") #initialise xml xml_path = '/home/creaton/yolo_test2/actual_training/labels/' + str( image_name) + str(index_3d) + '.xml' root = Element("Annotation") tree = ElementTree(root) #Create filename tag filename = Element("filename") root.append(filename) filename.text = str(image_name) + str(index_3d) + '.jpg' #create photo size tag size = Element("size") root.append(size) #with tag in photo size width = Element("width") size.append(width) width.text = str(int_width) #height tag in photo size height = Element("height") size.append(height) height.text = str(int_height) #create object tag for x in range(0, num_of_objects): #object tag object = Element("object") root.append(object) #object name name = Element("name") object.append(name) name.text = str(labels[x]) #bounding boxes coordinates bndbox = Element("bndbox") object.append(bndbox) #seperate coordinates into xmin,ymin,xmax,ymax xmin = Element("xmin") bndbox.append(xmin) xmin.text = str(dimensions[x][0]) ymin = Element("ymin") bndbox.append(ymin) ymin.text = str(dimensions[x][1]) xmax = Element("xmax") bndbox.append(xmax) xmax.text = str(dimensions[x][2]) ymax = Element("ymax") bndbox.append(ymax) ymax.text = str(dimensions[x][3]) tree.write(xml_path)
def create_request_xml(self, **kwargs): order_id = kwargs.get('order_id') order_type = kwargs.get('order_type', 'card') timestamp = kwargs.get('timestamp') amount = kwargs.get('amount') currency = kwargs.get('currency', 'RON') customer_id = kwargs.get('customer_id') details = kwargs.get('details') billing = kwargs.get('billing') params = kwargs.get('params', {}) confirm_url = kwargs.get('confirm_url') return_url = kwargs.get('return_url') order = Element('order', type=order_type, id=order_id, timestamp=timestamp) signature = SubElement(order, 'signature') signature.text = self.signature invoice = SubElement(order, 'invoice', currency=currency, amount=str(amount), customer_type="2", customer_id=str(customer_id)) details_el = SubElement(invoice, 'details') details_el.text = details if billing: first_name = billing.get('first_name', '') last_name = billing.get('last_name', '') address = billing.get('address', '') email = billing.get('email', '') phone = billing.get('phone', '') contact_info = SubElement(invoice, 'contact_info') billing = SubElement(contact_info, 'billing', type="person") first_name_el = SubElement(billing, 'first_name') first_name_el.text = first_name last_name_el = SubElement(billing, 'last_name') last_name_el.text = last_name address_el = SubElement(billing, 'address') address_el.text = address email_el = SubElement(billing, 'email') email_el.text = email phone_el = SubElement(billing, 'mobile_phone') phone_el.text = phone # if we have other params to add if params: params = SubElement(order, 'params') def add_other_param(param_name, param_value): if param_name and param_value: param = SubElement(params, 'param') name = SubElement(param, 'name') name.text = param_name value = SubElement(param, 'value') value.text = str(param_value) for param in params: add_other_param(key, params[key]) url = SubElement(order, 'url') confirm = SubElement(url, 'confirm') confirm.text = confirm_url return_url_el = SubElement(url, 'return') return_url_el.text = return_url parent_element = ElementTree(order) virtual_file = BytesIO() parent_element.write(virtual_file, encoding='utf-8', xml_declaration=True) return virtual_file.getvalue()
def write(self, fh): # Serialize graph G in GEXF to the open fh if self.prettyprint: self.indent(self.xml) document = ElementTree(self.xml) document.write(fh, encoding=self.encoding, xml_declaration=True)
def get_state_changes(self, gexf_file, grep_log_file, steps=400, out_dir=None): """ grep -R "changed to state" --include=*.log . > statelog.txt the simulation time will be evenly divided up by "steps" """ # convert grep_log_file to csv if (out_dir is None): out_dir = os.path.dirname(gexf_file) #grep_log_file = '{0}/statelog.txt'.format(out_dir) #cmd = "" csv_file = '{0}/csv_file.csv'.format(out_dir) sqlite_file = '{0}/sqlite_file.sqlite'.format(out_dir) if (not os.path.exists(csv_file)): with open(grep_log_file, "r") as f: alllines = f.readlines() with open(csv_file, "w") as fo: for line in alllines: ts = line.split('[DEBUG]')[0].split('dlgNM.log:')[1].strip() ts = int(dt.strptime(ts,'%Y-%m-%d %H:%M:%S,%f').strftime('%s')) oid = line.split('oid=')[1].split()[0] state = line.split()[-1] fo.write('{0},{1},{2},{3}'.format(ts, oid, state, os.linesep)) else: logger.info("csv file already exists: {0}".format(csv_file)) if (not os.path.exists(sqlite_file)): sql = sql_create_status.format(csv_file) sql_file = csv_file.replace('.csv', '.sql') with open(sql_file, "w") as fo: fo.write(sql) cmd = "sqlite3 {0} < {1}".format(sqlite_file, sql_file) ret = commands.getstatusoutput(cmd) if (ret[0] != 0): logger.error("fail to create sqlite: {0}".format(ret[1])) return else: logger.info("sqlite file already exists: {0}".format(sqlite_file)) dbconn = dbdrv.connect(sqlite_file) q = "SELECT min(ts) from ac" cur = dbconn.cursor() cur.execute(q) lhs = cur.fetchall()[0][0] cur.close() q = "SELECT max(ts) from ac" cur = dbconn.cursor() cur.execute(q) rhs = cur.fetchall()[0][0] cur.close() step_size = (rhs - lhs) / steps if (step_size == 0): return lr = list(np.arange(lhs, rhs, step_size)) if (lr[-1] != rhs): lr.append(rhs) last_gexf = gexf_file for i, el in enumerate(lr[0:-1]): a = el b = lr[i + 1] step_name = '{0}-{1}'.format(a, b) logger.debug("stepname: %s" % step_name) new_gexf = '{0}/{1}.gexf'.format(out_dir, step_name) if (os.path.exists(new_gexf)): logger.info("{0} already exists, ignore".format(new_gexf)) last_gexf = new_gexf continue sql = sql_query.format(a, b) logger.debug(sql) cur = dbconn.cursor() cur.execute(sql) drops = cur.fetchall() cur.close() #build a dictionary drop_dict = dict() # key - gnid, value: drop status for drop in drops: gnid = self.oid_gnid_dict[drop[1]] drop_dict[gnid] = drop[2] tree = ElementTree() tree.parse(last_gexf) root = tree.getroot() for node in root.iter('{http://www.gexf.net/1.3}node'): gnid = node.attrib['id'] if (not gnid in drop_dict): continue new_status = drop_dict[gnid] r, g, b = self.status_to_colour(new_status) colour = node[2] colour.attrib['r'] = '{0}'.format(r) colour.attrib['g'] = '{0}'.format(g) colour.attrib['b'] = '{0}'.format(b) tree.write(new_gexf) logger.info("GEXF file '{0}' is generated".format(new_gexf)) del drop_dict if (not filecmp.cmp(last_gexf, new_gexf, False)): new_png = new_gexf.split('.gexf')[0] + '.png' cmd = "{0} {1} {2}".format(java_cmd, new_gexf, new_png) ret = commands.getstatusoutput(cmd) else: logger.info("Identical {0} == {1}".format(new_gexf, last_gexf)) last_gexf = new_gexf if (ret[0] != 0): logger.error("Fail to print png from %s to %s: %s" % (last_gexf, new_png, ret[1]))
def generate_annotation_xml(filename, path, width, height, depth, text_size1, text_size2, text_size3, text_size4, text_size5, name, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, word_len): root = Element('annotation') SubElement(root, 'folder').text = 'images' SubElement(root, 'filename').text = filename + '.png' size = SubElement(root, 'size') SubElement(size, 'width').text = str(width) SubElement(size, 'height').text = str(height) SubElement(size, 'depth').text = str(depth) SubElement(root, 'segmented').text = '0' # object 1 object = SubElement(root, 'object') SubElement(object, 'name').text = "text" SubElement(object, 'pose').text = 'Unspecified' SubElement(object, 'truncated').text = '0' SubElement(object, 'occluded').text = '0' SubElement(object, 'difficult').text = '0' bnd = SubElement(object, 'bndbox') # SubElement(bnd, 'xmin').text = str(x1 - text_size1/2) # SubElement(bnd, 'ymin').text = str(y1 - text_size1/2) # SubElement(bnd, 'xmax').text = str(x1 + text_size1/2) # SubElement(bnd, 'ymax').text = str(y1 + text_size1/2) SubElement(bnd, 'xmin').text = str(x1) SubElement(bnd, 'ymin').text = str(y1) SubElement(bnd, 'xmax').text = str(x1 + text_size1*(word_len-3)) SubElement(bnd, 'ymax').text = str(y1 + text_size1) # object 2 object = SubElement(root, 'object') SubElement(object, 'name').text = "text" SubElement(object, 'pose').text = 'Unspecified' SubElement(object, 'truncated').text = '0' SubElement(object, 'occluded').text = '0' SubElement(object, 'difficult').text = '0' bnd = SubElement(object, 'bndbox') # SubElement(bnd, 'xmin').text = str(x2 - text_size2/2) # SubElement(bnd, 'ymin').text = str(y2 - text_size2/2) # SubElement(bnd, 'xmax').text = str(x2 + text_size2/2) # SubElement(bnd, 'ymax').text = str(y2 + text_size2/2) SubElement(bnd, 'xmin').text = str(x2) SubElement(bnd, 'ymin').text = str(y2) SubElement(bnd, 'xmax').text = str(x2 + text_size2*(word_len-3)) SubElement(bnd, 'ymax').text = str(y2 + text_size2) # object 3 object = SubElement(root, 'object') SubElement(object, 'name').text = "text" SubElement(object, 'pose').text = 'Unspecified' SubElement(object, 'truncated').text = '0' SubElement(object, 'occluded').text = '0' SubElement(object, 'difficult').text = '0' bnd = SubElement(object, 'bndbox') # SubElement(bnd, 'xmin').text = str(x3 - text_size3/2) # SubElement(bnd, 'ymin').text = str(y3 - text_size3/2) # SubElement(bnd, 'xmax').text = str(x3 + text_size3/2) # SubElement(bnd, 'ymax').text = str(y3 + text_size3/2) SubElement(bnd, 'xmin').text = str(x3) SubElement(bnd, 'ymin').text = str(y3) SubElement(bnd, 'xmax').text = str(x3 + text_size3*(word_len-3)) SubElement(bnd, 'ymax').text = str(y3 + text_size3) # object 4 object = SubElement(root, 'object') SubElement(object, 'name').text = "text" SubElement(object, 'pose').text = 'Unspecified' SubElement(object, 'truncated').text = '0' SubElement(object, 'occluded').text = '0' SubElement(object, 'difficult').text = '0' bnd = SubElement(object, 'bndbox') # SubElement(bnd, 'xmin').text = str(x3 - text_size3/2) # SubElement(bnd, 'ymin').text = str(y3 - text_size3/2) # SubElement(bnd, 'xmax').text = str(x3 + text_size3/2) # SubElement(bnd, 'ymax').text = str(y3 + text_size3/2) SubElement(bnd, 'xmin').text = str(x4) SubElement(bnd, 'ymin').text = str(y4) SubElement(bnd, 'xmax').text = str(x4 + text_size4*(word_len-3)) SubElement(bnd, 'ymax').text = str(y4 + text_size4) # object 5 object = SubElement(root, 'object') SubElement(object, 'name').text = "text" SubElement(object, 'pose').text = 'Unspecified' SubElement(object, 'truncated').text = '0' SubElement(object, 'occluded').text = '0' SubElement(object, 'difficult').text = '0' bnd = SubElement(object, 'bndbox') # SubElement(bnd, 'xmin').text = str(x3 - text_size3/2) # SubElement(bnd, 'ymin').text = str(y3 - text_size3/2) # SubElement(bnd, 'xmax').text = str(x3 + text_size3/2) # SubElement(bnd, 'ymax').text = str(y3 + text_size3/2) SubElement(bnd, 'xmin').text = str(x5) SubElement(bnd, 'ymin').text = str(y5) SubElement(bnd, 'xmax').text = str(x5 + text_size5*(word_len-3)) SubElement(bnd, 'ymax').text = str(y5 + text_size5) tree = ElementTree(root) tree.write(path + filename + '.xml')
def cosmos_create_file(): # request.josn = 스프링에서 restTemplate로 보낸 json데이터를 담는다. data = request.json print(data) #기억이 안남 def indent(node, level=0): i = "\n" + level * " " * 4 if len(node): if not node.text or not node.text.strip(): node.text = i + " " * 4 if not node.tail or not node.tail.strip(): node.tail = i for node in node: indent(node, level + 1) if not node.tail or not node.tail.strip(): node.tail = i else: if level and (not node.tail or not node.tail.strip()): node.tail = i # BeautifulSoup 라이브러리를 사용해서 kst 파일 생성. # Root = KStars root = Element('KStars') # <Version> SubElement(root, 'Version').text = data['version'] # <Option> Option = SubElement(root, 'Option') # <Option> => <SpeakerList> for i in range(len(data['m_Option']["speakerList"])): SubElement(Option, "SpeakerList").text = data['m_Option']["speakerList"][i] # <Option> => <StringOption> SubElement(Option, "StringOption").text = data['m_Option']["stringOption"] # <Header> Header = SubElement(root, 'Header') # <Header> => <SpeechType> SubElement(Header, "SpeechType").text = data['m_header']['speechType'] # <Header> => <Participants> for i in range(len(data['m_header']['arrParticipants'])): SubElement( Header, "Participants").text = data['m_header']['arrParticipants'][i] # <Header> => <BirthPlaceofCHI> SubElement(Header, "BirthPlaceOfCHI").text = data['m_header']['birthPlaceOfCHI'] # <Header> => <Location> SubElement(Header, "Location").text = data['m_header']['location'] # <Header> => <Situation> SubElement(Header, "Situation").text = data['m_header']['situation'] # <Header> => <Recording> SubElement(Header, "Recording").text = data['m_header']['recording'] # <Header> => <Transcriber> SubElement(Header, "Transcriber").text = data['m_header']['transcriber'] # <Header> => <Reviewer> SubElement(Header, "Reviewer").text = data['m_header']['reviewer'] # <Header> => <Comment> SubElement(Header, "Comment").text = data['m_header']['comment'] # <Header> => <ID> for i in range(len(data['m_header']['arrID'])): UserID = SubElement(Header, "ID") # <Header> => <ID> => <IDCorpus> SubElement(UserID, "IDCorpus").text = data['m_header']['arrID'][i]['corpus'] # <Header> => <ID> => <IDCode> SubElement(UserID, "IDCode").text = data['m_header']['arrID'][i]['code'] # <Header> => <ID> => <IDDateOfBirth> SubElement( UserID, "IDDateOfBirth").text = data['m_header']['arrID'][i]['dateOfBirth'] # <Header> => <ID> => <IDAge> SubElement(UserID, "IDAge").text = data['m_header']['arrID'][i]['age'] # <Header> => <ID> => <IDSex> SubElement(UserID, "IDSex").text = data['m_header']['arrID'][i]['sex'] # <Header> => <ID> => <IDGroup> SubElement(UserID, "IDGroup").text = data['m_header']['arrID'][i]['group'] # <Header> => <ID> => <IDRegion> SubElement(UserID, "IDRegion").text = data['m_header']['arrID'][i]['region'] # <Header> => <ID> => <IDSES> SubElement(UserID, "IDSES").text = data['m_header']['arrID'][i]['ses'] # <Header> => <ID> => <IDEdu> SubElement(UserID, "IDEdu").text = data['m_header']['arrID'][i]['edu'] # <Header> => <ID> => <IDRole> SubElement(UserID, "IDRole").text = data['m_header']['arrID'][i]['role'] # <Tier type = "KUtterance"> KUtterance = SubElement(root, "Tier") KUtterance.attrib['type'] = data['m_KTierVer2']['dataType'] # <Tier type = "KUtterance"> => <Data> for i in range(len(data['m_KTierVer2']['datas'])): DataUtter = SubElement(KUtterance, "Data") # <Tier type = "KUtterance"> => <Data uid = "?"> DataUtter.attrib['uid'] = data['m_KTierVer2']['datas'][i]['uid'] # <Tier type = "KUtterance"> => <Data uid = "?"> => <Speaker> SubElement(DataUtter, 'Speaker').text = data['m_KTierVer2']['datas'][i]['speaker'] # <Tier type = "KUtterance"> => <Data uid = "?"> => <Text> SubElement(DataUtter, 'Text').text = data['m_KTierVer2']['datas'][i]['text'] # <Tier type = "KUtterance"> => <Data uid = "?"> => <Time> SubElement(DataUtter, 'Time').text = data['m_KTierVer2']['datas'][i]['time'] KMorpheme = SubElement(root, "Tier") KMorpheme.attrib['type'] = data['m_KTierMorpVer2']['dataType'] for i in range(len(data['m_KTierMorpVer2']['datas'])): DataMorp = SubElement(KMorpheme, "Data") DataMorp.attrib['uid'] = data['m_KTierMorpVer2']['datas'][i]['uid'] SubElement( DataMorp, 'Speaker').text = data['m_KTierMorpVer2']['datas'][i]['speaker'] SubElement(DataMorp, 'MEtri').text = data['m_KTierMorpVer2']['datas'][i]['morp'] SubElement(DataMorp, 'MUser').text = data['m_KTierMorpVer2']['datas'][i]['user'] Audio = SubElement(root, "Audio") for i in range(len(data['m_Audio']['audioPath'])): SubElement(Audio, 'AudioPath').text = data['m_Audio']['audioPath'][i] SubElement(Audio, 'AudioFileIndex').text = data['m_Audio']['audioFileIndex'] SubElement( Audio, 'AudioCurrentPosition').text = data['m_Audio']['audioCurrentPosition'] indent(root) tree = ElementTree(root) # localPath = os.path.abspath("C:/Users/User/eclipse-workspace/K-Stars/src/main/java/kr/ac/skuniv/cosmos") cloudPath = os.path.abspath("/home/ubuntu/kst") if data['userDto']['user'] == "guest": # tree.write(localPath + "\\guest\\temp\\" + data['userDto']['fileName'] + ".kst", encoding="utf-8") tree.write(cloudPath + "\\guest\\temp\\" + data['userDto']['fileName'] + ".kst", encoding="utf-8") elif data['userDto']['user'] == "user": try: # if not(os.path.isdir(localPath + "\\user\\" + data['userDto']['id'])): # os.makedirs(os.path.join(localPath + "\\user\\" + data['userDto']['id'])) # tree.write(localPath + "\\user\\" + data['userDto']['id'] + "\\" + data['userDto']['fileName'] + ".kst", encoding="utf-8") # if os.path.isdir(localPath + "\\user\\" + data['userDto']['id']): # tree.write(localPath + "\\user\\" + data['userDto']['id'] + "\\" + data['userDto']['fileName'] + ".kst", encoding="utf-8") if not (os.path.isdir(cloudPath + "\\user\\" + data['userDto']['id'])): os.makedirs( os.path.join(cloudPath + "\\user\\" + data['userDto']['id'])) tree.write(cloudPath + "\\user\\" + data['userDto']['id'] + "\\" + data['userDto']['fileName'] + ".kst", encoding="utf-8") if os.path.isdir(cloudPath + "\\user\\" + data['userDto']['id']): tree.write(cloudPath + "\\user\\" + data['userDto']['id'] + "\\" + data['userDto']['fileName'] + ".kst", encoding="utf-8") except OSError as e: if e.errno != errno.EEXIST: print("Failed to create directory!!!!!") raise return jsonify(data)
def save(self): self.uichanges() self.saveFile = self.archive root = ET.Element('programElements') tree = ElementTree(root) for i in range(self.list.count()): self.liTxt = self.list.item(i).text() listitem = ET.SubElement(root, 'listitem') licon = self.list_icons_dict[self.liTxt] listitem.set('item_icon', licon) listitem.text = self.liTxt for g in range(self.stack.count()): self.stackTab = self.stack.widget(g) tabwidgetName = ET.SubElement(root, 'tabwid_name') tabwidgetName.text = self.stackTab.objectName() for p in range(self.stackTab.count()): self.tabtext = self.stackTab.tabText(p) self.ticon = self.tabwidget_icons_dict[ self.stackTab.objectName()][self.tabtext] self.tabcontents = self.tabtext if not os.path.exists( os.path.splitext(self.saveFile)[0] + '/{}'.format(tabwidgetName.text) + '/{}/'.format(self.tabcontents)): os.makedirs( os.path.splitext(self.saveFile)[0] + '/{}'.format(tabwidgetName.text) + '/{}/'.format(self.tabcontents)) with open( r'{}'.format(os.path.splitext(self.saveFile)[0]) + r'/{}'.format(tabwidgetName.text) + r'/{}/{}.html'.format(self.tabcontents, self.tabcontents), 'w') as file: file.write(self.stackTab.widget(p).toHtml()) file.close() tabName = ET.SubElement(tabwidgetName, 'tabName') tabName.set('content', str(self.tabcontents)) tabName.set('tabIcon', self.ticon) tabName.text = self.tabtext tree.write(open(self.saveFile + '/config.xml', 'wb')) if '_' in self.saveFile: # used to add all files in the working directory with the -o flag and when i deleted it, it worked the way it should.....idk subprocess.run([ r'7z\7-Zip\7z.exe', 'a', '-p{}'.format(self.pw), '{}'.format( self.saveFile), '{}'.format(self.saveFile) ], shell=False) else: subprocess.run([ r'7z\7-Zip\7z.exe', 'a', '{}'.format(self.saveFile), '{}'.format(self.saveFile) ], shell=False) self.programconfig(self.saveFile) self.status = True
# -*- coding:utf-8 -*- from xml.etree.ElementTree import ElementTree, Element tree = ElementTree() tree.parse('morerout17-simple.xml') id = 1 for edge in tree.findall('Edge'): edge.set('ID', str(id)) id += 1 for child in edge.getchildren(): if child.tag == 'StackOperations': edge.remove(child) print 'delete StackOperations ' for edge in tree.findall('Edge'): for child in edge.getchildren(): if child.tag == 'LifecycleCallbacks': edge.remove(child) print 'delete LifecycleCallbacks' tree.write('./test.xml', encoding='utf-8', xml_declaration=False)
def write(self): "actiegegevens terugschrijven" if self.file_exists: # os.path.exists(self.fn): tree = ElementTree(file=str(self.fn)) rt = tree.getroot() sett = rt.find('settings') else: rt = Element("acties") sett = SubElement(rt, 'settings') # terugschrijven imagecount sett.set('imagecount', str( self.imagecount)) # moet dit niet parent.parent.imagecount zijn? if self.startitem: sett.set('startitem', str(self.startitem)) if not self.exists: x = SubElement(rt, "actie") x.set("id", self.id) x.set("datum", self.datum) found = True else: for x in rt.findall("actie"): if x.get("id") == self.id: found = True break if found: x.set("updated", dt.datetime.today().isoformat(' ')[:10]) print(self.soort) h = self.soort if h is None or h == '': self.soort = " " x.set("soort", self.soort) x.set("status", self.status) if self.arch: x.set("arch", "arch") else: h = x.get("arch") if h is not None: x.set("arch", "herl") h = x.find("titel") if h is None: h = SubElement(x, "titel") h.text = self.titel h = x.find("melding") if h is None: h = SubElement(x, "melding") h.text = self.melding h = x.find("oorzaak") if h is None: h = SubElement(x, "oorzaak") h.text = self.oorzaak h = x.find("oplossing") if h is None: h = SubElement(x, "oplossing") h.text = self.oplossing h = x.find("vervolg") if h is None: h = SubElement(x, "vervolg") h.text = self.vervolg h = x.find("stand") if h is None: h = SubElement(x, "stand") h.text = self.stand h = x.find("events") if h is not None: x.remove(h) h = SubElement(x, "events") for y, z in self.events: q = SubElement(h, "event", id=y) q.text = z h = x.find("images") if h is not None: x.remove(h) h = SubElement(x, "images") for fname in self.imagelist: q = SubElement(h, 'image', filename=fname) with open(fname, 'rb') as _in: data = _in.read() log('length of data:', len(data)) q.text = str(base64.b64encode(data)) log('length of text:', len(q.text)) ## q.text = str(base64.encodebytes(data)) ## q.text = str(gzip.compress(data)) # let op: bdata, geen cdata ! tree = ElementTree(rt) copyfile(str(self.fn), str(self.fn) + ".old") tree.write(str(self.fn), encoding='utf-8', xml_declaration=True) self.exists = True ## else: ## return False return found
from xml.etree.ElementTree import ElementTree as ET from svg_util.etree import find, findall from svg_util.css import css_dict, css_string, set_property, get_property from copy import deepcopy tree = ET() tree.parse("./tests/addabove/A.svg") root = tree.getroot() g = find(root, "g") rect = find(root, "g/rect") rect2 = deepcopy(rect) rect2.attrib['id'] = rect.attrib['id'] + "2" rect2.attrib['x'] = str(float(rect.attrib['x']) + float(rect.attrib['width'])) g.append(rect2) tree.write('bla3.svg')
def dump(self, stream): if self.prettyprint: self.indent(self.xml) document = ElementTree(self.xml) document.write(stream, encoding=self.encoding, xml_declaration=True)
def createok(self): self.saveFile = self.createle.text() self.pw = self.le_pass.text() global instance instance = self.saveFile if self.pw != "": if not os.path.exists(self.saveFile): self.savefile_fn = os.path.split(self.saveFile) self.savefile_fnh = self.savefile_fn[0] self.savefile_fnt = self.savefile_fn[1] os.makedirs(self.savefile_fnh + '/_{}'.format(self.savefile_fnt)) self.saveFile = self.savefile_fnh + '/_{}'.format( self.savefile_fnt) instance = self.saveFile subprocess.run([ r'7z\7-Zip\7z.exe', 'a', '-p{}'.format(self.pw), '{}'.format(self.saveFile), '{}'.format(self.saveFile) ], shell=False) root = ET.Element('programElements') tree = ElementTree(root) tree.write(open(self.saveFile + '/config.xml', 'wb')) xml = ET.parse('settings/programSettings.xml') rfp = xml.find('recentfilepath') rfp.text = str(self.saveFile) xml.write(open('settings/programSettings.xml', 'wb')) # might have to make the self.notewin a different name than the one below self.notewin = NotesEditing() self.creatediaglog.close() else: if not os.path.exists(self.saveFile): os.makedirs(self.saveFile) root = ET.Element('programElements') tree = ElementTree(root) tree.write(open(self.saveFile + '/config.xml', 'wb')) xml = ET.parse('settings/programSettings.xml') rfp = xml.find('recentfilepath') rfp.text = str(self.saveFile) xml.write(open('settings/programSettings.xml', 'wb')) self.notewin = NotesEditing() self.creatediaglog.close()
# -*- coding: utf-8 -*- """ 创建xml文件的两种方法 tree= ElementTree.parse("路径") tree = ElementTree.ElementTree(根节点(Element对象)) """ from xml.etree.ElementTree import Element, ElementTree from xml.etree.ElementTree import tostring e = Element('Data') # 创建一个元素 e.set('name', 'abc') # 为元素添加name属性,并指定name属性值为'abc' e.text = '123' # 为元素添加文本内容 print( tostring(e) ) # 将xml转化为字符串文本,但是不含'\n''\t':b'<Data name="abc">123</Data>',导致大文本的xml可读性差 e2 = Element('Row') e3 = Element('Open') e3.text = '8.80' e2.append(e3) # 将e3添加到e2的子元素 e.append(e2) # 将e2添加到e的子元素 print(tostring(e)) et = ElementTree(e) # 生成ElementTree树结构,只需传入根节点即可 et.write('demo02.xml') # 将树结构写文件即可
stdout, stderr = p.communicate() if not stderr: for line in stdout.split("\n"): if "first job" in line: jobid = (line.split(":")[1]).strip(" ") if "job(s)" in line: nJobs = (line.split(" ")[0]).strip(" ") theSub = args.name print theSub print "Found jobid:", jobid print "nJobs: ", nJobs nomvar = "nom" if ("nom" in theSub) else "var" print nomvar jobid_pre = jobid.split("@")[0] print jobid.split("@") builder.start("Sub", {"Name":theSub, "Sample":sample, "Type":"nom"}) for i in range(0,int(nJobs)): jobid_end_num = int(jobid_pre[-1]) + i new_jobid = jobid_pre[0:-1] + str(jobid_end_num) builder.start("Job", {"ID": new_jobid , "N":str(i)}) builder.end("Job") builder.end("Sub") else: print "Error\n", stderr builder.end("Jobs") root = builder.close() rough = tostring(root, 'utf-8') reparsed = xdm.parseString(rough) tree = ElementTree(fromstring(reparsed.toprettyxml(indent=" "))) tree.write(args.o)
def IMUmappings(sensor,trial_dir_path,files, IMUs): #------------------------------------------------------------------------------ #---sensor Xsens--------------------------------------------------------------- if sensor == 'Xsens': DOT_numbers = [0]*len(files) count = 0 for file in files: DOT_numbers[count] = file[10:12] count += 1 #---OpenSimDocument root = Element('OpenSimDocument') root.set('Version','41000') tree = ElementTree(root) #---XsensDataReaderSettings settings = SubElement(root,'XsensDataReaderSettings') #---trial trial_prefix = SubElement(settings,'trial_prefix') trial = '{}'.format(files[0][13:28]) trial_prefix.text = trial #---sensors ExperimentalSensors = SubElement(settings,'ExperimentalSensors') #---identify elements and add to .xml file count = 0 for x in files: ExperimentalSensor = SubElement(ExperimentalSensors,'ExperimentalSensor') ExperimentalSensor.set('name','_Xsens_DOT_{}'.format(DOT_numbers[count])) name_in_model = SubElement(ExperimentalSensor,'name_in_model') name_in_model.text = IMUs[count] + '_imu' count += 1 #--- write file #--- this file needs to be in the same folder as main script tree.write('myIMUmappings.xml') #------------------------------------------------------------------------------ #---sensor Vicon--------------------------------------------------------------- if sensor == 'Vicon': csvfilename_short = [0]*len(files) count = 0 for x in files: TSindex = files[0].index('TS') csvfilename_short[count] = files[count].replace('-','') count += 1 #---OpenSimDocument root = Element('OpenSimDocument') root.set('Version','41000') tree = ElementTree(root) #---XsensDataReaderSettings settings = SubElement(root,'XsensDataReaderSettings') #---trial trial_prefix = SubElement(settings,'trial_prefix') trial = '{}_{}'.format(csvfilename_short[0][TSindex+8:TSindex+16],csvfilename_short[0][TSindex+16:TSindex+22]) trial_prefix.text = trial #---sensors ExperimentalSensors = SubElement(settings,'ExperimentalSensors') #---identify elements and add to .xml file count = 0 for x in files: ExperimentalSensor = SubElement(ExperimentalSensors,'ExperimentalSensor') ExperimentalSensor.set('name','_Vicon_TS_{}'.format(csvfilename_short[count][TSindex+2:TSindex+7])) name_in_model = SubElement(ExperimentalSensor,'name_in_model') name_in_model.text = IMUs[count] + '_imu' count += 1 #--- write file #--- this file needs to be in the parent directory of the directory with IMU data txt files tree.write('myIMUmappings.xml')
#!/usr/bin/env python3 import add_disks from xml.etree.ElementTree import ElementTree, Element from typing import List tree = ElementTree() root = tree.parse("./platform_graphene_s1.xml") for i in range(17, 34): add_disks.add_host(root, '1.25E8Bps', '1.25E8Bps', "1.0E-4s", "16.673E9f", 4, "graphene-" + str(i) + ".nancy.grid5000.fr") header = '''<?xml version='1.0'?> <!DOCTYPE platform SYSTEM "http://simgrid.gforge.inria.fr/simgrid/simgrid.dtd">''' with open("./platform_graphene_s1_full.xml", 'wb') as f: f.write(header.encode('utf8')) tree.write(f, 'utf-8', xml_declaration=False)
def save(self): utils.create_folder_if_not_exists(self.save_folder) classed_image = os.path.join(self.save_folder, "classed_images") utils.create_folder_if_not_exists(classed_image) voc_path = os.path.join(self.save_folder, "voc") utils.create_folder_if_not_exists(voc_path) jpeg_image_path = os.path.join(voc_path, "JPEGImages") utils.create_folder_if_not_exists(jpeg_image_path) annotation_path = os.path.join(voc_path, "Annotations") utils.create_folder_if_not_exists(annotation_path) file_name = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') annotation_xml = Element('annotation') size_xml = SubElement(annotation_xml, 'size') width_xml = SubElement(size_xml, 'width') width_xml.text = str(self.raw_image.size[0]) height_xml = SubElement(size_xml, 'height') height_xml.text = str(self.raw_image.size[1]) depth_xml = SubElement(size_xml, 'depth') depth_xml.text = str(3) for i, label in enumerate(self.labels_listbox.get(0, END)): found = self.canvas.find_withtag(label) label_path = os.path.join(classed_image, label) utils.create_folder_if_not_exists(label_path) for j, found_index in enumerate(found): # Process crop image xmin, ymin, xmax, ymax = self.canvas.bbox(found_index) bbox = (xmin, ymin, xmax, ymax) crop = self.raw_image.crop(bbox) crop_path = os.path.join( label_path, str.format("{0}-{1}[{2}].jpg", label, file_name, j)) # Remove iligeal part xmin = max(xmin, 0) ymin = max(ymin, 0) xmax = min(xmax, self.raw_image.size[0]) ymax = min(ymin, self.raw_image.size[1]) crop.save(crop_path) # Process xml object object_xml = SubElement(annotation_xml, 'object') name_xml = SubElement(object_xml, 'name') name_xml.text = str(label) difficult_xml = SubElement(object_xml, 'difficult') difficult_xml.text = str(0) bndbox_xml = SubElement(object_xml, 'bndbox') xmin_xml = SubElement(bndbox_xml, 'xmin') xmin_xml.text = str(xmin) ymin_xml = SubElement(bndbox_xml, 'ymin') ymin_xml.text = str(ymin) xmax_xml = SubElement(bndbox_xml, 'xmax') xmax_xml.text = str(xmax) ymax_xml = SubElement(bndbox_xml, 'ymax') ymax_xml.text = str(ymax) pass with open( os.path.join(annotation_path, str.format("{0}.xml", file_name)), 'w') as xml: tree = ElementTree(annotation_xml) tree.write(xml, encoding='unicode') self.raw_image.save( os.path.join(jpeg_image_path, str.format("{0}.jpeg", file_name)))
def main(argv): global pricingService global apiKey #Default values - will change these fileIn = '' fileOut = '' groupParts = False pricingService = '' #Which pricing service to use (currently 'F' = FindChips) ##### # COMMENT OUT FOR COMMAND LINE - THIS IS HERE FOR DEVELOPMENT TESTING ONLY ##### # fileIn = '' #replace with filename # groupParts = True # apiKey = '' #Put your API key here # pricingService= 'F' # fileOut = '' #replace with filename ###### ######################################################## #Process the Command Line logger.info('Command Line Arguments: %s', str(argv)) try: opts, args = getopt.getopt( argv, "hgfa:i:o:", ["help", "group", "apikey=", "input=", "output="]) except getopt.GetoptError: printUsage() logger.error('Invalid argument list provided') sys.exit(2) for opt, arg in opts: if opt in ("-i", "--input"): fileIn = arg if opt in ("-o", "--output"): fileOut = arg if opt in ("-a", "--apikey"): apiKey = arg if opt in ("-f", "--findchips"): pricingService = opt if opt in ("-g", "--group"): groupParts = True if opt in ("-h", "--help"): printUsage() #Perform error checking to make sure cmd-line params passed, files exist etc. checkParams(fileIn) #If no output file specified, create one: if fileOut == '': fileOut = fileIn[:fileIn.rfind( '.')] + '_BOM' #strip the extension off the Input file logger.info('No OUTPUT Filename specified - using: %s', fileOut) ######################################################## #Parse and process the XML netlist eTree = ElementTree() eTree.parse(fileIn) root = eTree.getroot() section = root.find( tagComponent) #Find the component-level in the XML Netlist #Loop through each component for component in section: processComponent( listOutput, component, groupParts) #Extract compoonent info and add to listOutput #Get Pricing if we need to. Need a Manufacturer Part No, and a Pricing Service to be specified if fldMfgPartNo in CSVFieldNames and pricingService != '': getPricing(listOutput) ######################################################## #Generate the Output CSV File with open(fileOut + '.csv', 'wb') as fOut: csvWriter = csv.DictWriter(fOut, delimiter=',', fieldnames=CSVFieldNames) csvWriter.writeheader() utf8Output = [] for row in listOutput: utf8Row = {} for key in row: utf8Row[key] = row[key].encode('utf-8') utf8Output.append(utf8Row) csvWriter.writerows(utf8Output) #Print and Log the file creation print('Created CSV File') logger.info('Created CSV file with %i items: %s', len(listOutput), fileOut + '.csv') ######################################################## #Generate the Output XML File parent = Element('schematic') #Create top-level XML element #Loop through each Component and create a child of the XML top-level for listItem in listOutput: child = SubElement(parent, 'component') #Loop through each attribute of the component. # We do it this way, in order to preserve order of elements - more logical output for key in CSVFieldNames: if key in listItem: attribute = SubElement( child, key.replace(' ', '_').replace('&', '_') ) #XML doesn't like spaces in element names, so replace them with "_" attribute.text = listItem[key] #Output to XML file ET = ElementTree(parent) ET.write(fileOut + '.xml') #Print and Log the file creation print('Created XML File') logger.info('Created XML file with %i items: %s', len(listOutput), fileOut + '.xml') #Close the log file - we're done! logging.shutdown()
for tmp_id in no_parent_list: if len(elem_dict[tmp_id]) > 0: root_list.append(tmp_id) else: orphan_list.append(tmp_id) log_file.write('Number of root elements = ' + str(len(root_list)) + '\n') log_file.write('Number of orphan elements = ' + str(len(orphan_list)) + '\n') ####################################################### #output log_file.write('\n\n##############################################\n') ########## #save tree MP_tree = ElementTree(elem_dict[root_list[0]]) MP_tree.write(tree_fname) log_file.write('Tree saved to file: ' + tree_fname + '\n') ############################################# #save attributes (only those in attr_sublist) attr_sublist = ['name', 'def', 'alt_id'] null_str = 'None' attr_out = open(attr_fname, 'w') #write header attr_out.write('#id\t' + '\t'.join(attr_sublist) + '\n') #write attributes for each id for attr_dict in elem_attr.values(): attr_out.write(attr_dict['id'])
node.attrib['id'] = str(-200000 - i) node.attrib['action'] = 'modify' node.attrib['visible'] = 'true' if not fr_csv[i][0] or not fr_csv[i][1]: print("Error: All of lines must have coordinate") fr.close() sys.exit() else: node.attrib['lat'] = fr_csv[i][0] node.attrib['lon'] = fr_csv[i][1] #print(i) for j in range(2, len(keys_to_add)): # add tags if fr_csv[i][j]: tag = SubElement(node, 'tag') tag.attrib['k'] = keys_to_add[j] tag.attrib['v'] = fr_csv[i][j] tree = ElementTree(fw_xml) print("Info: Done building the tree") try: tree.write(osm_file_path, encoding="utf-8", xml_declaration=True) # write except: print("Error: Please delete '" + osm_file_path + "'") fr.close() sys.exit() print("Info: Writed to '" + osm_file_path + "'") fr.close()
def generatePluginInfo(SDK, usrSDKConfig, workDir): """the infomation about Plugin would configure here""" PluginFile = workDir + '/supportPlugin.xml' targetTree = None targetRoot = None pluginLsNode = None # if os.path.exists(PluginFile): # file_operate.delete_file_folder(PluginFile) if not os.path.exists(PluginFile): targetTree = ElementTree() targetRoot = Element('support') targetTree._setroot(targetRoot) else: targetTree = ET.parse(PluginFile) targetRoot = targetTree.getroot() for plugin in SDK['pluginLs']: type = plugin['typePlugin'] typeTag = '<plugin>' if type == 0: typeTag = 'user_plugin' if not usrSDKConfig['type'] & 32: continue elif type == 1: typeTag = 'ads_plugin' if not usrSDKConfig['type'] & 16: continue elif type == 2: typeTag = 'iap_plugin' if not usrSDKConfig['type'] & 8: continue elif type == 3: typeTag = 'social_plugin' if not usrSDKConfig['type'] & 128: continue elif type == 4: typeTag = 'share_plugin' if not usrSDKConfig['type'] & 2: continue elif type == 5: typeTag = 'analytics_plugin' if not usrSDKConfig['type'] & 1: continue elif type == 6: typeTag = 'push_plugin' if not usrSDKConfig['type'] & 64: continue pluginName = plugin['name'] if pluginName is None: file_operate.printf('pluginName error') error_operate.error(109) return 1 pluginLsNode = targetRoot.find(typeTag) if pluginLsNode is not None: for plugin in pluginLsNode.getchildren(): if plugin.text == pluginName: pluginLsNode.remove(plugin) if pluginLsNode is None: pluginLsNode = SubElement(targetRoot, typeTag) paramNode = SubElement(pluginLsNode, 'param') paramNode.text = pluginName paramNode.set('name', pluginName) paramNode.set('pluginName', SDK['SDKName']) paramNode.set('pluginId', SDK['SDKNum']) targetTree.write(PluginFile, 'UTF-8') file_operate.printf('generate supportPlugin.xml success') return 0
class Beauti: def __init__(self, template_file): self.template = Tree() _ = self.template.parse(template_file) def populate(self, fasta, stem, time_unit='days', chain_length=None, screen_step=None, log_step=None, treelog_step=None, root_height=None): """ Load sequences from FASTA object into BEAST XML template :param fasta: a Python list object containing sublists of header/sequence pairs :param stem: file path and prefix to write *.log and *.tree files :param time_unit: used by BEAST for annotation only (e.g., days, years) :param chain_length: optional setting for number of steps in MCMC chain :return: paths to BEAST log and tree log files """ logfile = stem + '.log' treefile = stem + '.trees' # reset TAXA and ALIGNMENT blocks t_taxa = self.template.findall('taxa')[0] t_taxa._children = [] t_aln = self.template.find('alignment') t_aln._children = [] for k, v in fasta.iteritems(): h = v['header'] s = v['sequence'] date_val = float(v['days']) date = Node( 'date', { 'units': time_unit, 'direction': 'forwards', 'value': str(date_val) }) # TAXA taxon = Node('taxon', {'id': h}) taxon.append(date) t_taxa.append(taxon) # SEQUENCE seqtag = Node('sequence', {}) staxon = Node('taxon', {'idref': h}) staxon.tail = '\n\t\t\t' + s.upper( ) # mimic formatting in BEAST XML seqtag.append(staxon) t_aln.append(seqtag) # revise log settings t_mcmc = self.template.find('mcmc') if chain_length: t_mcmc.set('chainLength', str(int(chain_length))) # number of MCMC steps # set prior distribution for rootheight if root_height and type(root_height) is tuple and len( root_height) == 2: lower, upper = root_height assert lower <= upper, 'Root height prior specification lower must be <= upper.' # # set the uniform prior priors = t_mcmc.find('posterior').find('prior').getchildren() found = False for prior in priors: parameter = prior.find('parameter') if parameter is None or parameter.get( 'idref') != 'treeModel.rootHeight': continue found = True prior.set('lower', str(lower)) prior.set('upper', str(upper)) if not found: # TODO: create new element prior = Node('uniformPrior') prior.set('idref', 'treeModel.rootHeight') prior.set('lower', str(lower)) prior.set('upper', str(upper)) # rescale starting tree to be compatible with this prior t_tree = self.template.find('rescaledTree') t_tree.set('height', str(0.1 * (upper - lower) + lower)) for log in t_mcmc.findall('log'): if log.get('id') == 'fileLog': log.set('fileName', logfile) if log_step: log.set('logEvery', str(int(log_step))) elif log.get('id') == 'screenLog': if screen_step: log.set('logEvery', str(int(screen_step))) log_tree_element = t_mcmc.find('logTree') log_tree_element.set('fileName', treefile) if treelog_step: log_tree_element.set('logEvery', str(int(treelog_step))) return logfile, treefile def write(self, handle): self.template.write(handle) def parse_log(self, handle, mod=1): """ Parse contents of a BEAST log file :param handle: an open file handle :return: """ keys = None result = {} count = 0 for line in handle: if line.startswith('#'): # ignore comment line continue if not result: # reached the first non-comment line keys = line.strip('\n').split('\t') result = dict([(key, []) for key in keys]) continue if count % mod == 0: values = line.strip('\n').split('\t') for i, k in enumerate(keys): v = values[i] result[k].append(int(v) if k == 'state' else float(v)) count += 1 return result def parse_treelog(self, handle, sample_size): """ Extract sampled trees from BEAST tree log and convert into Newick tree strings. :param handle: :return: """ # use grep to figure out how many trees are in the file p = subprocess.Popen(['grep', '--count', '-e', '^tree', handle.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() ntrees = int(stdout.strip('\n')) # figure out a modulus to get target sample mod = max(ntrees / sample_size, 1) trBlock = False label_d = {} newicks = [] tree_count = 0 for line in handle: if 'Translate' in line: # entered taxa block trBlock = True continue if trBlock: if ';' in line: # end of block trBlock = False continue index, label = line.strip(',\n').split()[-2:] label_d.update({index: label}) continue # this should follow the Translate block if line.startswith('tree'): tree_count += 1 if tree_count % mod == 0: tree = line.split()[-1].strip(';') # remove figtree annotations tree1 = re.sub('\[[^]]+\]', '', tree) # replace all indices with labels tree2 = re.sub('([0-9]+):', lambda x: label_d[x.groups()[0]] + ':', tree1) newicks.append(tree2) continue return newicks def max_credible(self, newicks): """ Return the maximum clade crediblity tree :param newicks: a list of Newick tree strings :return: """ def get_tips(tree): return tuple( sorted([tip.name for tip in tree.root.get_terminals()])) def get_clades(tree): # recursive function to collect all monophyletic clades of tips result = [get_tips(tree)] for subtree in tree.root: if not subtree.is_terminal(): result.extend(get_clades(subtree)) return result ntrees = len(newicks) counts = {} clades_cache = {} for newick in newicks: handle = StringIO(newick) tree = Phylo.read(handle, 'newick') clades = get_clades(tree) for clade in clades: if clade not in counts: counts.update({clade: 0.}) counts[clade] += 1. / ntrees clades_cache.update({newick: clades}) def credibility(clades, counts): return sum(math.log(counts[clade]) for clade in clades) return max(clades_cache.keys(), key=lambda t: credibility(clades_cache[t], counts))
def make_xml(path): if not os.path.exists(path): root = Element('pictures') tree = ElementTree(root) tree.write(path, encoding="utf-8", xml_declaration=True)
def generateDeveloperInfo(channel, SDK, usrSDKConfig, workDir, game): """the infomation about developer would configure here the value of element's attribute cann't be int """ developerFile = workDir + '/developerInfo.xml' targetTree = None targetRoot = None if not os.path.exists(developerFile): targetTree = ElementTree() targetRoot = Element('developer') targetTree._setroot(targetRoot) else: targetTree = ET.parse(developerFile) targetRoot = targetTree.getroot() infoNode = targetRoot.find('channel') if infoNode is None: infoNode = SubElement(targetRoot, 'channel') channelNum = str(channel.get('customChannelNumber')) if channelNum == '' or channelNum is None: channelNum = str(channel.get('channelNum')) if infoNode.get('idChannel') is None: infoNode.set('idChannel', channelNum) infoNode.set('uApiKey', channel['uapiKey']) infoNode.set('uApiSecret', channel['uapiSecret']) infoNode.set('oauthLoginServer', channel['oauthLoginServer']) infoNode.set('privateKey', game['privateKey']) if channel['extChannel'] is not None: infoNode.set('extChannel', channel['extChannel']) if game.get('order_url') is not None and game['order_url'] != '': infoNode.set('order_url', game['order_url']) if usrSDKConfig['type'] & 8: for plugin in SDK['pluginLs']: type = plugin['typePlugin'] if type == 2: pluginName = plugin['name'] notifyName = pluginName + '_notify_url' notifyValue = '' if usrSDKConfig.get('notify_url') is not None: notifyValue = usrSDKConfig['notify_url'] if notifyValue == '': notifyValue = SDK['orderCallback'] if notifyValue != '': infoNode.set(notifyName, notifyValue) break if channel['r_big_app_id'] is not None: infoNode.set('r_big_app_id', str(channel['r_big_app_id'])) if channel['r_sub_app_id'] is not None: infoNode.set('r_sub_app_id', str(channel['r_sub_app_id'])) if SDK.get('showVersion') is not None: attrName = SDK['SDKName'] + '_Version' infoNode.set(attrName, SDK['showVersion']) for param in usrSDKConfig['param']: if param['bWriteIntoClient'] and not param['bWriteIntoManifest']: paramName = param['name'] pos = paramName.find('##') if pos != -1: paramName = paramName[pos + 2:] infoNode.set(paramName, param['value']) targetTree.write(developerFile, 'UTF-8') file_operate.printf('generate developerInfo.xml success')
from xml.etree.ElementTree import ElementTree tree = ElementTree() tree.parse("example.xml") p = tree.find("body/p") # Finds first occurrence of tag p in body links = p.getiterator("a") # Returns list of all links for i in links: # Iterates through all found links i.attrib["target"] = "blank" tree.write("output.xhtml")
def writeFile(results=None): if results is None : return print("aegawgwerg ",results) root_xml = Element('root') sentence_xml = SubElement(root_xml, 'sentence') variables_xml = SubElement(root_xml, 'variables') variaDic = results.get("variable") if variaDic is not None : #有重复现象 for varia in variaDic: variable = variaDic[varia] key_xml=SubElement(variables_xml,'key') if "indexOfPlace" in variable and "belong" in variable : if variable['indexOfPlace'] is not None and variable['belong'] is not None : key_xml.attrib={'name':variable['word'],'indexOfPlace':str(variable['indexOfPlace']),'belong':variable['belong']} elif variable['indexOfPlace'] is not None : key_xml.attrib={'name':variable['word'],'indexOfPlace':str(variable['indexOfPlace'])} elif variable['belong'] is not None : key_xml.attrib={'name':variable['word'],'belong':variable['belong']} else: key_xml.attrib={'name':variable['word']} elif "indexOfPlace" in variable : if variable['indexOfPlace'] is not None : key_xml.attrib={'name':variable['word'],'indexOfPlace':str(variable['indexOfPlace'])} else: key_xml.attrib={'name':variable['word']} elif "belong" in variable : if variable['belong'] is not None : key_xml.attrib={'name':variable['word'],'belong':variable['belong']} else: key_xml.attrib={'name':variable['word']} else: key_xml.attrib={'name':variable['word']} ref_xml=SubElement(key_xml,'ref') ref_xml.text=variable['ref'] # preposition_xml = SubElement(root_xml, 'preposition') verb_xml = SubElement(root_xml, 'verb') conjunction_xml = SubElement(root_xml,"conjunction") # getTrans() translate_xml = SubElement(root_xml, 'translate') translate_xml.text = "#".join(results['formalSentences']) # translate_xml.text=transRst.strip('\n') # getType() # type_xml = SubElement(root_xml, 'type') # type_xml.text=typeRst.strip('\n') tree = ElementTree(root_xml) sentence = results['rawSentence'] sentence_xml.text = sentence # for prep in prepRst: # tempPrep = SubElement(preposition_xml, prep) # SubElement(tempPrep, 'role').text = prepRst[prep] verbRst = results.get('verb') if verbRst is not None : for verb in verbRst: verb = verbRst[verb] if verb['originVerb'] is None : return False verb_item = SubElement(verb_xml, verb['originVerb']) attrib = {} if "indexOfPlace" in verb and "belong" in verb : if verb['indexOfPlace'] is not None and verb['belong'] is not None : attrib = {'indexOfPlace':str(verb['indexOfPlace']),'belong':verb['belong']} elif verb['indexOfPlace'] is not None : attrib = {'indexOfPlace':str(verb['indexOfPlace'])} elif verb['belong'] is not None : attrib = {'belong':verb['belong']} elif "indexOfPlace" in verb : if verb['indexOfPlace'] is not None : attrib['indexOfPlace'] = str(verb['indexOfPlace']) elif "belong" in verb : if verb['belong'] is not None : attrib['belong'] = verb['belong'] if "isleft" in verb and verb['isleft'] is not None : attrib['isleft'] = str(verb['isleft']) if "isNegative" in verb and verb['isNegative'] is not None : attrib['isNegative'] = str(verb['isNegative']) # print(attrib) verb_item.attrib = attrib # print(verb_item.attrib) source_xml = SubElement(verb_item, 'source') source_xml.text = 'propbank' word_xml = SubElement(verb_item,"wordInSentence") word_xml.text = verb['word'] # num_xml = SubElement(verb_item, 'num') # num_xml.text = re.findall(r'.*\.(.*)', verb_num)[0] if "roles" in verb and verb['roles'] : thema_xml = SubElement(verb_item, 'thematicRoles') i = 0 for r in verb['roles']: argn = SubElement(thema_xml, 'arg' + str(i)) role = SubElement(argn, 'role') role.text = r[0] content = SubElement(argn,'content') content.text = r[1] # descr = SubElement(argn, 'descr') # descr.text = dic['descr'] i += 1 conjunctionRst = results.get("conjunction") if conjunctionRst is not None : for conjunction in conjunctionRst : conjunction = conjunctionRst[conjunction] conjunction_item = SubElement(conjunction_xml, conjunction['word']) if "indexOfPlace" in conjunction and "belong" in conjunction : if conjunction['indexOfPlace'] is not None and conjunction['belong'] is not None : conjunction_item.attrib = {'indexOfPlace':str(conjunction['indexOfPlace']),'belong':conjunction['belong']} elif conjunction['indexOfPlace'] is not None : conjunction_item.attrib = {'indexOfPlace':str(conjunction['indexOfPlace'])} elif conjunction['belong'] is not None : conjunction_item.attrib = {'belong':conjunction['belong']} elif "indexOfPlace" in conjunction : if conjunction['indexOfPlace'] is not None : conjunction_item.attrib = {'indexOfPlace':str(conjunction['indexOfPlace'])} elif "belong" in conjunction : if conjunction['belong'] is not None : conjunction_item.attrib = {'belong':conjunction['belong']} role_xml = SubElement(conjunction_item, 'thematic') role_xml.text = conjunction['role']['role'] # translate_xml.text = transRst.strip('\n') # type_xml.text = typeRst.strip('\n') filename = results['filename'] # f = open('./result/%s.xml' % filename,'a+') tree.write(filename, encoding='utf-8') return True
#!/usr/bin/env python3 from sys import stdin, stdout, argv from xml.etree.ElementTree import ElementTree import xml tree = ElementTree() #xml.etree.ElementTree.register_namespace("","http://www.w3.org/2005/Atom") tree.parse(stdin) if argv[1] == '--whitelist': whitelist = True keywordID = argv[2:] else: whitelist = False keywordID = argv[1:] root = tree.getroot() for channel in tree.findall('channel'): for node in tree.findall('.//item'): ch = node.find('title') if ch is not None: node_matched = False for keyword in keywordID: if ch.text.find(keyword) != -1: node_matched = True break if node_matched ^ whitelist: channel.remove(node) tree.write(stdout, encoding='unicode')
def _save(self, file_name): ''' Save settings into the given file @param file_name: path of file. Format is XML. @param ide_ui: wxPython ctrl of ide @param param_obj: object holding parameters ''' self._file_name = file_name ide_ui = self._ide_ui #@UnusedVariable param_obj = self._param_obj #@UnusedVariable etree = ElementTree(file=file_name) root_element = etree.getroot() attrib_finder = XmlAttribFinder(root_element) for xml_attrib_name, rel_obj_str in self._param_list: # In eval we need ide_ui and param_obj param = ParameterAccess(eval(rel_obj_str)) attrib, attrib_key = attrib_finder.get_obj(xml_attrib_name) attrib[attrib_key] = param.get_related_object_value() # Write XML-File etree.write(file_name) self._changed = False