Exemplo n.º 1
0
    def merge_elements(target: Element, source: Element):
        """ merges the source attributes into the target element and adds an attribute from source
            if it does not exist in the target attribute list

        Arguments:
            target {Element} -- the target element
            source {Element} -- the source element
        """

        # the target-dictionary is dominant

        # merge attributes
        if (target.attrib == None):
            target.attrib = {}
        if (source.attrib == None):
            source.attrib = {}
        td: dict = target.attrib
        sd: dict = source.attrib
        for key, value in sd.items():
            if td.get(key) == None:
                td[key] = value
            else:
                # the key already exists
                pass

        # merge elements
        # todo: recursive merge
        for elem in source.iter():
            target.append(elem)
Exemplo n.º 2
0
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>')
Exemplo n.º 3
0
    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:])
Exemplo n.º 4
0
    def recurse(self, oldnode, newnode):
        """
               recursive function to remove 
            """
        from xml.etree.ElementTree import ElementTree, Element
        try:
            newnode.text = oldnode.text
        except AttributeError:
            pass
        try:
            newnode.attrib = oldnode.attrib
        except AttributeError:
            pass
        try:
            newnode.tail = oldnode.tail
        except AttributeError:
            pass

        for oldi in oldnode.getchildren():
            if oldi.tag != "Inputs" and oldi.tag == "DatasetInfo":
                newi = Element(oldi.tag)
                newtag = Element("Entry")
                newtag.attrib = {'Name': 'Description'}
                newtag.text = 'Unknown provenance'
                newi.append(newtag)
                newnode.append(newi)
                self.recurse(oldi, newi)
            elif oldi.tag != "Inputs" and oldi.tag != "DatasetInfo":
                newi = Element(oldi.tag)
                newnode.append(newi)
                self.recurse(oldi, newi)
def test11():
    top = Element('transactions')
    attributes1 = {'id': '234567'}
    top.attrib = attributes1
    attributes2 = {'id': '2'}
    SubElement(top, 'query', attributes2)
    return prettify(top)
Exemplo n.º 6
0
    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}
Exemplo n.º 7
0
    def recurse(self,oldnode,newnode):
            """
               recursive function to remove 
            """
            from xml.etree.ElementTree import ElementTree, Element
            try: 
                newnode.text = oldnode.text
            except AttributeError: pass
            try: 
                newnode.attrib = oldnode.attrib
            except AttributeError: pass
            try: 
                newnode.tail = oldnode.tail
            except AttributeError: pass

            for oldi in oldnode.getchildren():
                if oldi.tag != "Inputs" and oldi.tag == "DatasetInfo":
                    newi = Element(oldi.tag)
                    newtag = Element("Entry")
                    newtag.attrib = {'Name':'Description'}
                    newtag.text = 'Unknown provenance'
                    newi.append(newtag)
                    newnode.append(newi)
                    self.recurse(oldi, newi)
                elif oldi.tag != "Inputs" and oldi.tag != "DatasetInfo":    
                    newi = Element(oldi.tag)
                    newnode.append(newi)
                    self.recurse(oldi, newi)
def test5():
    top = Element('transactions')
    attributes1 = {'id': '123456'}
    top.attrib = attributes1
    attributes2 = {'sym': 'Test2', 'amount': '5000', 'limit': '1000'}
    SubElement(top, 'order', attributes2)
    return prettify(top)    #err
Exemplo n.º 9
0
def _convertGeoJSONToXML(requestData):
    # for requests for a single country only a single object is returned
    if not isinstance(requestData, list):
        requestData = [requestData]
    elem = Element('Request')
    requestChild = Element('requestName')
    requestChild.text = 'GeoJson'
    elem.append(requestChild)

    dataChild = Element('data')
    countriesElem = Element('countries')

    for country in requestData:
        countryChild = Element('country')
        countryChild.attrib = {'countryname': country['countryname']}
        countriesElem.append(countryChild)

        count = 0
        while count in country:
            pointElem = Element("point")

            latElem = Element('latitude')
            latElem.text = country[count]['latitude']
            pointElem.append(latElem)

            lonElem = Element('longitude')
            lonElem.text = country[count]['longitude']
            pointElem.append(lonElem)

            countryChild.append(pointElem)
            count = count + 1

    dataChild.append(countriesElem)
    elem.append(dataChild)
    return tostring(elem)
Exemplo n.º 10
0
    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:])
Exemplo n.º 11
0
    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:])
Exemplo n.º 12
0
def from_dict(d):
    element = Element(tag=d['#tag'])
    if '#text' in d:
        element.text = d['#text']
    if '@attributes' in d:
        element.attrib = d['@attributes'].copy()
    if '#children' in d:
        element.extend([from_dict(c) for c in d['#children']])
    return element
Exemplo n.º 13
0
    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)
Exemplo n.º 14
0
 def buildMTCStreamsElement(self):
     # Create the MTCStreams element.
     mtcStreams = Element("MTConnectStreams")
     # Add the typical attributes to it.
     mtcStreams.attrib = {"xmlns:m":"urn:mtconnect.org:MTConnectStreams:1.2",
                          "xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",
                          "xmlns":"urn:mtconnect.org:MTConnectStreams:1.2",
                          "xsi:schemaLocation":"urn:mtconnect.org:MTConnectStreams:1.2 http://www.mtconnect.org/schemas/MTConnectStreams_1.2.xsd"
                          }
     return mtcStreams
Exemplo n.º 15
0
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
Exemplo n.º 16
0
    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 test6():
    top = Element('transactions')
    attributes1 = {'id': '98765'}
    top.attrib = attributes1
    attributes2 = {'sym': 'Test2', 'amount': '5000', 'limit': '1000'}
    SubElement(top, 'order', attributes2)
    attributes3 = {'id': '2'}
    SubElement(top, 'query', attributes3)
    attributes4 = {'id': '3'}
    SubElement(top, 'cancel', attributes4)
    return prettify(top)    #err
def transaction_request():
    top=Element('transactions')
    attributes1={'id':str(random.randint(1,10001))}
    top.attrib=attributes1
    attributes2={'sym':randomword(3),'amount':str(random.randint(-10000,10001)),'limit':str(random.randint(1,10001))}
    SubElement(top,'order',attributes2)
    attributes3={'id':str(random.randint(1,10001))}
    SubElement(top,'query',attributes3)
    attributes4={'id':str(random.randint(1,10001))}
    SubElement(top,'cancel',attributes4)
    return prettify(top)
Exemplo n.º 19
0
	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)
Exemplo n.º 20
0
def _convertISSDBKeyToXML(requestData):
    data = []
    # take only 10% of the positions. Goal: less XMLData to send to Frontend, faster drawing of ISS route.
    # lower resolution of ISS route is no problem.
    # take 2 ISSDBKeys (pair of longitude and latitude) and leave 18
    for x in range(0, len(requestData), 20):
        data.append(requestData[x])
        data.append(requestData[x + 1])
    requestData = data
    elem = Element("Request")
    requestChild = Element("requestName")
    requestChild.text = "ISSDB"
    elem.append(requestChild)

    dataChild = Element("data")

    roundChild = Element("round")
    timeValueElem = Element("timeValue")

    longNow = 0
    LongLast = 0

    longindex = 0
    latindex = 0

    for x in range(0, len(requestData), 2):
        timeValueElem.attrib = {"time": requestData[x].timeValue}

        if requestData[x].key == "longitude":
            longindex = x
            latindex = x + 1
        else:
            longindex = x + 1
            latindex = x
        longNow = float(requestData[longindex].value)
        LatElem = Element(requestData[latindex].key)
        LatElem.text = str(requestData[latindex].value)
        LongElem = Element(requestData[longindex].key)
        LongElem.text = requestData[longindex].value
        timeValueElem.append(LatElem)
        timeValueElem.append(LongElem)

        if longNow < LongLast != 0:
            dataChild.append(roundChild)
            roundChild = Element("round")
            test = False
        LongLast = longNow
        roundChild.append(timeValueElem)
        timeValueElem = Element("timeValue")
    dataChild.append(roundChild)
    elem.append(dataChild)
    return tostring(elem)
Exemplo n.º 21
0
def create_new_route(rte, waypoints):

    for waypoint in waypoints:
        # turn the waypoint into a rtept
        rtept = Element(RTEPT_TAG)
        rtept.attrib = waypoint.attrib
        for item in waypoint:
            if item.tag.find("extension") >= 0:
                continue
            rtept.append(item)
        rte.append(rtept)

    return rte
Exemplo n.º 22
0
 def buildStreamHeader(self):
     # Create the Header element.
     header = Element("Header")
     # Add the needed attributes to it.
     header.attrib = {"creationTime":self.header.attributes["creationTime"],
                      "sender":self.header.attributes["sender"],
                      "instanceId":self.header.attributes["instanceId"],
                      "bufferSize":self.header.attributes["bufferSize"],
                      "version":self.header.attributes["version"],
                      "nextSequence":str(self.nextSequenceNumber),
                      "firstSequence":str(self.firstSequenceNumber),
                      "lastSequence":str(self.lastSequenceNumber)
                      }
     return header
Exemplo n.º 23
0
def clean_namespaces(element: ET.Element, parent: ET.Element):
    for child in list(element):
        clean_namespaces(child, element)
    new_attrib = {}
    for attr in element.attrib:
        if -1 == attr.find(':'):
            new_attrib[attr] = element.attrib[attr]
    element.attrib = new_attrib
    if -1 != element.tag.find('}'):
        parts = element.tag.split('}')
        if '{http://www.w3.org/2000/svg' == parts[0]:
            element.tag = parts[1]
        else:
            parent.remove(element)
Exemplo n.º 24
0
 def buildMTCStreamsElement(self):
     # Create the MTCStreams element.
     mtcStreams = Element("MTConnectStreams")
     # Add the typical attributes to it.
     mtcStreams.attrib = {
         "xmlns:m":
         "urn:mtconnect.org:MTConnectStreams:1.2",
         "xmlns:xsi":
         "http://www.w3.org/2001/XMLSchema-instance",
         "xmlns":
         "urn:mtconnect.org:MTConnectStreams:1.2",
         "xsi:schemaLocation":
         "urn:mtconnect.org:MTConnectStreams:1.2 http://www.mtconnect.org/schemas/MTConnectStreams_1.2.xsd"
     }
     return mtcStreams
Exemplo n.º 25
0
def href(link, element=None):
    """Builds an atom:link object for the link."""

    if element == None:
        element = Element("atom:link")

    element.tag = "atom:link"
    element.attrib = {
            "xmlns:atom":"http://www.w3.org/2005/Atom",
            "rel":"alternate",
            "href":link,
            "type":"application/xml",
            }

    return element
Exemplo n.º 26
0
 def buildStreamHeader(self):
     # Create the Header element.
     header = Element("Header")
     # Add the needed attributes to it.
     header.attrib = {
         "creationTime": self.header.attributes["creationTime"],
         "sender": self.header.attributes["sender"],
         "instanceId": self.header.attributes["instanceId"],
         "bufferSize": self.header.attributes["bufferSize"],
         "version": self.header.attributes["version"],
         "nextSequence": str(self.nextSequenceNumber),
         "firstSequence": str(self.firstSequenceNumber),
         "lastSequence": str(self.lastSequenceNumber)
     }
     return header
Exemplo n.º 27
0
 def get_font_element(self):
     font_root_elem = self.root.find('font')
     if font_root_elem is None:
         font_root_elem = self.shared_functions.create_element('font')
         self.root.append(font_root_elem)
     child_font_elem = font_root_elem.find('font')
     if child_font_elem is None:
         child_font_elem = Element('font')
         child_font_elem.attrib = {
             'family': 'Liberation Sans',
             'size': '14',
             'style': 'REGULAR'
         }
         font_root_elem.append(child_font_elem)
     return child_font_elem
Exemplo n.º 28
0
def href(link, element=None):
    """Builds an atom:link object for the link."""

    if element == None:
        element = Element("atom:link")

    element.tag = "atom:link"
    element.attrib = {
        "xmlns:atom": "http://www.w3.org/2005/Atom",
        "rel": "alternate",
        "href": link,
        "type": "application/xml",
    }

    return element
Exemplo n.º 29
0
        def copy(treenode: Node, etnode: etree.Element) -> NoReturn:
            etnode.tag = treenode.tag

            # 如果 value 值为字典则按照键拷贝
            if isinstance(treenode.value, dict):
                etnode.attrib = treenode.value.get(attribute)
                etnode.text = treenode.value.get(text)

            # 如果是单纯的一个值
            else:
                # 如果 value 为 None 则设置为空
                if treenode.value is None:
                    etnode.text = ''
                else:
                    etnode.text = str(treenode.value)
Exemplo n.º 30
0
def generate_xml(file_name, index_num):
    real_name = "result" + file_name + ".xml"
    with open(real_name, "w", encoding="utf-8") as g_file:
        elem = Element("resources")
        for name in index_list:
            child = Element("string")
            attr_dict = {"name": name}
            child.attrib = attr_dict
            try:
                child.text = str(data_dict[index_dict[name]][index_num])
                elem.append(child)
            except Exception as e:
                print(file_name + "翻译,没有" + str(e))

        data = str(tostring(elem), encoding="utf-8")
        g_file.write(html.unescape(data))
Exemplo n.º 31
0
 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:])
Exemplo n.º 32
0
 def __generateXMLElement(self, props: dict, tagname: str) -> Element:
     el = Element(tagname)
     if '_text' in props:
         el.text = props['_text']
     if '_attributes' in props:
         el.attrib = props['_attributes']
     for child_tagname, child_props_or_list in props.items():
         if child_tagname.startswith('_'):
             continue
         if not isinstance(child_props_or_list, list):
             child_props_list = [child_props_or_list]
         else:
             child_props_list = child_props_or_list
         for child_props in child_props_list:
             child_el = self.__generateXMLElement(child_props,
                                                  child_tagname)
             el.append(child_el)
     return el
Exemplo n.º 33
0
    def resource_etree_element(self, resource, element_name='url'):
        """Return xml.etree.ElementTree.Element representing the resource

        Returns and element for the specified resource, of the form <url> 
        with enclosed properties that are based on the sitemap with extensions
        for ResourceSync.
        """
        e = Element(element_name)
        sub = Element('loc')
        sub.text = resource.uri
        e.append(sub)
        if (resource.timestamp is not None):
            lastmod_name = 'lastmod'
            lastmod_attrib = {}
            if (hasattr(resource, 'changetype')
                    and resource.changetype is not None):
                # Not a plain old <lastmod>, use <lastmod> with
                # rs:type attribute or <expires>
                if (resource.changetype == 'CREATED'):
                    lastmod_attrib = {'rs:type': 'created'}
                elif (resource.changetype == 'UPDATED'):
                    lastmod_attrib = {'rs:type': 'updated'}
                elif (resource.changetype == 'DELETED'):
                    lastmod_name = 'expires'
                else:
                    raise Exception(
                        "Unknown change type '%s' for resource %s" %
                        (resource.changetype, resource.uri))
            # Create appriate element for timestamp
            sub = Element(lastmod_name, lastmod_attrib)
            sub.text = str(resource.lastmod)  #W3C Datetime in UTC
            e.append(sub)
        if (resource.size is not None):
            sub = Element('rs:size')
            sub.text = str(resource.size)
            e.append(sub)
        if (resource.md5 is not None):
            sub = Element('rs:fixity')
            sub.attrib = {'type': 'md5'}
            sub.text = str(resource.md5)
            e.append(sub)
        if (self.pretty_xml):
            e.tail = "\n"
        return (e)
Exemplo n.º 34
0
    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:])
Exemplo n.º 35
0
    def resource_etree_element(self, resource, element_name='url'):
        """Return xml.etree.ElementTree.Element representing the resource

        Returns and element for the specified resource, of the form <url> 
        with enclosed properties that are based on the sitemap with extensions
        for ResourceSync.
        """
        e = Element(element_name)
        sub = Element('loc')
        sub.text=resource.uri
        e.append(sub)
        if (resource.timestamp is not None):
            lastmod_name = 'lastmod'
            lastmod_attrib = {}
            if (hasattr(resource,'changetype') and 
                resource.changetype is not None):
                # Not a plain old <lastmod>, use <lastmod> with 
                # rs:type attribute or <expires>
                if (resource.changetype == 'CREATED'):
                    lastmod_attrib = {'rs:type': 'created'}
                elif (resource.changetype == 'UPDATED'):
                    lastmod_attrib = {'rs:type': 'updated'}
                elif (resource.changetype == 'DELETED'):
                    lastmod_name = 'expires'
                else:
                    raise Exception("Unknown change type '%s' for resource %s" % (resource.changetype,resource.uri))
            # Create appriate element for timestamp
            sub = Element(lastmod_name,lastmod_attrib)
            sub.text = str(resource.lastmod) #W3C Datetime in UTC
            e.append(sub)
        if (resource.size is not None):
            sub = Element('rs:size')
            sub.text = str(resource.size)
            e.append(sub)
        if (resource.md5 is not None):
            sub = Element('rs:fixity')
            sub.attrib = {'type':'md5'}
            sub.text = str(resource.md5)
            e.append(sub)
        if (self.pretty_xml):
            e.tail="\n"
        return(e)
Exemplo n.º 36
0
    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}
Exemplo n.º 37
0
def _convertAstrosToXML(requestData):
    elem = Element('Request')
    requestChild = Element("requestName")
    requestChild.text = "AstrosOnISS"
    elem.append(requestChild)
    dataChild = Element("data")
    for astro in requestData:
        AstroChild = Element("Astro")
        AstroChild.attrib = {"name": astro.name}
        picture = Element("picture")
        flag = Element("flag")
        nation = Element("nation")
        picture.text = astro.pic
        flag.text = astro.flag
        nation.text = astro.nation
        AstroChild.append(picture)
        AstroChild.append(flag)
        AstroChild.append(nation)
        dataChild.append(AstroChild)
    elem.append(dataChild)
    return tostring(elem)
Exemplo n.º 38
0
def _convertISSFuturePassesToXML(requestData):
    elem = Element('Request')
    requestChild = Element('requestName')
    requestChild.text = 'ISSfuturePasses'
    elem.append(requestChild)
    dataChild = Element('data')
    timeValueElem = Element('timeValue')

    # create tuples for time values
    for index, r in enumerate(requestData):
        timeElem = Element('time')
        timeElem.attrib = {'index': str(index)}
        passDateElem = Element('futurePassDatetime')
        passDateElem.text = r['futurePassDatetime']
        durationElem = Element('duration')
        durationElem.text = str(r['duration'])

        timeElem.append(passDateElem)
        timeElem.append(durationElem)
        timeValueElem.append(timeElem)

    dataChild.append(timeValueElem)
    elem.append(dataChild)
    return tostring(elem)
Exemplo n.º 39
0
 def toxml(self):
     xliff = Element('xliff')
     xliff.attrib = {'xmlns': self.xmlns, 'xmlns:xsi': self.xmlns_xsi, 'version': self.version,
                     'xsi:schemaLocation': self.xmlns + ' ' + self.xsi_schema_location}
     map(lambda file: file.toxml(xliff), self.files)
     return minidom.parseString(tostring(xliff, 'utf-8')).toprettyxml(indent="    ")
Exemplo n.º 40
0
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)
Exemplo n.º 41
0
    def add_file(self, fp: str) -> None:
        '''
        增加文件到Dicom树
        这是定义Dicom树的核心方法
            因为Dicom树本质上只是具有特定Element和Attribute的xml树,提取和维护哪些属性就决定了DicomTree的定义
        '''
        # TEST
        print(fp)
        '''将.dcm文件索引加入Dicom树'''
        if not fp.endswith('.dcm'):
            return

        dicom_object = pydicom.dcmread(fp)

        metadata_dict = DicomTree.get_necessary_meatadata(dicom_object)

        # 逐级检查标识符,若无则创建,若有则添加到其上
        # 检查是否已有此患者
        patient_id_list = [patient.get('id') for patient in list(self._root)]
        patient_id = metadata_dict['Patient ID']
        if patient_id not in patient_id_list:
            # 构建新的patient元素
            new_patient = Element('patient')
            new_patient.attrib = {
                'id': metadata_dict['Patient ID'],
                'name': metadata_dict['Patient Name']
            }
            # 根据patient id进行排序,将新的patient元素插入合适的位置
            patient_id_list.append(metadata_dict['Patient ID'])
            index = sorted(patient_id_list).index(metadata_dict['Patient ID'])
            self._root.insert(index, new_patient)
            current_patient = new_patient
        else:
            current_patient = list(
                self._root)[patient_id_list.index(patient_id)]

        # 检查是否已有此study,执行操作同上
        study_uid_list = [
            study.get('uid') for study in current_patient.findall('study')
        ]
        study_id_list = [
            study.get('id') for study in current_patient.findall('study')
        ]
        study_uid = metadata_dict['Study UID']
        if study_uid not in study_uid_list:
            new_study = Element('study')
            new_study.attrib = {
                'uid': metadata_dict['Study UID'],
                'id': metadata_dict['Study ID'],
                'date': metadata_dict['Study Date'],
                'time': metadata_dict['Study Time']
            }
            study_id_list.append(metadata_dict['Study ID'])
            index = sorted(study_id_list).index(metadata_dict['Study ID'])
            current_patient.insert(index, new_study)
            current_study = new_study
        else:
            current_study = list(current_patient)[study_uid_list.index(
                study_uid)]

        # 检查是否已有此series,执行操作同上
        series_uid_list = [
            series.get('uid') for series in current_study.findall('series')
        ]
        series_number_list = [
            series.get('number') for series in current_study.findall('series')
        ]
        series_uid = metadata_dict['Series UID']
        if series_uid not in series_uid_list:
            new_series = Element('series')
            new_series.attrib = {
                'uid': metadata_dict['Series UID'],
                'number': metadata_dict['Series Number'],
                'description': metadata_dict['Series Description'],
                'annotated': self.NOT_ANNOTATED,
                # 以时间戳字符串(float转字符串)形式存储时间,便于排序
                # 以time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(timestamp))) 语句进行格式化显示
                'imported_timestamp': str(time.time()),
                'modified_timestamp': ''
            }
            series_number_list.append(metadata_dict['Series Number'])
            index = sorted(series_number_list).index(
                metadata_dict['Series Number'])
            current_study.insert(index, new_series)
            current_series = new_series
        else:
            current_series = list(current_study)[series_uid_list.index(
                series_uid)]
        # 根据标记文件的存在性,在series级上标记序列的被标记状况
        if osp.exists(fp.replace('.dcm', '.pkl')):
            current_series.attrib.update(
                {'annotated': self.SYSTEM_DEFINED_ANNOTATED})

        # 检查是否已有此instance
        instance_uid_list = [
            instance.get('uid')
            for instance in current_series.findall('instance')
        ]
        instance_number_list = [
            instance.get('number')
            for instance in current_series.findall('instance')
        ]
        instance_uid = metadata_dict['Instance UID']

        if instance_uid not in instance_uid_list:
            new_instance = Element('instance')
            new_instance.attrib = {
                'uid': metadata_dict['Instance UID'],
                'number': metadata_dict['Instance Number'],
                'path': fp
            }
            # 根据instance number进行排序
            instance_number_list.append(metadata_dict['Instance Number'])
            index = sorted(instance_number_list).index(
                metadata_dict['Instance Number'])
            current_series.insert(index, new_instance)