コード例 #1
0
ファイル: timing.py プロジェクト: somaproject/doctools
    def __init__(self, filename):
        
        self.filename = filename
        
        # we assume that the clock is the maximum length
        
        self.period = 40
        self.height = 20
        self.signalspacing = 10

        self.xzero = 90
        self.signalcnt  = 0 
        self.cycles = 0
        
        
        self.colors = ['powderblue', 'palegreen', 'lightpink', 'lightsalmon', 'lightgrey']
        self.classes = {}
        
        
        self.svgelem = Element("{http://www.w3.org/2000/svg}svg")


        self.signalselem = Element("g")
        
        self.ypos = self.height + self.signalspacing
コード例 #2
0
    def dump(self, output):
        tempo = {}

        root = Element('resources')
        root.tail = '\n'

        tempo[()] = root

        for key in self._resources_order:
            for i in range(1, len(key) + 1):
                if key[0:i] not in tempo:
                    parent = tempo[key[0:i - 1]]

                    value = self._resources.get(key[0:i], None)

                    if value is None:
                        elem = SubElement(parent, 'node', name=key[i - 1])
                    else:
                        fullKey = key[0]
                        for j in range(1, i):
                            fullKey += '/' + key[j]
                        newValue = self._dictionary[fullKey]

                        elem = SubElement(parent,
                                          'node',
                                          name=key[i - 1],
                                          value=newValue)

                    parent.text = elem.tail = '\n' + i * SPACES
                    tempo[key[0:i]] = elem

        fix_it(root)

        print >> output, '<?xml version="1.0" encoding="UTF-8"?>'
        ElementTree(root).write(output, 'ascii')
コード例 #3
0
ファイル: restore-i18n.py プロジェクト: ALEXGUOQ/FBReader
    def dump(self, output):
        tempo = {}

        root = Element('resources')
        root.tail = '\n'

        tempo[()] = root
        
        for key in self._resources_order:
            for i in range(1, len(key)+1):
                if key[0:i] not in tempo:
                    parent = tempo[key[0:i-1]]

                    value = self._resources.get(key[0:i], None)

                    if value is None:
                        elem = SubElement(parent, 'node', name=key[i-1])
                    else:
                        fullKey = key[0];
                        for j in range(1, i):
                            fullKey += '/' + key[j] 
                        newValue = self._dictionary[fullKey]

                        elem = SubElement(parent, 'node', name=key[i-1], value=newValue)

                    parent.text = elem.tail = '\n' + i*SPACES
                    tempo[key[0:i]] = elem

        fix_it(root)

        print >> output, '<?xml version="1.0" encoding="UTF-8"?>'
        ElementTree(root).write(output, 'ascii')
コード例 #4
0
	def AdicionarUsuario(self,Aluno):
		"""
			Método que cria o usuário no jenkins, atualmente o jenkins está vinculado com o ldap do sistema ead, por mais que o usuário esteja criado no jenkins, ele não conseguirá autenticar se não estiver cadastrado no LDAP também.
			Para fazer o cadastro do aluno é adicionada mais uma linha do /var/lib/jenkins/config.xml dentro das tags <permission> somente com permissão de leitura.

			:param Aluno: Aluno é uma string somente com o email do aluno.

			:returns: Esse método não possui valor de retorno
		"""
		try:
			tree = parse("/var/lib/jenkins/config.xml")
			elem = tree.getroot()
			perm = elem.find('authorizationStrategy')
			busca = perm.findall("permission")
			for b in busca:
				if Aluno in b.text:
					log.warning("[!] Usuario Ja cadastrado no jenkins")
					return
			user = Element("permission")
			user.text = "hudson.model.Hudson.Read:%s"%Aluno
			perm.append(user)
			tree.write("/var/lib/jenkins/config.xml")
			log.info("[+] Usuario %s adicionado ao jenkins com Sucesso",Aluno)
		except Exception as e:
			log.error("[-] Erro ao adicionar usuario ao jenkins %s",e)
コード例 #5
0
 def create_new_feature(self, location=None):
     self.feature = Element('feature')
     for elem in self.tag_names:
         self.feature.append(Element(elem))
     if not location:
         self.xmltree.append(self.feature)
     else:
         self.xmltree.insert(location, self.feature)
     self.indent(self.xmltree)
コード例 #6
0
 def addRing(self, objRing, strType):
         if strType == 'Inner':
                 elemBnd = Element('innerBoundaryIs')
         else:
                 elemBnd = Element('outerBoundaryIs')
         elemRing = SubElement(elemBnd, 'LinearRing')
         elemCoords = SubElement(elemRing, "coordinates")
         elemCoords.text = self.addCoordinates(objRing[1])
         return elemBnd
コード例 #7
0
ファイル: xml_op.py プロジェクト: DreamsFuture/pytools
def create_node(tag, property_map, content):
    '''新造一个节点
       tag:节点标签
       property_map:属性及属性值map
       content: 节点闭合标签里的文本内容
       return 新节点'''
    element = Element(tag, property_map)
    element.text = content
    return element
コード例 #8
0
ファイル: xml_op.py プロジェクト: zwr8/pytools
def create_node(tag, property_map, content):
    '''新造一个节点
       tag:节点标签
       property_map:属性及属性值map
       content: 节点闭合标签里的文本内容
       return 新节点'''
    element = Element(tag, property_map)
    element.text = content
    return element
コード例 #9
0
 def ToElement(self, it=None):
     """
     Represents the store contents as an ElementTree.Element.
     """
     if it is None:
         it = self.entries.iteritems()
     elt = Element("entities")
     for peer_id, entry in it:
         elt.append(entry.ToElement())
     return elt
コード例 #10
0
    def convert(self, data, cache, **kwargs):
        bodydom = Element('div')
        kmldom = XML(data)
        ns = kmldom.tag.strip('kml')
        placemarks = kmldom.findall('.//%sPlacemark' % ns)
        for placemark in placemarks:
            titles = placemark.findall(ns + 'name')
            for title in titles:
                t = Element('h2')
                t.text = title.text
                bodydom.append(t)

            descriptions = placemark.findall(ns + 'description')
            for desc in descriptions:
                if desc.text:
                    try:
                        text = desc.text.encode('ascii',
                                                'xmlcharrefreplace').strip()
                    except:
                        text = desc.text.strip()
                    text = sanitize(text)
                    d = XML('<div>' +
                            text.encode('ascii', 'xmlcharrefreplace') +
                            '</div>')
                    bodydom.append(d)

        body = tostring(bodydom)
        cache.setData(body)
        return cache
コード例 #11
0
ファイル: timing.py プロジェクト: somaproject/doctools
    def draw_clock(self):

        elem = Element("path")
        ptuple = (self.x, self.y, self.period/2, -self.height, self.period/2, self.height)
        elem.attrib['d'] = "M%f,%f h%f v%f h%f v%f" % ptuple
        elem.attrib['stroke'] = "black"
        elem.attrib['fill'] = "none"
        elem.attrib['stroke-linecap'] = "square"
        self.x += self.period
        self.sval = 'L'
        return elem
コード例 #12
0
class ZigXmlParser(object):
    def __init__(self, input):
        self.filename = os.path.split(input)[-1]
        self.xmltree = parse(input).getroot()
        self.TODAY = date.today().isoformat()
        self.tag_names = [
            'ID', 'creator', 'created_date', 'modified_date', 'weight',
            'aplha', 'BQP', 'BQP_buffer', 'cell_removal', 'spp_file'
        ]

    def read_element(self, element, idvalue):
        for target in self.xmltree.findall('feature'):
            if target.find('ID').text == str(idvalue):
                return target.find(element).text

    def write_element(self, element, idvalue, value):
        # Set modified_date for the inputset
        self.xmltree.find('modified_date').text = self.TODAY
        for target in self.xmltree.findall('feature'):
            if target.find('ID').text == str(idvalue):
                target.find(element).text = str(value)
                # Set modified_date for the specific element
                target.find('modified_date').text = self.TODAY

    def create_new_feature(self, location=None):
        self.feature = Element('feature')
        for elem in self.tag_names:
            self.feature.append(Element(elem))
        if not location:
            self.xmltree.append(self.feature)
        else:
            self.xmltree.insert(location, self.feature)
        self.indent(self.xmltree)

    def write_xml_file(self):
        ElementTree(self.xmltree).write(os.getcwd() + r'\mod_' + self.filename)
        print os.getcwd() + r'\mod_' + self.filename

    def show_xml_tree(self):
        dump(self.xmltree)

    def indent(self, elem, level=0):
        """ Adds tab to the tree, so that saving it as usual results in a prettyprinted tree."""
        i = "\n" + level * "\t"
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "\t"
            for elem in elem:
                self.indent(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i
コード例 #13
0
ファイル: Converters.py プロジェクト: DeCarabas/mlsfu
def ConvertToKML(report):
    root = Element(KML("kml"))
    root.attrib["xmlns"] = "http://earth.google.com/kml/2.2"
    doc = SubElement(root, KML("Document"))
    for entry in report:
        placemark = SubElement(doc, KML("Placemark"))
        SubElement(placemark, KML("name")).text = entry["Address"]
        SubElement(placemark, KML("description")).text = BuildDescription(entry)
        # SubElement(placemark, KML("description")).text = entry['Details']
        SubElement(SubElement(placemark, KML("Point")), KML("coordinates")).text = Geocode(entry["Address"])
    return ElementTree(root)
コード例 #14
0
    def create_slide(self, buf, i,name=''):
        # creating the name of the slide
        # by parsing the title and removing any odd character
        slidename = re.sub('[^a-zA-Z0-9\\s]','',name)
        slidename = re.sub('\\s','_',slidename)      

        # we create a new div that will contain the slide
        cont = Element("div") #etree_loader.importETree().Element('div')
        cont.set('class', 'slide')
        cont.set('id', slidename)

        return cont
コード例 #15
0
ファイル: rsswriter.py プロジェクト: DeCarabas/feedarchive
def GetFeedElement(feed):
    """Create an atom:feed element for the provided feed.

    The provided feed must be in the format described at http://feedparser.org.
    """

    rss = Element("rss")
    rss.attrib["version"] = "2.0"

    root = SubElement(rss, "channel")

    TextElement(root, "title", feed.feed.get("title_detail"))
    if feed.feed.has_key("links"):
        for link in feed.feed.links:
            if link.rel != "self": continue
            SubElementIf(root, "link", link.href)
    
    TextElement(root, "description", feed.feed.get("subtitle_detail"))
    TextElement(root, "copyright", feed.feed.get("rights_detail"))
    SubElement(root, "generator").text = "feedarchive"
    
    if feed.feed.has_key("image"):
        im = feed.feed.image
        ie = SubElement(root, "image")
        SubElementIf(ie, "url", im.get("href"))
        SubElementIf(ie, "title", im.get("title"))
        SubElementIf(ie, "link", im.get("link"))

    if feed.feed.has_key("tags"):
        for tag in feed.feed.tags:
            te = SubElement(root, "category")
            if (tag.has_key("scheme")): te.attrib["domain"] = tag.scheme
            te.text = tag.term

    for entry in feed.entries:
        ee = SubElement(root, "item")
        TextElement(ee, "title", entry.get("title_detail"))
        SubElementIf(ee, "link", entry.get("link"))
        TextElement(ee, "description", entry.get("summary_detail"))
        SubElementIf(ee, "guid", entry.get("id"))
        DateTimeElement(ee, "pubDate", entry, "published")
        PersonElement(ee, "author", entry.get("author_detail"))

        if entry.has_key("links"):
            for link in entry.links:
                if link.rel != "enclosure": continue
                ence = SubElement(ee, "enclosure")
                AttribIf(ence, "url", link.get("url"))
                AttribIf(ence, "length", link.get("length"))
                AttribIf(ence, "type", link.get("type"))
                
    return rss
コード例 #16
0
ファイル: export.py プロジェクト: avoinea/stiamro
    def properties(self):
        """ Export properties
        """
        contentType = self.context.contentType
        prop = Element("property", name="contentType")
        prop.text = contentType
        yield prop

        data = self.context.data
        prop = Element("property", name="data")
        data = base64.encodestring(data)
        prop.text = CDATA % data
        yield prop
コード例 #17
0
def gencix(major, minor):
    # First generate first pass at the CILE over all of the lib tree
    cixfile = "activeperl-%d.%d.cix" % (major, minor)
    command = "python ../../../ci2.py scan -n -r -p -l Perl -T /tmp/ActivePerl-%d.%d/perl/lib -i \"*.pm\"> %s" % (
        major, minor, cixfile)
    retval = os.system(command)
    if retval != 0:
        print "Error scanning ActivePerl library"
        sys.exit(retval)
    #
    # Grab the output of that scan

    root = parse(cixfile).getroot()

    newroot = Element("codeintel", version="2.0")
    cixfile = SubElement(newroot,
                         "file",
                         lang="Perl",
                         mtime=str(int(time.time())),
                         path=os.path.basename('perl.cix'))

    for file in root.getiterator('file'):
        print >> sys.stderr, "Processing", file.get('path')
        for blob in file:
            if blob.get("src"):
                # Don't want the src string.
                del blob.attrib["src"]
            cixfile.append(blob)

    cix = genPerlStdCIX(
        cixfile,
        "/tmp/ActivePerl-%d.%d/perl/lib/pod/perlfunc.pod" % (major, minor))

    parent_map = dict((c, p) for p in cixfile.getiterator() for c in p)
    for variable in newroot.getiterator('variable'):
        attributes = variable.get('attributes')
        if attributes and '__local__' in variable.get('attributes'):
            parent_map[variable].remove(variable)

    # Generate the CIX.
    print >> sys.stderr, "Prettying"
    prettify(newroot)
    tree = ElementTree(newroot)
    #fname = '../../../lib/codeintel2/stdlibs/perl-%d.%d.cix' % (major, minor)
    fname = 'perl-%d.%d.cix' % (major, minor)
    #os.system('p4 edit %s' % fname)
    stream = open(fname, "w")
    print >> sys.stderr, "Writing"
    stream.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    tree.write(stream)
    stream.close()
コード例 #18
0
ファイル: feedwriter.py プロジェクト: DeCarabas/feedarchive
def GetFeedElement(feed):
    """Create an atom:feed element for the provided feed.

    The provided feed must be in the format described at http://feedparser.org.
    """

    root = Element("feed")
    root.attrib["xmlns"] = "http://www.w3.org/2005/Atom"

    TextElement(root, "title", feed.feed.get("title_detail"))
    if feed.feed.has_key("links"):
        for link in feed.feed.links:
            LinkElement(root, "link", link)
            
    TextElement(root, "subtitle", feed.feed.get("subtitle_detail"))
    TextElement(root, "rights", feed.feed.get("rights_detail"))
    SubElement(root, "generator").text = "feedarchive"
    SubElement(root, "updated").text = rfc3339(time.time())
    SubElementIf(root, "id", feed.feed.get("id"))
    
    if feed.feed.has_key("image"):
        SubElement(root, "icon").text = feed.feed.image.href

    if feed.feed.has_key("tags"):
        for tag in feed.feed.tags:
            te = SubElement(root, "category")
            if tag.get("term"): te.attrib["term"] = tag.term
            if tag.get("scheme"): te.attrib["scheme"] = tag.scheme
            if tag.get("label"): te.attrib["label"] = tag.label

    PersonElement(root, "author", feed.feed.get("author_detail"))

    for entry in feed.entries:
        ee = SubElement(root, "entry")
        TextElement(ee, "title", entry.get("title_detail"))
        if entry.has_key("links"):
            for link in entry.links:
                LinkElement(ee, "link", link)
        TextElement(ee, "summary", entry.get("summary_detail"))
        TextElement(ee, "content", entry.get("content_detail"))
        DateTimeElement(ee, "published", entry, "published")
        DateTimeElement(ee, "updated", entry, "updated")
        SubElementIf(ee, "id", entry.get("id"))
        PersonElement(ee, "author", entry.get("author_detail"))
        PersonElement(ee, "publisher", entry.get("publisher_detail"))
        if entry.has_key("contributors"):
            for contributor in entry.contributors:
                PersonElement(ee, "contributor", contributor)
        CreateSourceElement(ee, entry.get("source"))

    return root
コード例 #19
0
ファイル: export.py プロジェクト: avoinea/stiamro
    def body(self):
        """ Body exporter
        """
        klass = self.context.__class__
        factory = ".".join((klass.__module__, klass.__name__))
        element = Element("object", name=self.context.__name__, factory=factory)

        for prop in self.properties:
            element.append(prop)

        for child in self.children:
            element.append(child)

        return element
コード例 #20
0
ファイル: parsebills.py プロジェクト: samknight/parlparse
def maketree(printdict):
	root=Element('top')
	
	i=0

	for (session, no, house) in printdict.keys():
		i=i+1
		elem=Element('print',printdict[(session, no, house)])

		root.insert(i, elem)	

	billtree=ElementTree(root)

	return billtree
コード例 #21
0
    def dump(self, output, lang):
        tempo = {}

        root = Element('resources')
        root.tail = '\n'

        tempo[()] = root

        for key in self._resources_order:
            for i in range(1, len(key) + 1):
                if key[0:i] not in tempo:
                    parent = tempo[key[0:i - 1]]

                    value = self._resources.get(key[0:i], None)

                    if value is None:
                        elem = SubElement(parent, 'node', name=key[i - 1])
                    else:
                        localized = value.get(lang, None)
                        english = value.get('en', None)

                        if english is None:
                            print >> sys.stderr, 'English file does not have the string for', key[
                                0:i]
                            print >> sys.stderr, '  entry is marked as obosolete.'

                            elem = SubElement(parent,
                                              'node',
                                              name=key[i - 1],
                                              value=localized,
                                              obsolete='true')
                        elif localized is not None:
                            elem = SubElement(parent,
                                              'node',
                                              name=key[i - 1],
                                              value=localized)
                        else:
                            elem = SubElement(parent,
                                              'node',
                                              name=key[i - 1],
                                              value=english,
                                              toBeTranslated='true')

                    parent.text = elem.tail = '\n' + i * SPACES
                    tempo[key[0:i]] = elem

        fix_it(root)

        print >> output, '<?xml version="1.0" encoding="UTF-8"?>'
        ElementTree(root).write(output, 'utf-8')
コード例 #22
0
def consultaDetalleProduccion(request, nrec):
    #def consultaDetalleProduccion(ncab):
    dajax = Dajax()
    nrec = DetProcesos.objects.filter(cabprocesos=CabProcesos.objects.get(
        pk=ncab))[0].id
    raiz = DetProcesos.get_root(DetProcesos.objects.get(pk=nrec)).id
    size = DetProcesos.get_descendant_count(
        DetProcesos.objects.get(id=raiz)) + 1
    print raiz
    padre = DetProcesos.objects.get(id=raiz)
    cpadre = str(raiz)
    #Cabecera del Mensaje
    root = ET.Element("mxGraphModel")
    head = ET.SubElement(root, "root")
    ele = Element("mxCell")
    ele.set("id", "0")
    head.append(ele)
    ele1 = Element("mxCell")
    ele1.set("id", cpadre)
    ele1.set("parent", "0")
    head.append(ele1)
    objetoProcesos(head, str(raiz + 1), str(raiz + 1), str(raiz), str(raiz),
                   padre.descripcion)
    print padre.descripcion
    nid = raiz
    for ele in range(0, size - 1):
        obj = DetProcesos.get_children(DetProcesos.objects.get(id=nid))
        if len(obj) != 0:
            objetoProcesos(head, str(nid + 2), str(nid + 2), cpadre, cpadre,
                           obj.values()[0]['descripcion'])
            print obj.values()[0]['descripcion']
            nid = obj.values()[0]['id']

    nid = raiz
    cpadre = str(raiz + 1)
    for ele in range(0, size - 1):
        obj = DetProcesos.get_children(DetProcesos.objects.get(id=nid))
        if len(obj) != 0:
            nid = obj.values()[0]['id']
            dest = nid + 1
            enlaceProceso(
                head, str(nid + 2), str(nid + 2), str(raiz), str(raiz), cpadre,
                str(dest),
                TiposProcesos.objects.get(id=obj.values()[0]['tproceso_id']))
            cpadre = str(dest)

    valores = simplejson.dumps(ET.tostring(root), cls=JSONEncoder)
    #tree = ET.ElementTree(root)
    #tree.write("salida.xml")
    return valores
コード例 #23
0
ファイル: any_writer.py プロジェクト: Huskyeder/augustus
 def _format(self,elemap,obj):
   defaults = self._defaults
   out = Element(elemap[0])
   for subspec in elemap[1:]:
     if type(subspec) == type(''):
       tmp = obj.get(subspec,None)
       if tmp is None or str(tmp) == '':
         tmp = defaults.get(subspec,'')
       out.text = str(tmp)
       continue
     # here, subspec is really a recursive element map
     subelem = self._format(subspec,obj)
     out.append(subelem)
   return out
コード例 #24
0
 def _format(self, elemap, obj):
     defaults = self._defaults
     out = Element(elemap[0])
     for subspec in elemap[1:]:
         if type(subspec) == type(''):
             tmp = obj.get(subspec, None)
             if tmp is None or str(tmp) == '':
                 tmp = defaults.get(subspec, '')
             out.text = str(tmp)
             continue
         # here, subspec is really a recursive element map
         subelem = self._format(subspec, obj)
         out.append(subelem)
     return out
コード例 #25
0
ファイル: treemodel.py プロジェクト: IMAGE-ET/dicomimport
    def __init__(self, root, showRoot = True):
        QtCore.QAbstractItemModel.__init__(self)
        if showRoot:
            fakeroot = Element("fakeroot")
            fakeroot.append(root)
            self._root = fakeroot
        else:
            self._root = root

        self._realroot = self._root
        
        self._columns = ["Tag", "Attributes"]
        
        self._np = dict((child, (parent, rowidx)) for parent in self._root.getiterator()
                        for rowidx, child in enumerate(parent))
コード例 #26
0
def createFilePodcast(mediaFilePath, title, description=''):
    """
    create the xml file using utf
    """

    mediaItem = Element("media")
    mediaItem.attrib["version"] = VERSION
    titleNode = SubElement(mediaItem, "title")
    titleNode.text = title
    descrNode = SubElement(mediaItem, "description")
    descrNode.text = description

    createXmlFile(mediaFilePath + '.xml', mediaItem)

    mediaItem.clear()
コード例 #27
0
def createFilePodcast(mediaFilePath, title, description=''):
    """
    create the xml file using utf
    """  
    
    mediaItem = Element("media")    
    mediaItem.attrib["version"] = VERSION
    titleNode = SubElement(mediaItem, "title")
    titleNode.text = title
    descrNode = SubElement(mediaItem, "description")
    descrNode.text = description
    
    createXmlFile(mediaFilePath + '.xml', mediaItem)
    
    mediaItem.clear()
コード例 #28
0
ファイル: mlparser.py プロジェクト: EU-OSHA/osha.policy
def new_tree_term(termIdentifier, caption, description):
    term = Element(ns + 'term')
    treeTermIdentifier = Element(ns + 'termIdentifier')
    treeTermIdentifier.text = termIdentifier
    term.append(treeTermIdentifier)
    treeCaption = Element('caption')
    addLangs(treeCaption, caption)
    term.append(treeCaption)
    treeDesc = Element('description')
    addLangs(treeDesc, description)
    term.append(treeDesc)
    return term
コード例 #29
0
ファイル: tools.py プロジェクト: EU-OSHA/osha.policy
 def new_tree_term(self, termIdentifier, caption, description):
     term = Element(NS + "term")
     treeTermIdentifier = Element(NS + "termIdentifier")
     treeTermIdentifier.text = termIdentifier
     term.append(treeTermIdentifier)
     treeCaption = Element(NS + "caption")
     self.addLangs(treeCaption, caption)
     term.append(treeCaption)
     treeDesc = Element("description")
     self.addLangs(treeDesc, description)
     term.append(treeDesc)
     return term
コード例 #30
0
	def toXML(self):
		'''Generate the xml representation of the letter matrix'''
		# <control type="panel">
		control = Element('control', type='panel', id=str(CONTROL_PANEL))
		if True:
			SubElement(control, 'posx').text = str(self.posx)
			SubElement(control, 'posy').text = str(self.posy)
			SubElement(control, 'width').text = str(self.width)
			SubElement(control, 'height').text = str(self.height)
			SubElement(control, 'onleft').text = '-'
			SubElement(control, 'onright').text = '-'
			SubElement(control, 'onup').text = '-'
			SubElement(control, 'ondown').text = '-'
			SubElement(control, 'viewtype', label='').text = 'panel'
			SubElement(control, 'pagecontrol').text = '-'
			SubElement(control, 'scrolltime').text = '-'
			SubElement(control, 'hitrect', x=str(-10), y=str(-10), w=str(1), h=str(1))
			# <itemlayout>
			itemlayout = SubElement(control, 'itemlayout', height=str(self.letterHeight), width=str(self.letterWidth))
			if True:
				self.addItemLayout(itemlayout, self.theme.inactive, 1)
				self.addItemLayout(itemlayout, self.theme.active, 2)
			# </itemlayout>
			SubElement(control, 'focusedlayout', height=str(self.height), width=str(self.width))
			# <content>
			content = SubElement(control, 'content')
			if True:
				# <item>
				for letter in self.letters:
					content.append(letter.toXML())
				# </item>
			# </content>
		# </control>
		return control
コード例 #31
0
ファイル: pattern.py プロジェクト: scottjrodgers/sc
def write(pattern, fpath):
    import os
    from elementtree.ElementTree import Element, ElementTree
    root = Element('xml')
    toelem(pattern, root)
    ElementTree(root).write(fpath)
    os.system('tidy -xml -iqm \"%s\"' % fpath)
コード例 #32
0
	def toXML(self):
		# <window>
		window = Element('window', id=str(WINDOW_ID))
		if True:
			# Fade in for 1.0 second (but not in screensaver mode)
			if not self.screensaverMode:
				SubElement(window, 'animation', effect='fade', time=str(1000)).text = 'WindowOpen'
			
			# <controls>
			controls = SubElement(window, 'controls')
			if True:
				# <control type="image">
				color = Image(1280, 720, BACKGROUND_IMAGE, self.theme.background)
				controls.append(color.toXML())
				# </control>
				
				# <control type="image">
				if self.theme.image:
					image = Image(self.theme.imageWidth, self.theme.imageHeight, self.theme.image)
				else:
					# Placeholder for if we change the theme by pressing T
					image = Image(1280, 720, '-')
				controls.append(image.toXML())
				# </control>
				
				#sprites = Sprites(self.layout, self.theme)
				#controls.append(sprites.toXML())
				
				# <control type="panel">
				matrix = Matrix(self.letters, self.layout, self.theme)
				controls.append(matrix.toXML())
				# </control>
			# </controls>
		# </window>
		return window
コード例 #33
0
    def __call__ (self) :
        self.processed = {}
        self.pending   = {}
        tree           = Element ("project", id = "SW-Tasks")
        SubElement (tree, "label").text = ("Task(s) %s." % self.toplevel)
        SubElement (tree, "import-resources", file = "workers.xml")

        if self.VERBOSE > 1 :
            self.debug ("Writing `part_of` tree ...")
        for issue_id in self.toplevel :
            if self.VERBOSE > 2 :
                self.debug \
                    ("Issue %d is top-level. Processing it now ..." % issue_id)
            issue = self.db.issue.getnode (issue_id)
            self.process_issue (issue, tree)

        if self.VERBOSE > 1 :
            self.debug ("\nWriting issues due to `depends_on` or `needs` ...")
        while self.pending :
            (issue_id, issue) = self.pending.popitem ()
            if issue_id not in self.processed :
                if self.VERBOSE > 2 :
                    self.debug ("Adding %s ... "  % issue_id)
                self.process_issue (issue, tree)
            else :
                if self.VERBOSE > 3 :
                    self.debug ("%s already included." % issue_id)

        file = open (self.oname, "w")
        ElementTree (tree).write (file, encoding = "utf-8")
        if self.VERBOSE > 1 :
            self.debug ("Done.")
コード例 #34
0
 def writePolygon(self, objGeo, elemPlace):
         elemGeo = Element('Polygon')
         #Now add the ring(s)
         dctRings = objGeo.getRingInfo()
         #get the external ring(s)
         lstOuter = objGeo.getRing('Outer')
         lstInner = objGeo.getRing('Inner')
         for x in range(0, dctRings['Outer']):
                 elemRing = self.addRing(lstOuter[x], 'Outer')
                 elemGeo.append(elemRing)
                 
         for x in range(0, dctRings['Inner']):
                 elemRing = self.addRing(lstInner[x], 'Inner')
                 elemGeo.append(elemRing)
                 
         return elemGeo
コード例 #35
0
ファイル: Pyprofile.py プロジェクト: nmalka/Python_MIG
 def createNewProfiles(self, baseElem):
     for i in range(0, len(self.UniqueCos)):
         self.logger.info('New Default Profile element was created.')
         newElem = Element('DefaultProfile')
         for key, val in self.config['ProfileTags'].iteritems():
             e = Element(key)
             if e.tag == 'Id' or e.tag == 'ProfileId':
                 self.logger.info('The id is %s' % str(self.NewCosIds[i]))
                 e.text = str(self.NewCosIds[i])
             elif e.tag == 'CoSId':
                 self.logger.info('The CoSId is %s' % str(self.UniqueCos[i]))
                 e.text = self.UniqueCos[i]
             else:
                 e.text = val
             newElem._children.append(e)
         baseElem._children.append(newElem)
コード例 #36
0
ファイル: modules.py プロジェクト: msGenDev/Yeps-EURAC
 def get_runtime_inputs(self):
     label = self.state.get("name", "Input Dataset")
     return dict(input=DataToolParameter(
         None,
         Element(
             "param", name="input", label=label, type="data",
             format="data")))
コード例 #37
0
ファイル: genperlcix.py プロジェクト: Defman21/KomodoEdit
def gencix(major, minor):
    # First generate first pass at the CILE over all of the lib tree
    cixfile = "activeperl-%d.%d.cix" % (major, minor)
    command = "python ../../../ci2.py scan -n -r -p -l Perl -T /tmp/ActivePerl-%d.%d/perl/lib -i \"*.pm\"> %s" % (major, minor, cixfile)
    retval = os.system(command)
    if retval != 0:
        print "Error scanning ActivePerl library"
        sys.exit(retval)
    #    
    # Grab the output of that scan
    
    root = parse(cixfile).getroot()
    
    newroot = Element("codeintel", version="2.0")
    cixfile = SubElement(newroot, "file", lang="Perl",
                         mtime=str(int(time.time())),
                         path=os.path.basename('perl.cix'))
    
    for file in root.getiterator('file'):
        print >> sys.stderr, "Processing", file.get('path')
        for blob in file:
            if blob.get("src"):
                # Don't want the src string.
                del blob.attrib["src"]
            cixfile.append(blob)
    
    cix = genPerlStdCIX(cixfile, "/tmp/ActivePerl-%d.%d/perl/lib/pod/perlfunc.pod" % (major, minor))
        
    parent_map = dict((c, p) for p in cixfile.getiterator() for c in p)
    for variable in newroot.getiterator('variable'):
        attributes = variable.get('attributes')
        if attributes and '__local__' in variable.get('attributes'):
            parent_map[variable].remove(variable)

    # Generate the CIX.
    print >>sys.stderr, "Prettying"
    prettify(newroot)
    tree = ElementTree(newroot)
    #fname = '../../../lib/codeintel2/stdlibs/perl-%d.%d.cix' % (major, minor)
    fname = 'perl-%d.%d.cix' % (major, minor)
    #os.system('p4 edit %s' % fname)
    stream = open(fname, "w")
    print >>sys.stderr, "Writing"
    stream.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    tree.write(stream)
    stream.close()
コード例 #38
0
    def encode_XMLDict(self, mapping):
        """!TXT!"""

        def encode(key, value):
            element = Element(key)
            if isinstance(value, NoneType):
                element.attrib['type'] = 'none'
            elif isinstance(value, BooleanType):
                element.attrib['type'] = 'bool'
                element.attrib['value'] = value and 'true' or 'false'
            elif isinstance(value, ComplexType):
                element.attrib['type'] = 'complex'
                element.attrib['re'] = repr(value.real)
                element.attrib['im'] = repr(value.imag)
            elif isinstance(value, FloatType):
                element.attrib['type'] = 'float'
                element.attrib['value'] = repr(value)
            elif isinstance(value, IntType):
                element.attrib['type'] = 'int'
                element.attrib['value'] = repr(value)
            elif isinstance(value, LongType):
                element.attrib['type'] = 'long'
                element.attrib['value'] = repr(value)
            elif isinstance(value, StringType) or isinstance(value, UnicodeType):
                element.attrib['type'] = 'cdata'
                element.text = u"<![CDATA[%s]]>" % value
            elif isinstance(value, DictType):
                element.attrib['type'] = 'dict'
                for key in value.keys():
                    element.append(encode(key, value[key]))
            elif isinstance(value, ListType):
                element.attrib['type'] = 'list'
                for subvalue in value:
                    element.append(encode('value', subvalue))
            elif isinstance(value, TupleType):
                element.attrib['type'] = 'tuple'
                for subvalue in value:
                    element.append(encode('value', subvalue))
            else:
                raise TypeError("Encoding of %s not supported (Key: %s)" % (repr(value), key))
            return element

        root = Element("data")
        for key in mapping.keys():
            root.append(self.encode(key, mapping[key]))
        return tostring(root)
コード例 #39
0
ファイル: webtools.py プロジェクト: kd17290/USPSWebToolsAPI
 def build_request_xml(self, data, root_tag):
     root = Element(root_tag, USERID=self.user_id)
     for i, address in enumerate(data):
         address_element = SubElement(root, 'Address', ID=str(i))
         for field in self.address_fields:
             SubElement(
                 address_element, field).text = address.get(field.lower())
     return tostring(root)
コード例 #40
0
ファイル: timing.py プロジェクト: somaproject/doctools
    def add_clock(self, name, datastr):
        
        sigelem = Element('g')

        # this is where we get the cycle count
        
        self.cycles = len(datastr.split())
        
        clksig = signal(name, self.xzero, self.ypos, self.period, self.height)
        sigelem.append(clksig.draw_name())
        for i in datastr.split():
                sigelem.append(clksig.draw_clock())

        self.ypos += self.signalspacing + self.height   

        self.signalselem.append(sigelem)
        self.signalcnt += 1
コード例 #41
0
 def __split_models(self, xmlDoc):
     """generator that takes parameter xmlDoc and splits it into many
     xml files, with only one model per each"""
     elem = XML(xmlDoc)
     models = elem.find("Models")
     if models:
         elem.remove(models)
         for model in models:    
             to_return = copy.deepcopy(elem)    
             new_models = Element("Models")
             for a in models.attrib:
                 new_models.attrib[a] = models.attrib[a]
             new_models.append(model)
             to_return.append(new_models)
             yield (model.attrib['id'], to_return)
     else:
         pass #TODO return error
コード例 #42
0
    def convert(self, data, cache, **kwargs):
        bodydom = Element('div')
        kmldom = XML(data)
        ns = kmldom.tag.strip('kml')
        placemarks = kmldom.findall('.//%sPlacemark' % ns)
        for placemark in placemarks:
            titles = placemark.findall(ns + 'name')
            for title in titles:
                t = Element('h2')
                t.text = title.text
                bodydom.append(t)

            descriptions = placemark.findall(ns+'description')
            for desc in descriptions:
                if desc.text:
                    try:
                        text = desc.text.encode('ascii', 'xmlcharrefreplace').strip()
                    except:
                        text = desc.text.strip()
                    text = sanitize(text)
                    d = XML('<div>' + text.encode('ascii', 'xmlcharrefreplace') + '</div>')
                    bodydom.append(d)

        body = tostring(bodydom)
        cache.setData(body)
        return cache
コード例 #43
0
	def create_new_feature(self, location=None):
		self.feature = Element('feature')
		for elem in self.tag_names:
			self.feature.append(Element(elem))
		if not location:
			self.xmltree.append(self.feature)
		else:
			self.xmltree.insert(location, self.feature)
		self.indent(self.xmltree)
コード例 #44
0
ファイル: modules.py プロジェクト: charz/galaxy-central
 def get_runtime_inputs(self, filter_set=['data']):
     label = self.state.get("name", "Input Dataset")
     return dict(input=DataToolParameter(
         None,
         Element("param",
                 name="input",
                 label=label,
                 multiple=True,
                 type="data",
                 format=', '.join(filter_set)), self.trans))
コード例 #45
0
ファイル: treemodel.py プロジェクト: IMAGE-ET/dicomimport
    def __init__(self, root, showRoot = True):
        QtCore.QAbstractItemModel.__init__(self)
        if showRoot:
            fakeroot = Element("fakeroot")
            fakeroot.append(root.getroot())
            self._root = fakeroot
        else:
            self._root = root.getroot()

        self._xpathroot = root
        self._realroot = self._root
        
        self._columns = ["Tag", "Attributes"]
        
        self._ne = {}
        self._np = {}
        self._ne[0] = self._root
        self.buildMaps(self._root, 0)
        self._neo = self._ne.copy()
        self._npo = self._np.copy()
コード例 #46
0
def ConvertDialogToElement(dialog):
	

	# build a tree structure
	root = Element("DIALOG")
	for ctrl in dialog.AllControls():
		ctrlElem = SubElement(root, "CONTROL")
		for name, value in ctrl.properties.items():
			AddElement(ctrlElem, name, value)
	
	return root
コード例 #47
0
ファイル: modules.py プロジェクト: charz/galaxy-central
 def get_runtime_inputs(self, filter_set=['data']):
     label = self.state.get("name", self.default_name)
     collection_type = self.state.get("collection_type",
                                      self.default_collection_type)
     input_element = Element("param",
                             name="input",
                             label=label,
                             type="data_collection",
                             collection_type=collection_type)
     return dict(
         input=DataCollectionToolParameter(None, input_element, self.trans))
コード例 #48
0
ファイル: timing.py プロジェクト: somaproject/doctools
    def timinggrid(self):
        """
        This function uses the signalcnt, cycles, period, height, and spacing
        to draw the light lines that will be the clock lines.
        """

        gelem = Element("g") # create a group
        for i in range(int(self.cycles)):

            lelem = Element("line")
            lelem.attrib['x1'] = str(i*self.period + self.period/2.0 + self.xzero)
            lelem.attrib['y1'] = str(0);
            lelem.attrib['x2'] = str(i*self.period + self.period/2.0 + self.xzero)
            lelem.attrib['y2'] = str(self.signalcnt*(self.height + self.signalspacing) + self.signalspacing)
            lelem.attrib['stroke'] = "grey"
            lelem.attrib['stroke-width'] = "0.5"
            gelem.append(lelem)

        
        self.svgelem.append(gelem)
        self.svgelem.append(self.signalselem)
コード例 #49
0
ファイル: timing.py プロジェクト: somaproject/doctools
 def draw_name(self):
     """ the name is to the left of the original draw point"""
     elem = Element("text")
     elem.attrib['x'] =  "%f" %  (self.startx -4)
     elem.attrib['y'] = "%f" % (self.starty-4)
     elem.attrib['font-family'] = "Helvetica"
     elem.attrib['font-size'] = "%f" % (self.height/1.4)
     elem.attrib['text-anchor'] = "end"
     elem.text = self.name
     return elem
コード例 #50
0
def getCommand(args):
    result = getInterfaceInfo(args.macaddress)

    if result is None:
        print 'adapter not found'
        return 3

    top_node = Element('NetConfigurations')
    formatNetworkAdapterConfig(top_node, result)

    print tostring(top_node)
    return 0
コード例 #51
0
ファイル: timing.py プロジェクト: somaproject/doctools
    def draw_low(self):
        elem = Element("path")


        if self.sval == 'H':
            starty = self.y - self.height
        elif self.sval == 'Z':
            starty = self.y - self.height/2
        else:
            starty = self.y

        ptuple = (self.x, starty,  self.period/8, self.y-starty, 7*self.period/8)
        elem.attrib['d'] = "M%f,%f  l%f, %f h%f" % ptuple
        elem.attrib['stroke'] = "black"
        elem.attrib['fill'] = "none"
        elem.attrib['stroke-linecap'] = "square"
        self.x += self.period
        self.sval = 'L'
        

            
        return elem
コード例 #52
0
    def create_job(self, branch_name): 

        cleaned_branch_name = branch_name.replace("origin/", "").replace("/", "_")
        job_name = "%s-%s" % (self.prefix, cleaned_branch_name)
        full_job_path = "%s/%s" % (self.root_job_dir, job_name)
        try:
            os.mkdir(full_job_path)
        except OSError:
            print "Job already exists! Not creating."
            return
        template = open(self.config_template, "r")

        parser = parse(self.config_template)
        top_element = parser.getroot()

        branch_element = top_element.getiterator("hudson.plugins.git.BranchSpec")[0]
        [branch_element.remove(element) for element in branch_element.getchildren()]
        new_name_element = Element("name")
        new_name_element.text = branch_name
        branch_element.append(new_name_element)

        parser.write("%s/%s" % (full_job_path, self.config_xml))
コード例 #53
0
	def toXML(self):
		'''Generate the xml representation of this Letter'''
		# <item>
		item = Element('item')
		if True:
			# <label>$INFO[Window(Home).Property(Unqlocked.0.Background)]</label>
			SubElement(item, 'label').text = '$INFO[Window(Home).Property(%s)]' % (PROPERTY_INACTIVE % self.index)
			# <label2>$INFO[Window(Home).Property(Unqlocked.0.Highlight)]</label2>
			SubElement(item, 'label2').text = '$INFO[Window(Home).Property(%s)]' % (PROPERTY_ACTIVE % self.index)
			# <onclick>-</onclick>
			SubElement(item, 'onclick').text = '-'
		# </item>
		return item
コード例 #54
0
	def toXML(self):
		# <control>
		control = Element('control', type='image', id=str(self.id))
		if True:
			SubElement(control, 'posx').text = str((1280 - self.width) / 2)
			SubElement(control, 'posy').text = str((720 - self.height) / 2)
			SubElement(control, 'width').text = str(self.width)
			SubElement(control, 'height').text = str(self.height)
			SubElement(control, 'texture').text = self.image
			if self.diffuse:
				SubElement(control, 'colordiffuse').text = self.diffuse # AARRGGBB
			
		# </control>
		return control
コード例 #55
0
def listCommand(args):
    if isWindows():
        result = [win32GetInterfaceInfo(i) for i in win32EnumerateInterfaces()]
    elif isLinux() or isBsd():
        result = unixGetInterfaceList()
    else:
        raise Exception('Unsupported operating system')

    top_node = Element('NetConfigurations')

    for adapter in result:
        formatNetworkAdapterConfig(top_node, adapter)

    print tostring(top_node)
    return 0
コード例 #56
0
def main():
	top_node = Element('osinfo')

	if sys.platform == 'win32':
		info = windowsInfo()
	elif sys.platform == 'linux2':
		info = linuxInfo()
	elif sys.platform.startswith('freebsd'):
		info = bsdInfo()

	SubElement(top_node, 'name').text = info['name']
	SubElement(top_node, 'version').text = info['version']
	SubElement(top_node, 'details').text = info['details']
	
	print tostring(top_node)
	return 0
コード例 #57
0
def objetoProcesos(head, id, customid, vertex, parent, texto):
    subhead = ET.SubElement(head, "mxCell")
    subhead.set("id", id)
    subhead.set("customId", customid)
    subhead.set(
        "value",
        '<img src="editors/images/overlays/workplace.png"><br><b> %s </b> ' %
        texto)
    subhead.set("vertex", vertex)
    subhead.set("parent", parent)
    subele = Element("mxGeometry")
    subele.set("x", "0")
    subele.set("y", "0")
    subele.set("width", "180")
    subele.set("height", "70")
    subele.set("as", "geometry")
    subhead.append(subele)
    return head
コード例 #58
0
    def toElementTree(self, details):
        """
		Return an Element node with the XML rappresentation of this module
		"""
        c = Element('module')
        n = SubElement(c, 'name')
        n.text = self._alias
        if details:
            # version
            v = SubElement(c, 'version')
            v.text = str(self._version)
            # type
            t = SubElement(c, 'type')
            t.text = self._type
            # lock
            u = SubElement(c, 'upgradable')
            u.text = repr(self._upgradable).lower()
        return c
コード例 #59
0
ファイル: __init__.py プロジェクト: Matt-Sartain/AAN
 def FormattedContent(self, report_obj, chart_style, request):
     from atrinsic.base.models import AqWidget,UserAqWidget
     x = self.widget_id
     widget = AqWidget.objects.get(pk=self.widget_id)
     var_columns = None
     
     if self.user_widget_id != None:
         user_widget = UserAqWidget.objects.get(pk=self.user_widget_id)
         if user_widget.custom_columns != None:
             var_columns = user_widget.custom_columns
     if (var_columns == None) & (self.data_columns != None):
         var_columns = self.data_columns	
     else:
         var_columns = widget.data_columns
     if var_columns.find(",") > 0:
         col1,col2 = var_columns.split(",")
     else:
         col1 = var_columns
         col2 = None
     columns = { 'var1': col1, 'var2':col2 }
     if chart_style == "table":
         html = self.getReportHTML(report_obj)
         return html
     elif chart_style == "json-array":
         import cjson
         return cjson.encode(report_obj.RenderContents())
     elif chart_style == "json":
         import cjson
         json = self.get_json(report_obj)
         return cjson.encode(json)
     elif chart_style == "xml":
         from elementtree import ElementTree
         from elementtree.ElementTree import Element,tostring,SubElement,ElementTree,dump
         xmldict = {}
         xmldict["xml"] = self.get_json(report_obj)
         root = Element("xml")
         for row in xmldict["xml"]:
             item_element = SubElement(root,"item")
             for field in row:
                 SubElement(item_element,field).text = row[field]
         return tostring(root)
         
     else:
         return self.getAQChart(request=request,chart_style=chart_style,report_obj=report_obj,columns=columns)