示例#1
0
def get_yahoo_player_audio_url(row, arrow=True, albumcover=False):
    #gets url to track with album image if album image exists
    #if arrow is true, arrow icon is shown on page
    #if album cover is true, album cover is shown on page
    try:
        if not arrow:
            link = ET.Element('a',
                              style='display:none',
                              title="%s - %s (%s)" %
                              (row.artist, row.title, row.album),
                              href='/mp3/T%s.mp3' % str(row.id))
        else:
            link = ET.Element('a',
                              title="%s - %s (%s)" %
                              (row.artist, row.title, row.album),
                              href='/mp3/T%s.mp3' % str(row.id))
        #don't show text for this
        link.text = ''
        #now add the album cover
        if len(row.albums) > 0:  #atand row.albums.count()>0 :
            albumcover_url = get_albumcover_urltxt(row.albums[0])
            if len(albumcover_url) <> '':
                link_img = ET.SubElement(link,
                                         'img',
                                         align='right',
                                         style='display:none',
                                         src=albumcover_url)
    except:
        link = ''

    return link
示例#2
0
 def set_drillhole_data(self, element, data_list):
     """set data in list as drillhole data (i.e. delete all
     existing Row elements and create new ones);
     element should
     be one of the drillhole file elements, i.e.
     self.drillholes["survey"], self.drillholes["collar"]
     or self.drillholes["geology"]
     list should be on correct format"""
     results = element.find("{"+self.xmlns+"}Result")
     rows = results.findall("{"+self.xmlns+"}Row")
     for row in rows:
         results.remove(row)
     # data = []
     if element.tag == "{"+self.xmlns+"}GeologyTable":
         for l in data_list:
             elem = ET.Element("{"+self.xmlns+"}Row")
             # turn list into string
             text = '"%s","%s","%s","%s"' % (l[0], l[1], l[2], l[3])
             elem.text = text
             results.append(elem)
     if element.tag == "{"+self.xmlns+"}CollarTable":
         for l in data_list:
             elem = ET.Element("{"+self.xmlns+"}Row")
             # turn list into string
             text = '"%s","%s","%s","%s","%s"' % (l[0], l[1], l[2], l[3], l[4])
             elem.text = text
             results.append(elem)
     if element.tag == "{"+self.xmlns+"}SurveyTable":
         for l in data_list:
             elem = ET.Element("{"+self.xmlns+"}Row")
             # turn list into string
             text = '"%s","%s","%s","%s"' % (l[0], l[1], l[2], l[3])
             elem.text = text
             results.append(elem)
     return True
示例#3
0
    def add_comp_elem(self, comp, hostaddr, execpath, sorder, hostport="50000"):
        compel = xml.Element('component')
        compel.attrib['cid'] = comp.name + '0'

        self.add_elem_text(compel, "hostAddr", hostaddr)
        self.add_elem_text(compel, "hostPort", hostport)
        instname = comp.name + "0" + "." + "rtc"
        self.add_elem_text(compel, "instName", instname)
        self.add_elem_text(compel, "execPath", execpath)
        self.add_elem_text(compel, "confFile", "/tmp/daqmw/rtc.conf")
        self.add_elem_text(compel, "startOrd", sorder)
        inps = xml.Element("inPorts")
        outps = xml.Element("outPorts")
        params = xml.Element("params")

        for index in range(len(comp.outp)):
            self.add_elem_text(outps, "outPort", comp.outp[index])

        for index in range(len(comp.inp)):
            self.add_elem_attr(inps, "inPort", comp.inp[index], "from",
                               comp.ofrom[index])

        for index in range(len(comp.params)):
            self.add_elem_attr(params, "param", comp.params[index][1], "pid",
                               comp.params[index][0])

        compel.append(inps)
        compel.append(outps)
        compel.append(params)

        self.cps.append(compel)
示例#4
0
def process_rel_href(tree):
    parent = get_parent_map(tree)
    for a in tree.findall('.//a'):
        m = re.match(r'(bold)?rel\:(.+)', a.get('href'))
        if m:
            (bold, path) = m.group(1, 2)
            text = a.text
            if text == path:
                tag = et.Element("MAKO:nav.toclink",
                                 path=repr(path),
                                 extension='extension',
                                 paged='paged',
                                 toc='toc')
            else:
                tag = et.Element("MAKO:nav.toclink",
                                 path=repr(path),
                                 description=repr(text),
                                 extension='extension',
                                 paged='paged',
                                 toc='toc')
            a_parent = parent[a]
            if bold:
                bold = et.Element('strong')
                bold.tail = a.tail
                bold.append(tag)
                a_parent[index(a_parent, a)] = bold
            else:
                tag.tail = a.tail
                a_parent[index(a_parent, a)] = tag
    def makeSubtree(self, index, table):
        termnodes = []
        for identifier in index.keys():
            termnode = ElementTree.Element('term')
            identifiernode = ElementTree.Element('termIdentifier')
            identifiernode.text = str(identifier)
            captionnode = ElementTree.Element('caption')

            translations = table[identifier].items()
            translations.sort(key=lambda (language, langstring): language)

            for (language, langstring) in translations:
                langstringnode = ElementTree.Element('langstring')
                langstringnode.text = langstring
                langstringnode.attrib[
                    'language'] = language or self.taxonomy.default_language or ''
                captionnode.append(langstringnode)

            termnode.append(identifiernode)
            termnode.append(captionnode)

            for nestedtermnode in self.makeSubtree(index[identifier], table):
                termnode.append(nestedtermnode)

            # add to list
            termnodes.append(termnode)

        return termnodes
    def __call__(self, as_string=False):
        taxonomy = self.taxonomy

        attrib = self.IMSVDEX_ATTRIBS
        attrib['language'] = taxonomy.default_language or ''

        root = ElementTree.Element('vdex', attrib=attrib)

        vocabName = ElementTree.Element('vocabName')
        root.append(vocabName)

        langstring = ElementTree.Element(
            'langstring', attrib={'language': taxonomy.default_language or ''})
        langstring.text = taxonomy.title
        vocabName.append(langstring)

        vocabIdentifier = ElementTree.Element('vocabIdentifier')
        vocabIdentifier.text = self.taxonomy.name.replace(
            'collective.taxonomy.', '')
        root.append(vocabIdentifier)

        root = self.buildTree(root)

        if as_string:
            indent(root)
            treestring = ElementTree.tostring(root, self.IMSVDEX_ENCODING)
            header = """<?xml version="1.0" encoding="%s"?>""" % \
                     self.IMSVDEX_ENCODING.upper() + '\n'
            treestring = header + treestring
            return treestring
        else:
            return root
    def damage(self, ref, amount):
        self.rounds[-1].append(ET.Element("damage"))
        damagexml = self.rounds[-1][-1]

        damagexml.append(ET.Element("reference", ref=ref))
        damagexml.append(ET.Element("amount"))
        amountxml = damagexml[-1]
        amountxml.text = str(amount)
示例#8
0
    def makeHistoryFile(self, service):
	root = ET.Element('history')
	child = ET.Element(service)
	root.append(child)   
	for i in range(5):
	    item = ET.Element('search')
	    child.append(item)
	self.writeHistoryFile(root)
示例#9
0
    def __init__(self):
        self.root = xml.Element('configInfo')

        self.op = xml.Element('daqOperator')
        self.root.append(self.op)
        self.dgs = xml.Element('daqGroups')
        self.root.append(self.dgs)
        dg = xml.Element('daqGroup')
        dg.attrib["gid"] = "group0"
        self.dgs.append(dg)

        self.cps = xml.Element('components')
        dg.append(self.cps)
示例#10
0
def get_albumcover(row, clickable=False, sz=120):
    url = get_albumcover_urltxt(row)
    if len(url) == 0:
        return ''

    if clickable:
        link = ET.Element('a', href='/album/%s' % row.id)
        link_img = ET.SubElement(link, 'img', src=url)
        link_img.set('width', '%i' % sz)
        link_img.set('border', '0')
    else:
        link = ET.Element('img', src=url)
        link.set('width', '%i' % sz)

    return link
    def init(self, side):
        self.sides.append(ET.Element("side", id=side.owner))
        sidexml = self.sides[-1]

        for type, amount in enumerate(side.ships.combine()):
            for index in range(0, amount):
                entityid = side.name(type, index)

                sidexml.append(ET.Element("entity", id=entityid))
                entityxml = sidexml[-1]

                namexml = ET.SubElement(entityxml, "name")
                namexml.text = entityid

                typexml = ET.SubElement(entityxml, "type")
                typexml.text = side.ships.names[type]
示例#12
0
def xldf_addSection(localpath,cmd,tree):
 success = False
 s = cmd.findall('*')[0]
 if s.tag in ('definitions','abbreviations','languageOverview'):
  if tree.findall('//lists'):
   tree.findall('//lists')[0].append(s)
  else:
   el = ET.Element('lists',{})
   el.append(s)
   for i in range(0,len(tree.findall('*'))):
    if tree.getroot()[i].tag=='frontMatter':
     tree.getroot().insert(i+1,el)
  print '[XLDF] add-section to lists'
  success = True
 elif s.tag in ('lineContinuations','whitespace','tokens','preprocessor','literals','lexical'):
  tree.findall('//lexicalPart')[0].append(s)
  print '[XLDF] add-section to lexical part'
  success = True
 elif s.tag in ('core','annex'):
  tree.findall('part')[0].append(s)
  print '[XLDF] add-section to the',s.tag
  success = True
 elif s.tag == 'placeholder':
  tree.getroot().insert(1,s)
  print '[XLDF] add-section to placeholders'
  success = True
 if not success:
  print '[----] xldf:add-section failed, double check or try add-subsection instead'
 return
示例#13
0
def get_album_sim_url(row):
    if row and row.other:
        link = ET.Element('a', href='/album/%s' % row.id)
        link.text = row.other.name
    else:
        link = ''
    return link
示例#14
0
def get_artist_sim_url(row):
    try:
        link = ET.Element('a', href='/artist/%s' % row.id)
        link.text = row.other.name
    except:
        link = ''
    return link
示例#15
0
 def __get__(self, document, owner):
     if document is None:
         return self
         
     if hasattr(document, '_element'):
         return document._element
     
     nodes = {}
     root = None
     for node in document._nodes:
         if node.parent_id is not None:
             parent = nodes[node.parent_id]
             elem = ElementTree.SubElement(parent, node.tag)
             nodes[node.element_id] = elem
         else:
             parent = None
             elem = root = ElementTree.Element(node.tag)
             nodes[node.element_id] = root
         for attr in node.attributes:
             elem.attrib[attr.name] = attr.value
         elem.text = node.text
         elem.tail = node.tail
         
     document._element = ElementTree.ElementTree(root)
     return document._element
示例#16
0
文件: BGF.py 项目: siwiwit/slps
 def getXml(self):
     #print 'Getting the XML of selectable',self.sel,'...'
     self.ex = ET.Element(slpsns.bgf_('expression'))
     self.xml = ET.SubElement(self.ex, 'seplistplus')
     self.xml.append(self.item.getXml())
     self.xml.append(self.sep.getXml())
     return self.ex
示例#17
0
def exportTopicTreeSpecXml(moduleName=None,
                           rootTopic=None,
                           bak='bak',
                           moduleDoc=None):
    """
    If rootTopic is None, then pub.getDefaultTopicTreeRoot() is assumed.
    """

    if rootTopic is None:
        from .. import pub
        rootTopic = pub.getDefaultTopicTreeRoot()
    elif py2and3.isstring(rootTopic):
        from .. import pub
        rootTopic = pub.getTopic(rootTopic)

    tree = ET.Element('topicdefntree')
    if moduleDoc:
        mod_desc = ET.SubElement(tree, 'description')
        mod_desc.text = ' '.join(moduleDoc.split())

    traverser = pub.TopicTreeTraverser(XmlVisitor(tree))
    traverser.traverse(rootTopic)

    indent(tree)

    if moduleName:

        filename = '%s.xml' % moduleName
        if bak:
            pub._backupIfExists(filename, bak)

        fulltree = ET.ElementTree(tree)
        fulltree.write(filename, "utf-8", True)

    return ET.tostring(tree)
示例#18
0
文件: ldfwriter.py 项目: siwiwit/slps
	def __init__(self):
		# requires preceding slpsns.init(ET)
		self._dtree = ET.Element('ldf:document')
		self._dtree.set('xmlns:ldf',slpsns.ldfns)
		self._dtree.set('xmlns:bgf',slpsns.bgfns)
		self._dtree.set('xmlns:html',slpsns.htmlns)
		return
示例#19
0
    def generate_xml(self, xml_out):
        id = 1
        root = ET.Element("comentarios")
        if self.__type:
            for i in self.__vector_tagged_comments:
                if i[0] != "None":
                    comentario = ET.SubElement(root, "comentario")
                    id_comentario = ET.SubElement(comentario, "id")
                    id_comentario.text = str(id)
                    texto = ET.SubElement(comentario, "contenido")
                    texto.text = i[0]
                    polaridad = ET.SubElement(comentario, "polaridad")
                    polaridad.text = i[1]
                    id += 1
        id = 1
        if self.__type == False:
            for i in self.__vector_comments:
                if i != "None":
                    comentario = ET.SubElement(root, "comentario")
                    id_comentario = ET.SubElement(comentario, "id")
                    id_comentario.text = str(id)
                    texto = ET.SubElement(comentario, "contenido")
                    texto.text = i
                    id += 1

        tree = ET.ElementTree(root)
        tree.write(xml_out)
示例#20
0
 def create(prefsFile, rootToken):
     '''
   Creates an empty preferences structure and saves it to the named file.
   If this preferences object already held a preferences structure, it
   is lost. The given preferences file name is stored for later use.
   '''
     Preferences.writeTree(prefsFile, ET.Element(rootToken))
示例#21
0
def appendXbgf(tree,xbgfFile):
 if not tree:
  tree = ET.Element(slpsns.xbgf_('sequence'))
 xtree = ET.parse(xbgfFile)
 for t in xtree.findall('*'):
  tree.append(t)
 return tree
示例#22
0
 def create_todo_item(self,
                      list_id,
                      content,
                      party_id=None,
                      notify=False,
                      due_at=None):
     """
     Creates a new todo item record for the given list. The new record
     begins its life in the "uncompleted" state. (See the "Complete" and
     "Uncomplete" actions.) It is added at the bottom of the given list.
     If a person is responsible for the item, give their id as the party_id
     value. If a company is responsible, prefix their company id with a 'c'
     and use that as the party_id value. If the item has a person as the
     responsible party, you can also use the "notify" key to indicate
     whether an email should be sent to that person to tell them about the
     assignment.
     """
     path = '/todo_lists/%u/todo_items.xml' % list_id
     req = ET.Element('todo-item')
     ET.SubElement(req, 'content').text = unicode(content)
     if party_id:
         ET.SubElement(req, 'responsible-party').text = str(party_id)
         ET.SubElement(req, 'notify').text = str(bool(notify)).lower()
     if due_at:
         ET.SubElement(req, 'due-at').text = str(due_at)
     return self._request(path, req, post=True, return_response=True)
示例#23
0
    def add(self, item, textValue=None):
        '''
      Adds the given item (specified as a path)--and all missing intervening
      items in the path--to this preferences structure and sets its text
      property to the given value. If the given value is None, then the text
      property of the added item is not set. If there is already an item at
      the given path, then another item is added as a sibling of the extant
      item. The added Element object is returned.
      '''
        added_elt = None

        if self.mRoot is not None:
            path = item.split('/')
            append_type = path.pop()
            item = '/'.join(path)
            parent = self.mRoot.find(item)

            if parent is None:
                parent = self.add(item)

            child = ET.Element(append_type)
            if textValue is not None:
                child.text = str(textValue)
            parent.append(child)

            added_elt = child
        else:
            raise Exception, 'No XML tree available to modify'

        return added_elt
示例#24
0
 def create_todo_list(self,
                      project_id,
                      milestone_id=None,
                      private=None,
                      tracked=False,
                      name=None,
                      description=None,
                      template_id=None):
     """
     This will create a new, empty list. You can create the list
     explicitly, or by giving it a list template id to base the new list
     off of.
     """
     path = '/projects/%u/todo_lists.xml' % project_id
     req = ET.Element('todo-list')
     if milestone_id is not None:
         ET.SubElement(req, 'milestone-id').text = str(milestone_id)
     if private is not None:
         ET.SubElement(req, 'private').text = str(bool(private)).lower()
     ET.SubElement(req, 'tracked').text = str(bool(tracked)).lower()
     if name is not None:
         ET.SubElement(req, 'name').text = unicode(name)
         ET.SubElement(req, 'description').text = unicode(description)
     if template_id is not None:
         ET.SubElement(req,
                       'todo-list-template-id').text = str(int(template_id))
     return self._request(path, req, post=True)
示例#25
0
 def create_message(self,
                    project_id,
                    category_id,
                    title,
                    body,
                    private=False,
                    notify=None,
                    attachments=None):
     """
     Creates a new message, optionally sending notifications to a selected
     list of people. Note that you can also upload files using this
     function, but you need to upload the files first and then attach them.
     See the description at the top of this document for more information.
     """
     path = '/projects/%u/posts.xml' % project_id
     req = ET.Element('request')
     req.append(
         self._create_message_post_elem(category_id, title, body, private))
     if notify:
         for person_id in notify:
             ET.SubElement(req, 'notify').text = str(int(person_id))
     # TODO: Implement attachments.
     if attachments is not None:
         raise NotSupportedErr('Attachments are currently not implemented.')
     ##for attachment in attachments:
     ##    attms = ET.SubElement(req, 'attachments')
     ##    if attachment['name']:
     ##        ET.SubElement(attms, 'name').text = str(attachment['name'])
     ##    file_ = ET.SubElement(attms, 'file')
     ##    ET.SubElement(file_, 'file').text = str(attachment['temp_id'])
     ##    ET.SubElement(file_, 'content-type').text \
     ##        = str(attachment['content_type'])
     ##    ET.SubElement(file_, 'original-filename').text \
     ##        = str(attachment['original_filename'])
     return self._request(path, req, post=True, return_response=True)
示例#26
0
def writeKML(earth, counties, party):
    print 'Writing ' + party
    kml = ET.Element('kml', {'xmlns': 'http://earth.google.com/kml/2.0'})
    kmlDocument = ET.SubElement(kml, 'Document')
    kmlDocumentLookAt = ET.SubElement(kmlDocument, 'LookAt')
    kmlDocumentLookAtLatitude = ET.SubElement(kmlDocumentLookAt, 'latitude')
    kmlDocumentLookAtLatitude.text = '43.5'
    kmlDocumentLookAtLongitude = ET.SubElement(kmlDocumentLookAt, 'longitude')
    kmlDocumentLookAtLongitude.text = '-71.7'
    kmlDocumentLookAtRange = ET.SubElement(kmlDocumentLookAt, 'range')
    kmlDocumentLookAtRange.text = '200000'
    kmlDocumentLookAtTilt = ET.SubElement(kmlDocumentLookAt, 'tilt')
    kmlDocumentLookAtTilt.text = '55'
    kmlDocumentName = ET.SubElement(kmlDocument, 'name')
    kmlDocumentName.text = 'New Hampshire ' + partyName(party) + ' Primary'
    kmlFolder = ET.SubElement(kmlDocument, 'Folder')
    kmlFolderName = ET.SubElement(kmlFolder, 'name')
    kmlFolderName.text = 'New Hampshire Towns'
    for name, county in counties.iteritems():
        kmlPlacemark = ET.SubElement(kmlFolder, 'Placemark')
        #kmlPlaceName = ET.SubElement( kmlPlacemark, 'name' )
        #kmlPlaceName.text = name
        kmlMultiGeometry = ET.SubElement(kmlPlacemark, 'MultiGeometry')
        if earth:
            kmlPoint = ET.SubElement(kmlMultiGeometry, 'Point')
            kmlPointCoordinates = ET.SubElement(kmlPoint, 'coordinates')
            kmlPointCoordinates.text = coord(county['centroid'])
        kmlPolygon = ET.SubElement(kmlMultiGeometry, 'Polygon')
        kmlOuterBoundaryIs = ET.SubElement(kmlPolygon, 'outerBoundaryIs')
        kmlLinearRing = ET.SubElement(kmlOuterBoundaryIs, 'LinearRing')
        kmlCoordinates = ET.SubElement(kmlLinearRing, 'coordinates')
        kmlCoordinates.text = ' '.join(
            [coord(point) for point in county['points']])
        kmlStyle = ET.SubElement(kmlPlacemark, 'Style')
        if earth:
            kmlIconStyle = ET.SubElement(kmlStyle, 'IconStyle')
            kmlIcon = ET.SubElement(kmlIconStyle, 'Icon')
            kmlIconHref = ET.SubElement(kmlIcon, 'href')
            leader = getLeader(county, party) or {'name': 'generic'}
            kmlIconHref.text = iconBaseUrl + leader['name'] + '-border.png'
            kmlBalloonStyle = ET.SubElement(kmlStyle, 'BalloonStyle')
            kmlBalloonText = ET.SubElement(kmlBalloonStyle, 'text')
            kmlBalloonText.text = htmlBalloon(county, party)
        kmlLineStyle = ET.SubElement(kmlStyle, 'LineStyle')
        kmlLineStyleColor = ET.SubElement(kmlLineStyle, 'color')
        kmlLineStyleColor.text = '40000000'
        kmlLineStyleWidth = ET.SubElement(kmlLineStyle, 'width')
        kmlLineStyleWidth.text = '1'
        kmlPolyStyle = ET.SubElement(kmlStyle, 'PolyStyle')
        kmlPolyStyleColor = ET.SubElement(kmlPolyStyle, 'color')
        kmlPolyStyleColor.text = getColor(county, party)

    kmlTree = ET.ElementTree(kml)
    kmlfile = open(
        private.targetKML + ['maps', 'earth'][earth] + '-nh-' + party + '.kml',
        'w')
    kmlfile.write('<?xml version="1.0" encoding="utf-8" ?>\n')
    kmlTree.write(kmlfile)
    kmlfile.close()
示例#27
0
文件: BGF.py 项目: siwiwit/slps
 def getXml(self):
     #print 'Getting the XML of grammar...'
     self.ex = ET.Element(slpsns.bgf_('grammar'))
     for e in self.roots:
         ET.SubElement(self.ex, 'root').text = e
     for e in self.prods:
         self.ex.append(e.getXml())
     return self.ex
示例#28
0
 def test_et():
     """ElementTree"""
     _table = et.Element('table')
     for row in table:
         tr = et.SubElement(_table, 'tr')
         for c in row.values():
             et.SubElement(tr, 'td').text = str(c)
     et.tostring(_table)
示例#29
0
def main(bgffile,xbgffile):
	seq = ET.Element(slpsns.xbgf_('sequence'))
	rr = ET.SubElement(seq,slpsns.xbgf_('reroot'))
	for r in ET.XML('<list>'+''.join(open(bgffile,'r').readlines()).strip()+'</list>').findall('*'):
		x = ET.SubElement(rr,'root')
		x.text = r.text
	ET.ElementTree(seq).write(xbgffile)
	return
示例#30
0
文件: BGF.py 项目: siwiwit/slps
 def getXml(self):
     #print 'Getting the XML of production...'
     self.ex = ET.Element(slpsns.bgf_('production'))
     if self.label != '':
         ET.SubElement(self.ex, 'label').text = self.label
     ET.SubElement(self.ex, 'nonterminal').text = str(self.nt)
     self.ex.append(self.expr.getXml())
     return self.ex