def make_joint_xml(self): """ Generate the joint_xml and hold it by self.joint_xml """ joint = Element('joint') joint.attrib = {'name': self.name, 'type': self.type} origin = SubElement(joint, 'origin') origin.attrib = { 'xyz': ' '.join([str(_) for _ in self.xyz]), 'rpy': '0 0 0' } parent = SubElement(joint, 'parent') parent.attrib = {'link': self.parent} child = SubElement(joint, 'child') child.attrib = {'link': self.child} if self.type == 'revolute' or self.type == 'continuous' or self.type == 'prismatic': axis = SubElement(joint, 'axis') axis.attrib = {'xyz': ' '.join([str(_) for _ in self.axis])} if self.type == 'revolute' or self.type == 'prismatic': limit = SubElement(joint, 'limit') limit.attrib = { 'upper': str(self.upper_limit), 'lower': str(self.lower_limit), 'effort': '100', 'velocity': '100' } self.joint_xml = "\n".join(utils.prettify(joint).split("\n")[1:])
def make_transmission_xml(self): """ Generate the tran_xml and hold it by self.tran_xml Notes ----------- mechanicalTransmission: 1 type: transmission interface/SimpleTransmission hardwareInterface: PositionJointInterface """ tran = Element('transmission') tran.attrib = {'name': self.name + '_tran'} joint_type = SubElement(tran, 'type') joint_type.text = 'transmission_interface/SimpleTransmission' joint = SubElement(tran, 'joint') joint.attrib = {'name': self.name} hardwareInterface_joint = SubElement(joint, 'hardwareInterface') hardwareInterface_joint.text = 'PositionJointInterface' actuator = SubElement(tran, 'actuator') actuator.attrib = {'name': self.name + '_actr'} hardwareInterface_actr = SubElement(actuator, 'hardwareInterface') hardwareInterface_actr.text = 'PositionJointInterface' mechanicalReduction = SubElement(actuator, 'mechanicalReduction') mechanicalReduction.text = '1' self.tran_xml = "\n".join(utils.prettify(tran).split("\n")[1:])
def gentstxml(tstlists, setid, srclang, trglang): mteval = Element('mteval') for tstlist in tstlists: sysid = tstlist[0] set = SubElement(mteval, "tstset") set.attrib = { "setid": setid, "srclang": srclang, "trglang": trglang, "sysid": sysid } doc = SubElement(set, "doc") doc.attrib = {"docid": "doc1"} i = 0 for sentence in tstlist: # 第一位存储具体是哪个引擎 if i != 0: p = SubElement(doc, "p") seg = SubElement(p, "seg") seg.attrib = {"id": str(i)} seg.text = sentence i = i + 1 tree = ElementTree(mteval) tree.write(setid + '_tst.xml', encoding='utf-8')
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 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 asset_xml_download(sitename): # select assets to generate trends for, based on form asset_list = [] for asset_id in request.form.getlist('asset_id'): asset = Asset.query.filter_by(id=asset_id).one() asset_list.append(asset) # generate xml # top level objects object_set = Element('ObjectSet') object_set.attrib = { 'ExportMode': 'Standard', 'Version': '1.8.1.87', 'Note': 'TypesFirst' } exported_objects = SubElement(object_set, 'ExportedObjects') # folder object for each asset for asset in asset_list: oi_folder = SubElement(exported_objects, 'OI') oi_folder.attrib = {'NAME': asset.name, 'TYPE': 'system.base.Folder'} # extended trend object for each point for point in asset.points: # generate unique identifier as base64encode(siteID.assetID.pointID) # unique id is used for matching medusa points to webreports logs identifier = 'DONOTMODIFY:' + str( b64encode('{}.{}.{}'.format( asset.site.id, asset.id, point.id).encode('ascii')).decode('ascii')) # create trend log for each point oi_trend = SubElement(oi_folder, 'OI') oi_trend.attrib = { 'NAME': '{} Extended'.format(point.name), 'TYPE': 'trend.ETLog', 'DESCR': identifier } # attribute flag to include in webreports pi = SubElement(oi_trend, 'PI') pi.attrib = {'Name': 'IncludeInReports', 'Value': '1'} # save file out = BytesIO() tree = ElementTree(object_set) # write xml into bytes object tree.write(out, encoding='utf-8', xml_declaration=True) # reset pointer to start of bytes object out.seek(0) # prevent browser from caching the download response = make_response( send_file(out, attachment_filename='Import.xml', as_attachment=True)) response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' return response
def xmlrpc_playlist(): db = conn.cursor() history = [] requests = [] db.execute("SELECT * FROM history ORDER BY id DESC") rows = db.fetchall() for row in rows: i_user = row[2] history.append(get_song(row[1], i_user=i_user)) # Get the request list db.execute("SELECT * FROM requests ORDER BY id DESC") rows = db.fetchall() for row in rows: i_user = row[2] requests.append(get_song(row[0], i_user=i_user)) # Last song in this history list is what's currently playing playing = history.pop() # Create the XML root = Element('playlist') parent = SubElement(root, "nowplaying") child = SubElement(parent, "song") attribs = { 'artist': playing['artist'], 'title': playing['title'], 'requestby': playing['username'] } child.attrib = attribs parent = SubElement(root, "history") for song in history: child = SubElement(parent, "song") attribs = { 'artist': song['artist'], 'title': song['title'], 'requestby': song['username'] } child.attrib = attribs parent = SubElement(root, "upcoming") for song in requests: child = SubElement(parent, "song") attribs = { 'artist': song['artist'], 'title': song['title'], 'requestby': song['username'] } child.attrib = attribs # FIXME: there literally has to be a better way to do this. return parseString(tostring(root)).toprettyxml()
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 write_gazebo_launch(package_name, robot_name, save_dir): """ write gazebo launch file "save_dir/launch/gazebo.launch" Parameter --------- robot_name: str name of the robot save_dir: str path of the repository to save """ try: os.mkdir(save_dir + '/launch') except: pass launch = Element('launch') param = SubElement(launch, 'param') param.attrib = { 'name': 'robot_description', 'command': '$(find xacro)/xacro $(find {})/urdf/{}.xacro'.format( package_name, robot_name) } node = SubElement(launch, 'node') node.attrib = {'name':'spawn_urdf', 'pkg':'gazebo_ros', 'type':'spawn_model',\ 'args':'-param robot_description -urdf -model {}'.format(robot_name)} include_ = SubElement(launch, 'include') include_.attrib = {'file': '$(find gazebo_ros)/launch/empty_world.launch'} number_of_args = 5 args = [None for i in range(number_of_args)] args_name_value_pairs = [['paused', 'true'], ['use_sim_time', 'true'], ['gui', 'true'], ['headless', 'false'], ['debug', 'false']] for i, arg in enumerate(args): arg = SubElement(include_, 'arg') arg.attrib = { 'name': args_name_value_pairs[i][0], 'value': args_name_value_pairs[i][1] } launch_xml = "\n".join(utils.prettify(launch).split("\n")[1:]) file_name = save_dir + '/launch/' + 'gazebo.launch' with open(file_name, mode='w') as f: f.write(launch_xml)
def gen_link_xml(self): """ Generate the link_xml and hold it by self.link_xml """ link = Element('link') link.attrib = {'name': self.name} #inertial inertial = SubElement(link, 'inertial') origin_i = SubElement(inertial, 'origin') origin_i.attrib = { 'xyz': ' '.join([str(_) for _ in self.center_of_mass]), 'rpy': '0 0 0' } mass = SubElement(inertial, 'mass') mass.attrib = {'value': str(self.mass)} inertia = SubElement(inertial, 'inertia') inertia.attrib = \ {'ixx':str(self.inertia_tensor[0]), 'iyy':str(self.inertia_tensor[1]),\ 'izz':str(self.inertia_tensor[2]), 'ixy':str(self.inertia_tensor[3]),\ 'iyz':str(self.inertia_tensor[4]), 'ixz':str(self.inertia_tensor[5])} # visual visual = SubElement(link, 'visual') origin_v = SubElement(visual, 'origin') origin_v.attrib = { 'xyz': ' '.join([str(_) for _ in self.xyz]), 'rpy': '0 0 0' } geometry_v = SubElement(visual, 'geometry') mesh_v = SubElement(geometry_v, 'mesh') mesh_v.attrib = { 'filename': 'package://' + self.repo + self.name + '_m-binary.stl' } material = SubElement(visual, 'material') material.attrib = {'name': 'silver'} color = SubElement(material, 'color') color.attrib = {'rgba': '1 0 0 1'} # collision collision = SubElement(link, 'collision') origin_c = SubElement(collision, 'origin') origin_c.attrib = { 'xyz': ' '.join([str(_) for _ in self.xyz]), 'rpy': '0 0 0' } geometry_c = SubElement(collision, 'geometry') mesh_c = SubElement(geometry_c, 'mesh') mesh_c.attrib = { 'filename': 'package://' + self.repo + self.name + '_m-binary.stl' } # print("\n".join(prettify(link).split("\n")[1:])) self.link_xml = "\n".join(prettify(link).split("\n")[1:])
def get_columnList(node, SubEltroot): ## 指定 一级路径下的 selectlist 防止获取到其他地方 path = 'selectStatement/atomSelectStatement/selectClause/selectList' _selectListElt = node.find(path) selectItemElts = _selectListElt.findall('selectItem') num = 1 for selectItemElt in selectItemElts: columnList = [] ## 获取 所有字段 列表 try: expressions = selectItemElt.find('expression').findall( './/expression') except AttributeError: colAsSElt = SubElement(SubEltroot, 'ColAs') colAsSElt.attrib = {'col_%s' % num: '*'} continue if len(expressions) == 0: column = selectItemElt.findall('.//expression//identifier') columnList = get_columns(column, columnList) else: for exp in expressions: column = exp.findall('.//identifier') columnList = get_columns(column, columnList) columnList = list(set(columnList)) ## 获取 字段别名 try: fieldAlias = selectItemElt.find('identifier').text ## 需要一个排错选项 except AttributeError: fieldAlias = columnList[0].split('.')[-1] colAsSElt = SubElement(SubEltroot, 'ColAs') colAsSElt.attrib = {'col_%s' % num: fieldAlias} for cols in columnList: tmpCol = SubElement(colAsSElt, 'Col') tmpCol.text = cols logicCol = SubElement(colAsSElt, 'logic') get_logic(selectItemElt.find('expression'), logicCol) num += 1
def write_control_launch(robot_name, save_dir, joints_dict): """ write control launch file "save_dir/launch/robot_name_control.launch" Parameter --------- robot_name: str name of the robot save_dir: str path of the repository to save joints_dict: dict information of the joints """ try: os.mkdir(save_dir + '/launch') except: pass launch = Element('launch') controller_name = robot_name + '_controller' rosparam = SubElement(launch, 'rosparam') rosparam.attrib = { 'file': '$(find fusion2urdf)/launch/' + controller_name + '.yaml', 'command': 'load' } controller_args_str = ' '.join([joint + '_position_controller' for joint in joints_dict]) \ + ' joint_state_controller' node_controller = SubElement(launch, 'node') node_controller.attrib = {'name':'controller_spawner', 'pkg':'controller_manager', 'type':'spawner',\ 'respawn':'false', 'output':'screen', 'ns':robot_name,\ 'args':'{}'.format(controller_args_str)} node_publisher = SubElement(launch, 'node') node_publisher.attrib = {'name':'robot_state_publisher', 'pkg':'robot_state_publisher',\ 'type':'robot_state_publisher', 'respawn':'false', 'output':'screen'} remap = SubElement(node_publisher, 'remap') remap.attrib = {'from':'/joint_states',\ 'to':'/' + robot_name + '/joint_states'} launch_xml = "\n".join(prettify(launch).split("\n")[1:]) file_name = save_dir + '/launch/' + robot_name + '_control.launch' with open(file_name, mode='w') as f: f.write(launch_xml)
def xmlrpc_playlist(): db = conn.cursor() history = [ ] requests = [ ] db.execute("SELECT * FROM history ORDER BY id DESC") rows = db.fetchall() for row in rows: i_user = row[2] history.append(get_song(row[1], i_user=i_user)) # Get the request list db.execute("SELECT * FROM requests ORDER BY id DESC") rows = db.fetchall() for row in rows: i_user = row[2] requests.append(get_song(row[0], i_user=i_user)) # Last song in this history list is what's currently playing playing = history.pop() # Create the XML root = Element('playlist') parent = SubElement(root, "nowplaying") child = SubElement(parent, "song") attribs = {'artist': playing['artist'], 'title': playing['title'], 'requestby': playing['username']} child.attrib = attribs parent = SubElement(root, "history") for song in history: child = SubElement(parent, "song") attribs = {'artist': song['artist'], 'title': song['title'], 'requestby': song['username']} child.attrib = attribs parent = SubElement(root, "upcoming") for song in requests: child = SubElement(parent, "song") attribs = {'artist': song['artist'], 'title': song['title'], 'requestby': song['username']} child.attrib = attribs # FIXME: there literally has to be a better way to do this. return parseString(tostring(root)).toprettyxml()
def post_entry(self, title, content, updated=None, draft=False): if updated and isinstance(updated, datetime) is False: raise TypeError('Updated is must be datetime type. Passed updated is {}'.format(type(updated))) entry = Element('entry') entry.attrib = {'xmlns': 'http://purl.org/atom/ns#'} _title = SubElement(entry, 'title') _title.text = title _content = SubElement(entry, 'content') _content.attrib = {'type': 'text/plain'} _content.text = content _updated = SubElement(entry, 'updated') if updated: # default timezone is JST utc_offset = re.sub(r'((?:\+|-)\d{2})(\d{2})', r'\1:\2', updated.strftime('%z')) if updated.tzinfo else '+09:00' _updated.text = updated.strftime('%Y-%m-%dT%H:%M:%S{utc_offset}'.format(utc_offset=utc_offset)) else: _updated.text = None data = minidom.parseString(ET.tostring(entry)).toxml(encoding='utf-8') url = self.draft_collection if draft else self.collection_url response = requests.post(url=url, data=data, auth=self.auth) if response.ok: return ET.fromstring(response.text) else: return {'status_code': response.status_code, 'reason': response.reason}
def mergePopulationData(populationFile, regionFile, mergedFile): csvReader = csv.reader(open(populationFile), delimiter=',', quotechar='"') inhabDict = {} for entry in csvReader: if csvReader.line_num <= 3: continue while(len(entry[0]) < 2): entry[0] = '0' + entry[0] while(len(entry[2]) < 2): entry[2] = '0' + entry[2] while(len(entry[3]) < 4): entry[3] = '0' + entry[3] while(len(entry[4]) < 3): entry[4] = '0' + entry[4] inhabDict["".join(entry[:5])] = str(entry[6]).replace(' ', '') root = ET.ElementTree(file=regionFile).getroot() for parents in root.findall("./*"): for elem in parents.findall("param[7]"): RSValue = str(elem.attrib)[11:23] inhabitants = SubElement(parents, 'param') if RSValue in inhabDict: inhabitants.clear() inhabitants.attrib = { 'key': "INHABITANTS", 'value': inhabDict[RSValue]} outstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ") with open(mergedFile, 'w') as out: out.write(outstr.encode('utf-8'))
def mergePopulationData(populationFile, regionFile, mergedFile): csvReader = csv.reader(open(populationFile), delimiter=',', quotechar='"') inhabDict = {} for entry in csvReader: if csvReader.line_num <= 3: continue while (len(entry[0]) < 2): entry[0] = '0' + entry[0] while (len(entry[2]) < 2): entry[2] = '0' + entry[2] while (len(entry[3]) < 4): entry[3] = '0' + entry[3] while (len(entry[4]) < 3): entry[4] = '0' + entry[4] inhabDict["".join(entry[:5])] = str(entry[6]).replace(' ', '') root = ET.ElementTree(file=regionFile).getroot() for parents in root.findall("./*"): for elem in parents.findall("param[7]"): RSValue = str(elem.attrib)[11:23] inhabitants = SubElement(parents, 'param') if RSValue in inhabDict: inhabitants.clear() inhabitants.attrib = { 'key': "INHABITANTS", 'value': inhabDict[RSValue] } outstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ") with open(mergedFile, 'w') as out: out.write(outstr.encode('utf-8'))
def recurse_tree(xmliter, element=None): sub = None for tag, attrs in xmliter: if isinstance(attrs, list): for attr in attrs: recurse_tree(((tag, attr), ), element) elif element is not None: sub = SubElement(element, tag) else: sub = Element(tag) if isinstance(attrs, (str, int, bool, float)): sub.text = six.text_type(attrs) continue if isinstance(attrs, dict): sub.attrib = { attr: six.text_type(val) for attr, val in attrs.items() if not isinstance(val, (dict, list)) } for tag, val in [ item for item in normalize_iter(attrs) if isinstance(item[1], (dict, list)) ]: recurse_tree(((tag, val), ), sub) return sub
def gensrcxml(senlist, setid, srclang): mteval = Element('mteval') set = SubElement(mteval, "srcset") set.attrib = {"setid": setid, "srclang": srclang} doc = SubElement(set, "doc") doc.attrib = {"docid": "doc1"} i = 1 for sentence in senlist: p = SubElement(doc, "p") seg = SubElement(p, "seg") seg.attrib = {"id": str(i)} seg.text = sentence i += 1 tree = ElementTree(mteval) tree.write(setid + '_src.xml', encoding='utf-8')
def toxml(self, parent): file = SubElement(parent, 'file') file.attrib = {'original': self.original, 'source-language': self.source_language, 'datatype': self.data_type, 'target-language': self.target_language} self.header.toxml(file) self.body.toxml(file) return file
def make_link_xml(self): """ Generate the link_xml and hold it by self.link_xml """ link = Element('link') link.attrib = {'name': self.name} #inertial inertial = SubElement(link, 'inertial') origin_i = SubElement(inertial, 'origin') origin_i.attrib = { 'xyz': ' '.join([str(_) for _ in self.center_of_mass]), 'rpy': '0 0 0' } mass = SubElement(inertial, 'mass') mass.attrib = {'value': str(self.mass)} inertia = SubElement(inertial, 'inertia') inertia.attrib = \ {'ixx':str(self.inertia_tensor[0]), 'iyy':str(self.inertia_tensor[1]),\ 'izz':str(self.inertia_tensor[2]), 'ixy':str(self.inertia_tensor[3]),\ 'iyz':str(self.inertia_tensor[4]), 'ixz':str(self.inertia_tensor[5])} # visual visual = SubElement(link, 'visual') origin_v = SubElement(visual, 'origin') origin_v.attrib = { 'xyz': ' '.join([str(_) for _ in self.xyz]), 'rpy': '0 0 0' } geometry_v = SubElement(visual, 'geometry') mesh_v = SubElement(geometry_v, 'mesh') mesh_v.attrib = { 'filename': 'file://' + "$(find " + self.repo + ")" + self.name + '.stl', 'scale': '0.001 0.001 0.001' } material = SubElement(visual, 'material') material.attrib = {'name': self.material} # collision collision = SubElement(link, 'collision') origin_c = SubElement(collision, 'origin') origin_c.attrib = { 'xyz': ' '.join([str(_) for _ in self.xyz]), 'rpy': '0 0 0' } geometry_c = SubElement(collision, 'geometry') mesh_c = SubElement(geometry_c, 'mesh') mesh_v.attrib = { 'filename': 'file://' + "$(find " + self.repo + ")" + self.name + '.stl', 'scale': '0.001 0.001 0.001' } # print("\n".join(utils.prettify(link).split("\n")[1:])) self.link_xml = "\n".join(utils.prettify(link).split("\n")[1:])
def gen_joint_xml(self): """generate the xml strings of joints """ joint = Element('joint') joint.attrib = {'name':self.name, 'type':self.type} origin = SubElement(joint, 'origin') origin.attrib = {'xyz':' '.join([str(_) for _ in self.xyz]), 'rpy':'0 0 0'} parent = SubElement(joint, 'parent') parent.attrib = {'link':self.parent} child = SubElement(joint, 'child') child.attrib = {'link':self.child} axis = SubElement(joint, 'axis') axis.attrib = {'xyz':' '.join([str(_) for _ in self.axis])} # print("\n".join(prettify(joint).split("\n")[1:])) self.xml = "\n".join(prettify(joint).split("\n")[1:])
def toxml(self, parent): unit = SubElement(parent, 'trans-unit') unit.attrib = {'id': self.trans_unit_id} map(lambda source: source.toxml(unit), self.sources) map(lambda target: target.toxml(unit), self.targets) map(lambda note: note.toxml(unit), self.notes) return unit
def write_control_launch(package_name, robot_name, save_dir, joints_dict): """ write control launch file "save_dir/launch/controller.launch" Parameter --------- robot_name: str name of the robot save_dir: str path of the repository to save joints_dict: dict information of the joints """ try: os.mkdir(save_dir + '/launch') except: pass #launch = Element('launch') controller_name = robot_name + '_controller' #rosparam = SubElement(launch, 'rosparam') #rosparam.attrib = {'file':'$(find {})/launch/controller.yaml'.format(package_name), # 'command':'load'} controller_args_str = "" for j in joints_dict: joint_type = joints_dict[j]['type'] if joint_type != 'fixed': controller_args_str += j + '_position_controller ' controller_args_str += 'joint_state_controller ' node_controller = Element('node') node_controller.attrib = {'name':'controller_spawner', 'pkg':'controller_manager', 'type':'spawner',\ 'respawn':'false', 'output':'screen', 'ns':robot_name,\ 'args':'{}'.format(controller_args_str)} node_publisher = Element('node') node_publisher.attrib = {'name':'robot_state_publisher', 'pkg':'robot_state_publisher',\ 'type':'robot_state_publisher', 'respawn':'false', 'output':'screen'} remap = SubElement(node_publisher, 'remap') remap.attrib = {'from':'/joint_states',\ 'to':'/' + robot_name + '/joint_states'} #launch_xml = "\n".join(utils.prettify(launch).split("\n")[1:]) launch_xml = "\n".join(utils.prettify(node_controller).split("\n")[1:]) launch_xml += "\n".join(utils.prettify(node_publisher).split("\n")[1:]) file_name = save_dir + '/launch/controller.launch' with open(file_name, mode='w') as f: f.write('<launch>\n') f.write('\n') #for some reason ROS is very picky about the attribute ordering, so we'll bitbang this element f.write('<rosparam file="$(find {})/launch/controller.yaml" command="load"/>'.format(package_name)) f.write('\n') f.write(launch_xml) f.write('\n') f.write('</launch>')
def make_link_xml(self): """ Generate the link_xml and hold it by self.link_xml """ link = Element('link') link.attrib = {'name': "$(arg tf_prefix)" + self.name} #inertial inertial = SubElement(link, 'inertial') origin_i = SubElement(inertial, 'origin') origin_i.attrib = {'xyz':' '.join([str(_) for _ in self.center_of_mass]), 'rpy':'0 0 0'} mass = SubElement(inertial, 'mass') mass.attrib = {'value':str(self.mass)} inertia = SubElement(inertial, 'inertia') inertia.attrib = \ {'ixx':str(self.inertia_tensor[0]), 'iyy':str(self.inertia_tensor[1]),\ 'izz':str(self.inertia_tensor[2]), 'ixy':str(self.inertia_tensor[3]),\ 'iyz':str(self.inertia_tensor[4]), 'ixz':str(self.inertia_tensor[5])} # visual for body in self.bodies: visual = SubElement(link, 'visual') origin_v = SubElement(visual, 'origin') origin_v.attrib = {'xyz':' '.join([str(_) for _ in self.xyz]), 'rpy':'0 0 0'} geometry_v = SubElement(visual, 'geometry') mesh_v = SubElement(geometry_v, 'mesh') mesh_v.attrib = {'filename':'package://' + self.repo + self.name + "_" + self.design_name + "_" + body["name"] + "_" + self.name + '.stl','scale':'0.001 0.001 0.001'} material = SubElement(visual, 'material') material.attrib = {'name': body["material"]} color = SubElement(material, 'color') # rviz is not reading the materials properly in melodic so specify color here appearance = self.materials[body["material"]] color.attrib = {'rgba': "{} {} {} {}".format(appearance[1]/255, appearance[2]/255, appearance[3]/255, appearance[4]/255)} # collision collision = SubElement(link, 'collision') origin_c = SubElement(collision, 'origin') origin_c.attrib = {'xyz':' '.join([str(_) for _ in self.xyz]), 'rpy':'0 0 0'} geometry_c = SubElement(collision, 'geometry') mesh_c = SubElement(geometry_c, 'mesh') mesh_c.attrib = {'filename':'package://' + self.repo + self.name + '.stl','scale':'0.001 0.001 0.001'} # print("\n".join(utils.prettify(link).split("\n")[1:])) self.link_xml = "\n".join(utils.prettify(link).split("\n")[1:])
def write_gazebo_xacro(joints_dict, links_xyz_dict, inertial_dict, package_name, robot_name, save_dir): try: os.mkdir(save_dir + '/urdf') except: pass file_name = save_dir + '/urdf/' + robot_name + '.gazebo' # the name of urdf file repo = robot_name + '/meshes/' # the repository of binary stl files #repo = package_name + '/' + robot_name + '/bin_stl/' # the repository of binary stl files with open(file_name, mode='w') as f: f.write('<?xml version="1.0" ?>\n') f.write( '<robot name="{}" xmlns:xacro="http://www.ros.org/wiki/xacro" >\n'. format(robot_name)) f.write('\n') f.write('<xacro:property name="body_color" value="Gazebo/Silver" />\n') f.write('\n') gazebo = Element('gazebo') plugin = SubElement(gazebo, 'plugin') plugin.attrib = { 'name': 'control', 'filename': 'libgazebo_ros_control.so' } gazebo_xml = "\n".join(utils.prettify(gazebo).split("\n")[1:]) f.write(gazebo_xml) # for base_link f.write('<gazebo reference="base_link">\n') f.write(' <material>${body_color}</material>\n') f.write(' <mu1>0.2</mu1>\n') f.write(' <mu2>0.2</mu2>\n') f.write(' <selfCollide>true</selfCollide>\n') f.write(' <gravity>true</gravity>\n') f.write('</gazebo>\n') f.write('\n') # others for joint in joints_dict: name = joints_dict[joint]['child'] f.write('<gazebo reference="{}">\n'.format(name)) f.write(' <material>${body_color}</material>\n') f.write(' <mu1>0.2</mu1>\n') f.write(' <mu2>0.2</mu2>\n') f.write(' <selfCollide>true</selfCollide>\n') f.write('</gazebo>\n') f.write('\n') f.write('</robot>\n')
def write_display_launch(package_name, robot_name, save_dir): """ write display launch file "save_dir/launch/display.launch" Parameter --------- robot_name: str name of the robot save_dir: str path of the repository to save """ try: os.mkdir(save_dir + '/launch') except: pass launch = Element('launch') arg1 = SubElement(launch, 'arg') arg1.attrib = {'name':'model', 'default':'$(find {})/urdf/{}.xacro'.format(package_name, robot_name)} arg2 = SubElement(launch, 'arg') arg2.attrib = {'name':'gui', 'default':'true'} arg3 = SubElement(launch, 'arg') arg3.attrib = {'name':'rvizconfig', 'default':'$(find {})/launch/urdf.rviz'.format(package_name)} param1 = SubElement(launch, 'param') param1.attrib = {'name':'robot_description', 'command':'$(find xacro)/xacro $(arg model)'} param2 = SubElement(launch, 'param') param2.attrib = {'name':'use_gui', 'value':'$(arg gui)'} node1 = SubElement(launch, 'node') node1.attrib = {'name':'joint_state_publisher', 'pkg':'joint_state_publisher', 'type':'joint_state_publisher'} node2 = SubElement(launch, 'node') node2.attrib = {'name':'robot_state_publisher', 'pkg':'robot_state_publisher', 'type':'robot_state_publisher'} node3 = SubElement(launch, 'node') node3.attrib = {'name':'rviz', 'pkg':'rviz', 'args':'-d $(arg rvizconfig)', 'type':'rviz', 'required':'true'} launch_xml = "\n".join(utils.prettify(launch).split("\n")[1:]) file_name = save_dir + '/launch/display.launch' with open(file_name, mode='w') as f: f.write(launch_xml)
def createXMLElement(self, parent): '''generates an XML element that represents the given Cell''' element = SubElement(parent, "Cell") element.attrib = { "rX": str(self.rect.x), "rY": str(self.rect.y), "rW": str(self.rect.w), "rH": str(self.rect.h), "X": str(self.xLoc), "Y": str(self.yLoc), "isFlagged": str(self.isFlagged), "isVisible": str(self.isVisible), "isBomb": str(self.isBomb), "value": str(self.value) }
def edit_entry(self, date, entry_id, title, content, updated=None, draft=False): entry = Element('entry') entry.attrib = {'xmlns': 'http://purl.org/atom/ns#'} _title = SubElement(entry, 'title') _title.text = title _content = SubElement(entry, 'content') _content.attrib = {'type': 'text/plain'} _content.text = content _updated = SubElement(entry, 'updated') _updated.text = updated data = minidom.parseString(ET.tostring(entry)).toxml(encoding='utf-8') url = self.draft_member.format(entry_id=entry_id) if draft else self.member_url.format(date=date, entry_id=entry_id) response = requests.put(url=url, data=data, auth=self.auth) if response.ok: return ET.fromstring(response.text) else: return {'status_code': response.status_code, 'reason': response.reason}
def visit_node(node_name: str, path: str, parent: Union[Element, None], xml_root: Element, saved_root: Element): if parent is None: node = xml_root else: node = SubElement(parent, node_name) # type: Element xnode = XNode(node_name, path, parent, xml_root, saved_root) # Get and add attributes node.attrib = xnode.get_attributes() # Get and add text value node.text = xnode.get_node_text() # Get children child_names = xnode.get_child_node_names() # Do last for child_name, child_path in child_names: visit_node(node_name=child_name, path=child_path, parent=node, xml_root=xml_root, saved_root=saved_root)
def submit(self, data): top = Element('xml') # Creating XML document ezled = SubElement(top, 'LED_info_Easy') ezled.attrib = data submit_data = tostring(top) # Headers from original android app headers = { "User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)", "Content-Type": "multipart/form-data;boundary=*****", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip" } r = post(url=self.url, params={"Get_Type": 0}, headers=headers, data=submit_data) if "Upload OK!" in r.text: return True else: return False
def write_gazebo_plugin_and_endtag(file_name): """ Write about gazebo_plugin and the </robot> tag at the end of the urdf Parameters ---------- file_name: str urdf full path """ with open(file_name, mode='a') as f: # gazebo plugin gazebo = Element('gazebo') plugin = SubElement(gazebo, 'plugin') plugin.attrib = { 'name': 'control', 'filename': 'libgazebo_ros_control.so' } gazebo_xml = "\n".join(prettify(gazebo).split("\n")[1:]) f.write(gazebo_xml) f.write('</robot>\n')
def new_agvinfo_xml(agvinfo, path): root = Element('agv_info') agvsEle = SubElement(root, 'agvs') updateTree = xml.etree.ElementTree.ElementTree(root) #updateTree=ElementTree(root) head = SubElement(agvsEle, 'agv') head.attrib = { "id": str(agvinfo.vhid), "type": str(agvinfo.vhtype), 'ip': str(agvinfo.inet), 'mac_addr': str(agvinfo.hwaddr), 'port': str(agvinfo.mtport), 'shell_port': str(agvinfo.shport), 'fts_port': str(agvinfo.ftsport), 'status': str(agvinfo.status) } for i in range(len(agvinfo.attrs)): head.attrib[agvinfo.attrs[i].name] = str(agvinfo.attrs[i].describe) updateTree.write(path)
def _to_xml(self, parent=None, excludes=[]): """ Serialize document to xml """ if parent is not None: root = SubElement(parent, self._tagname) else: root = Element(self._tagname) for name, field in sorted(self._fields.items()): if name in self.xml_exclude or name in excludes: continue value = getattr(self, name) if value is None: # skip not filled fields continue attribs = dict() if isinstance(field, IntField) and name is not 'id': attribs['type'] = 'integer' if isinstance(field, PyDateTimeField): attribs['type'] = 'datetime' value = value.strftime('%Y/%m/%d %H:%M:%S %Z') if isinstance(field, PyBooleanField): attribs['type'] = 'boolean' value = str(value).lower() if isinstance(field, EmbeddedDocumentField): value._to_xml(root) else: elem = SubElement(root, name) elem.text = str(value) elem.attrib = attribs # allow sub classes to add custom ad-hoc fields self._contribute_to_xml(root) return tostring(root)
# import yaml # from pprint import pprint as pp # # data_set = yaml.safe_load(open('tmp.yaml')) # pp(data_set) """ <directories> <directory name='/tmp'> <file size="124" mtime="12 Mon Sep 19">file_name</file> <dir size="124" mtime="12 Mon Sep 19">dir_name</dir> </directory> </directories> """ "http://collabedit.com/vqkeg" from xml.etree.ElementTree import Element, SubElement, ElementTree root_tag = Element('directories') directory_tag = SubElement(root_tag, 'directory') directory_tag.set('name', '/tmp') file_tag = SubElement(directory_tag, 'file') file_tag.text = 'ansible' # adding text node to the tag file_tag.attrib = dict(size="124", mtime="12 Mon Sep 19") ElementTree(root_tag).write('tmp.xml')
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
def toxml(self, parent): tool = SubElement(parent, 'tool') tool.attrib = {'tool-id': self.tool_id, 'tool-name': self.tool_name, 'tool-version': self.tool_version, 'build-num': self.build_num} return tool
def _contribute_to_xml(self, etree): if getattr(self, "no_owner", False): elem = SubElement(etree, "no_owner") elem.text = str(True).lower() elem.attrib = {'type': 'boolean'}
def get_vulnerability(filename="", run_time=10): tree = ET.parse(filename) root = tree.getroot() issues = [] preferences = root.findall( "Policy/Preferences/ServerPreferences/preference") for preference in preferences: result = {} for node in preference: result[node.tag] = node.text if result["name"] == "plugin_set": plugin_set = result["value"] number_tests = len(plugin_set.split(";")) severity_match = {0: "S4", 1: "S3", 2: "S2", 3: "S1", 4: "S0"} testsuites = Element("testsuites") number_issues = 0 for elem in root.findall("Report/ReportHost"): # need to get host name or IP address host = elem.attrib["name"] testsuite = SubElement(testsuites, "testsuite") for issue in elem.findall("ReportItem"): number_issues = number_issues + 1 testcase = SubElement(testsuite, "testcase") attribs = issue.attrib failure = SubElement(testcase, "failure") description = "" synopsis = "" plugin_output = "" see_also = "" solution = "" fname = "" plugin_type = "" plugin_publication_date = "" plugin_modification_date = "" plugin_name = "" fname = "" script_version = "" risk_factor = "" for atom in issue: if atom.tag == "description": description = atom.text elif atom.tag == "synopsis": synopsis = atom.text elif atom.tag == "plugin_output": plugin_output = atom.text elif atom.tag == "see_also": see_also = atom.text elif atom.tag == "solution": solution = atom.text elif atom.tag == "fname": fname = atom.text elif atom.tag == "plugin_modification_date": plugin_modification_date = atom.text elif atom.tag == "plugin_name": plugin_name = atom.text elif atom.tag == "plugin_type": plugin_type = atom.text elif atom.tag == "risk_factor": risk_factor = atom.text elif atom.tag == "script_version": script_version = atom.text testcase_attribs = {} sev_level = int(attribs["severity"]) testcase_attribs["severity"] = severity_match[sev_level] testcase_attribs["name"] = attribs["pluginName"] testcase_attribs["pluginID"] = attribs["pluginID"] testcase_attribs["pluginName"] = attribs["pluginName"] testcase_attribs["classname"] = attribs["pluginID"] testcase.attrib = testcase_attribs failure.text = u"""Host:{} Description:{} Severity:{} Fname:{} Plugin_modification_date:{} Plugin_name:{} Plugin_publication_date:{} Plugin_type:{} Risk_factor:{} Script_version:{} See Also:{} Solution:{} Synopsis:{} Plugin_output:{} """.format( host, description, testcase_attribs["severity"], fname, plugin_modification_date, plugin_name, plugin_publication_date, plugin_type, risk_factor, script_version, see_also, solution, synopsis, plugin_output) issues.append(issue) testsuites_attribs = {} testsuites_attribs["failures"] = str(number_issues) testsuites_attribs["errors"] = "0" testsuites_attribs["name"] = "name" testsuites_attribs["skips"] = "0" testsuites_attribs["tests"] = str(number_tests) testsuites_attribs["host"] = host testsuites_attribs["time"] = str(run_time) testsuites.attrib = testsuites_attribs return tostring(testsuites)
from xml.etree.ElementTree import Element, SubElement, ElementTree root_tag = Element('directories') dir_tag = SubElement(root_tag, 'directory') dir_tag.set('name', r'c:\users\madduv\Desktop') file_tag = SubElement(dir_tag, 'file') file_tag.attrib = dict(size='308160', mtime='Sun Dec 11 11:11:11: 2017') file_tag.text = 'instance.xls' doc_tree = ElementTree(root_tag) doc_tree.write('tmp.xml')
from xml.etree.ElementTree import Element, SubElement, ElementTree root_tag = Element('directories') # root tag dir_tag = SubElement(root_tag, 'directory') # child tag # dir_tag.set('name', '/tmp') # setting an attribute dir_tag.attrib = {'name': '/tmp'} file_tag = SubElement(dir_tag, 'file') file_tag.text = 'Eureka Forbes.pdf' # text node file_tag.attrib = dict(size="1243", mtime='Sun Dec 11 22:29:41 2016') ElementTree(root_tag).write('tmp.xml', xml_declaration=True) # doc object