def testAppendChildFragment():
    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
    dom.documentElement.appendChild(frag)
    confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3),
            "appendChild(<fragment>)")
    frag.unlink()
    dom.unlink()
Exemplo n.º 2
0
Arquivo: _xml.py Projeto: cmotc/medit
    def __init__(self, string):
        object.__init__(self)

        dom = parseString(string)
        self.root = XMLGroup(dom.documentElement.tagName)
        self.root.load_xml(dom.documentElement)
        dom.unlink()
Exemplo n.º 3
0
	def load(self):
		d1 = self.dbhelper.dbRead(self.om_db, "xml_date")
		d2 = os.stat(self.defFile).st_mtime
		print "XML_CSL_LOAD", d1, d2
		if d1 != None:
			if d1 > d2:
				# FIXME: hata vermek yerine db'leri sifirlayip yeniden olustur
				print "XML_CSL: OOPS, xml om definition is newer than om db"
				print "XML_CSL: please remove db files manually"
				return
			else:
				return
		print "XML_CSL: creating om DBs..."
		try:
			dom = xml.dom.minidom.parse(self.defFile)
		except:
			print "OMDB: cannot parse '%s'" % (self.defFile)
			return 0
		if dom.documentElement.localName != "comar-om":
			print "OMDB: '%s' is not a COMAR om dtd" % (self.defFile)
			return 0
		ns = dom.getElementsByTagName("namespace")[0]
		# FIXME: namespace in useNS ile ayni oldugunu dogrula
		self.namespace = ns.getAttribute("name")
		print "Adding OM Keys:",
		for node in ns.childNodes:
			self.load_node(node)
			
		dom.unlink()
		if d1 == None:
			self.dbhelper.dbWrite(self.om_db, "xml_date", str(d2))
		return 1
def testAAB():
    dom = parseString("<abc/>")
    el = dom.documentElement
    el.setAttribute("spam", "jam")
    el.setAttribute("spam", "jam2")
    confirm(el.toxml() == '<abc spam="jam2"/>', "testAAB")
    dom.unlink()
def _testElementReprAndStrUnicode():
    dom = Document()
    el = dom.appendChild(dom.createElement(u"abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    dom.unlink()
Exemplo n.º 6
0
def testAAB():
    dom = parseString("<abc/>")
    el = dom.documentElement
    el.setAttribute("spam", "jam")
    el.setAttribute("spam", "jam2")
    confirm(el.toxml() == '<abc spam="jam2"/>', "testAAB")
    dom.unlink()
Exemplo n.º 7
0
    def load_persistent_configuration(self):
        (dom, element) = self.find_own_dom_element()

        configuration = enter_named_element(element, 'configuration')
        if configuration and self.configuration is not None:
            self.configuration.set_from_dom_node(configuration)
        dom.unlink()
def testLegalChildren():
    dom = Document()
    elem = dom.createElement('element')
    text = dom.createTextNode('text')

    try: dom.appendChild(text)
    except xml.dom.HierarchyRequestErr: pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    dom.appendChild(elem)
    try: dom.insertBefore(text, elem)
    except xml.dom.HierarchyRequestErr: pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    try: dom.replaceChild(text, elem)
    except xml.dom.HierarchyRequestErr: pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    nodemap = elem.attributes
    try: nodemap.setNamedItem(text)
    except xml.dom.HierarchyRequestErr: pass
    else:
        print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr"

    try: nodemap.setNamedItemNS(text)
    except xml.dom.HierarchyRequestErr: pass
    else:
        print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr"

    elem.appendChild(text)
    dom.unlink()
Exemplo n.º 9
0
def getDomains(targets,release):
  import urllib
  from xml.dom.minidom import parse  
  import xml.dom
  import pickle
  pfamDict ={}
  

  ## Loop through all targets and get pfam domains.
  errors = []
  for target in targets:
    #print "getting Pfam domains for %s" % target
    pfamDict[target] = {}
    pfamDict[target]["domains"] = []
    pfamDict[target]["start"] = []
    pfamDict[target]["end"] = []
    opener = urllib.FancyURLopener({})                                     
    f = opener.open("http://pfam.sanger.ac.uk/protein/%s?output=xml" % target) 
    dom = parse(f)
    if not dom.getElementsByTagName('sequence'):
      #print "encountered Error for %s" %target
      errors.append(target)
      del pfamDict[target]
      continue

    
    for pfam in dom.childNodes:
      if pfam.nodeName == 'pfam':
        for entry in pfam.childNodes:
          if entry.nodeName == 'entry':
            for matches in entry.childNodes:
              if matches.nodeName == 'matches':
                for match in matches.childNodes:
                  if match.nodeName == 'match':
                    if match.getAttribute('type') == 'Pfam-A':
                      pfamDict[target]['domains'].append(match.getAttribute('id'))
                      for location in match.childNodes:
                        if location.nodeName == 'location':
                          start = location.getAttribute('start')
                          end = location.getAttribute('end')
                          pfamDict[target]['start'].append(int(start))
                          pfamDict[target]['end'].append(int(end))
    dom.unlink()
    
    # Add domain count.
    pfamDict[target]['count'] = len(pfamDict[target]['domains'])
    
    # Calculate and add the uniq count of domains. 
    uniqDomains = {}
    for domain in pfamDict[target]['domains']:
      uniqDomains[domain] = 0   
    pfamDict[target]['countUnique'] = len(uniqDomains)
    
  ## Pickle the PfamDict
  output = open('data/protCodPfamDict_%s.pkl' %release, 'w')
  pickle.dump(pfamDict, output)

  print "encountered Error for", errors
  return pfamDict   
Exemplo n.º 10
0
def testCloneElementShallow():
    dom, clone = _setupCloneElement(0)
    confirm(len(clone.childNodes) == 0
            and clone.childNodes.length == 0
            and clone.parentNode is None
            and clone.toxml() == '<doc attr="value"/>'
            , "testCloneElementShallow")
    dom.unlink()
Exemplo n.º 11
0
def testCloneElementDeep():
    dom, clone = _setupCloneElement(1)
    confirm(
        len(clone.childNodes) == 1 and clone.childNodes.length == 1
        and clone.parentNode is None
        and clone.toxml() == '<doc attr="value"><foo/></doc>',
        "testCloneElementDeep")
    dom.unlink()
Exemplo n.º 12
0
 def set_persistent_configuration(self):
     (dom, element) = self.find_own_dom_element()
     child = enter_named_element(element, 'configuration')
     if child:
         element.removeChild(child)
     if self.configuration: self.configuration.write_to_dom(dom, element)
     get_vistrails_application().vistrailsStartup.write_startup_dom(dom)
     dom.unlink()
Exemplo n.º 13
0
def testCloneElementDeep():
    dom, clone = _setupCloneElement(1)
    confirm(len(clone.childNodes) == 1
            and clone.childNodes.length == 1
            and clone.parentNode is None
            and clone.toxml() == '<doc attr="value"><foo/></doc>'
            , "testCloneElementDeep")
    dom.unlink()
Exemplo n.º 14
0
 def parse_from_xml(self, xml_spec):
     '''Parse a string or file containing an XML specification.'''
     if type(xml_spec) in string_types():
         dom = xml.dom.minidom.parseString(xml_spec)
     else:
         dom = xml.dom.minidom.parse(xml_spec)
     self._parse_xml(dom)
     dom.unlink()
Exemplo n.º 15
0
 def set_persistent_configuration(self):
     (dom, element) = self.find_own_dom_element()
     child = enter_named_element(element, 'configuration')
     if child:
         element.removeChild(child)
     self.configuration.write_to_dom(dom, element)
     get_vistrails_application().vistrailsStartup.write_startup_dom(dom)
     dom.unlink()
Exemplo n.º 16
0
def testAppendChildFragment():
    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
    dom.documentElement.appendChild(frag)
    confirm(
        tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3),
        "appendChild(<fragment>)")
    frag.unlink()
    dom.unlink()
Exemplo n.º 17
0
def testReplaceChildFragment():
    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
    dom.documentElement.replaceChild(frag, orig)
    orig.unlink()
    confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3),
            "replaceChild(<fragment>)")
    frag.unlink()
    dom.unlink()
Exemplo n.º 18
0
def testReplaceChildFragment():
    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
    dom.documentElement.replaceChild(frag, orig)
    orig.unlink()
    confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3),
            "replaceChild(<fragment>)")
    frag.unlink()
    dom.unlink()
Exemplo n.º 19
0
def testCloneElementShallow():
    dom, clone = _setupCloneElement(0)
    confirm(len(clone.childNodes) == 0
            and clone.childNodes.length == 0
            and clone.parentNode is None
            and clone.toxml() == '<doc attr="value"/>'
            , "testCloneElementShallow")
    dom.unlink()
Exemplo n.º 20
0
def _testElementReprAndStrUnicodeNS():
    dom = Document()
    el = dom.appendChild(
        dom.createElementNS(u"http://www.slashdot.org", u"slash:abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    confirm(string1.find("slash:abc") != -1)
    dom.unlink()
Exemplo n.º 21
0
def _testElementReprAndStrUnicodeNS():
    dom = Document()
    el = dom.appendChild(
        dom.createElementNS(u"http://www.slashdot.org", u"slash:abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    confirm(string1.find("slash:abc") != -1)
    dom.unlink()
Exemplo n.º 22
0
def testRemoveAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    child.setAttribute("def", "ghi")
    confirm(len(child.attributes) == 1)
    child.removeAttribute("def")
    confirm(len(child.attributes) == 0)

    dom.unlink()
Exemplo n.º 23
0
def testDeleteAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    confirm(len(child.attributes) == 0)
    child.setAttribute("def", "ghi")
    confirm(len(child.attributes) == 1)
    del child.attributes["def"]
    confirm(len(child.attributes) == 0)
    dom.unlink()
Exemplo n.º 24
0
def testDeleteAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    confirm(len(child.attributes) == 0)
    child.setAttribute("def", "ghi")
    confirm(len(child.attributes) == 1)
    del child.attributes["def"]
    confirm(len(child.attributes) == 0)
    dom.unlink()
Exemplo n.º 25
0
def testAAA():
    dom = parseString("<abc/>")
    el = dom.documentElement
    el.setAttribute("spam", "jam2")
    confirm(el.toxml() == '<abc spam="jam2"/>', "testAAA")
    a = el.getAttributeNode("spam")
    confirm(a.ownerDocument is dom, "setAttribute() sets ownerDocument")
    confirm(a.ownerElement is dom.documentElement,
            "setAttribute() sets ownerElement")
    dom.unlink()
Exemplo n.º 26
0
def testRemoveAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    child.setAttribute("def", "ghi")
    confirm(len(child.attributes) == 1)
    child.removeAttribute("def")
    confirm(len(child.attributes) == 0)

    dom.unlink()
Exemplo n.º 27
0
def testRemoveAttributeNode():
    dom = Document()
    child = dom.appendChild(dom.createElement("foo"))
    child.setAttribute("spam", "jam")
    confirm(len(child.attributes) == 1)
    node = child.getAttributeNode("spam")
    child.removeAttributeNode(node)
    confirm(
        len(child.attributes) == 0 and child.getAttributeNode("spam") is None)

    dom.unlink()
Exemplo n.º 28
0
 def importXML(path):
     logDebug("Importing data from "+str(path))
     try:
         dom = xml.dom.minidom.parse(path)
         document = XMLDocHRModuleImport(dom);            
         #document.debug()
         dom.unlink()
         return document
     except:
         logError(_("Importing failed."))
         return None
Exemplo n.º 29
0
def testRemoveAttributeNode():
    dom = Document()
    child = dom.appendChild(dom.createElement("foo"))
    child.setAttribute("spam", "jam")
    confirm(len(child.attributes) == 1)
    node = child.getAttributeNode("spam")
    child.removeAttributeNode(node)
    confirm(len(child.attributes) == 0
            and child.getAttributeNode("spam") is None)

    dom.unlink()
Exemplo n.º 30
0
def testAAA():
    dom = parseString("<abc/>")
    el = dom.documentElement
    el.setAttribute("spam", "jam2")
    confirm(el.toxml() == '<abc spam="jam2"/>', "testAAA")
    a = el.getAttributeNode("spam")
    confirm(a.ownerDocument is dom,
            "setAttribute() sets ownerDocument")
    confirm(a.ownerElement is dom.documentElement,
            "setAttribute() sets ownerElement")
    dom.unlink()
Exemplo n.º 31
0
def testRemoveAttrNS():
    dom = Document()
    child = dom.appendChild(
            dom.createElementNS("http://www.python.org", "python:abc"))
    child.setAttributeNS("http://www.w3.org", "xmlns:python",
                                            "http://www.python.org")
    child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
    confirm(len(child.attributes) == 2)
    child.removeAttributeNS("http://www.python.org", "abcattr")
    confirm(len(child.attributes) == 1)

    dom.unlink()
Exemplo n.º 32
0
def testRemoveAttrNS():
    dom = Document()
    child = dom.appendChild(
        dom.createElementNS("http://www.python.org", "python:abc"))
    child.setAttributeNS("http://www.w3.org", "xmlns:python",
                         "http://www.python.org")
    child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
    confirm(len(child.attributes) == 2)
    child.removeAttributeNS("http://www.python.org", "abcattr")
    confirm(len(child.attributes) == 1)

    dom.unlink()
Exemplo n.º 33
0
def testGetElementsByTagNameNS():
    d="""<foo xmlns:minidom='http://pyxml.sf.net/minidom'>
    <minidom:myelem/>
    </foo>"""
    dom = parseString(d)
    elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom", "myelem")
    confirm(len(elems) == 1
            and elems[0].namespaceURI == "http://pyxml.sf.net/minidom"
            and elems[0].localName == "myelem"
            and elems[0].prefix == "minidom"
            and elems[0].tagName == "minidom:myelem"
            and elems[0].nodeName == "minidom:myelem")
    dom.unlink()
Exemplo n.º 34
0
def testGetElementsByTagNameNS():
    d = """<foo xmlns:minidom='http://pyxml.sf.net/minidom'>
    <minidom:myelem/>
    </foo>"""
    dom = parseString(d)
    elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom", "myelem")
    confirm(
        len(elems) == 1
        and elems[0].namespaceURI == "http://pyxml.sf.net/minidom"
        and elems[0].localName == "myelem" and elems[0].prefix == "minidom"
        and elems[0].tagName == "minidom:myelem"
        and elems[0].nodeName == "minidom:myelem")
    dom.unlink()
Exemplo n.º 35
0
def testNamedNodeMapSetItem():
    dom = Document()
    elem = dom.createElement('element')
    attrs = elem.attributes
    attrs["foo"] = "bar"
    a = attrs.item(0)
    confirm(a.ownerDocument is dom,
            "NamedNodeMap.__setitem__() sets ownerDocument")
    confirm(a.ownerElement is elem,
            "NamedNodeMap.__setitem__() sets ownerElement")
    confirm(a.value == "bar", "NamedNodeMap.__setitem__() sets value")
    confirm(a.nodeValue == "bar", "NamedNodeMap.__setitem__() sets nodeValue")
    elem.unlink()
    dom.unlink()
Exemplo n.º 36
0
def testInsertBeforeFragment():
    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
    dom.documentElement.insertBefore(frag, None)
    confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3),
            "insertBefore(<fragment>, None)")
    frag.unlink()
    dom.unlink()
    #
    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
    dom.documentElement.insertBefore(frag, orig)
    confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3, orig),
            "insertBefore(<fragment>, orig)")
    frag.unlink()
    dom.unlink()
Exemplo n.º 37
0
def getBindingSites(targets, release):
    import urllib
    from xml.dom.minidom import parse
    import xml.dom
    import xml.parsers.expat
    import pickle
    bsDict = {}
    for target in targets:
        try:
            print "searching binding sites for %s" % target
            bsDict[target] = {}
            bsDict[target]["ligands"] = []
            bsDict[target]["positions"] = []
            opener = urllib.FancyURLopener({})
            f = opener.open("http://www.uniprot.org/uniprot/%s.xml" % target)
            dom = parse(f)
            for uniprot in dom.childNodes:
                if uniprot.nodeName == 'uniprot':
                    for entry in uniprot.childNodes:
                        if entry.nodeName == 'entry':
                            for feature in entry.childNodes:
                                if feature.nodeName == 'feature':
                                    if feature.getAttribute(
                                            'type') == 'binding site':
                                        ligand = feature.getAttribute(
                                            'description')
                                        for location in feature.childNodes:
                                            if location.nodeName == 'location':
                                                for position in location.childNodes:
                                                    if position.nodeName == 'position':
                                                        position = position.getAttribute(
                                                            'position')
                                                        #print target,'\t',ligand,'\t',position
                                                        bsDict[target][
                                                            'ligands'].append(
                                                                ligand)
                                                        bsDict[target][
                                                            'positions'].append(
                                                                position)
            dom.unlink()
        except xml.parsers.expat.ExpatError:
            continue
        if len(bsDict[target]["positions"]) == 0:
            del bsDict[target]

    out = open('data/bsDictUniprot_chembl%s.pkl' % release, 'w')
    pickle.dump(bsDict, out)
    out.close()

    return bsDict
Exemplo n.º 38
0
def testInsertBeforeFragment():
    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
    dom.documentElement.insertBefore(frag, None)
    confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3),
            "insertBefore(<fragment>, None)")
    frag.unlink()
    dom.unlink()
    #
    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
    dom.documentElement.insertBefore(frag, orig)
    confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3, orig),
            "insertBefore(<fragment>, orig)")
    frag.unlink()
    dom.unlink()
Exemplo n.º 39
0
def parse_liqpay_exchanges():
    """
<rates> 
  <EUR> 
    <RUR>41.2499</RUR> 
    <UAH>11.5500</UAH> 
    <USD>1.4154</USD> 
  </EUR> 
  <RUR> 
    <EUR>0.0226</EUR> 
    <UAH>0.2680</UAH> 
    <USD>0.0328</USD> 
  </RUR> 
  <UAH> 
    <EUR>0.0843</EUR> 
    <RUR>3.5714</RUR> 
    <USD>0.1225</USD> 
  </UAH> 
  <USD> 
    <EUR>0.6818</EUR> 
    <RUR>28.8571</RUR> 
    <UAH>8.0800</UAH> 
  </USD> 
</rates> 
    """
    CURRENCY['RUR'] = Currency(code='RUR', numeric='643', name='Russian Ruble', countries=['RUSSIAN FEDERATION'])
    rates = []
    dom = minidom.parse(urllib.urlopen(RATES_URL))
    if dom.documentElement.tagName != "rates":
        return rates
    for node1 in dom.documentElement.childNodes:
        if node1.nodeType == xml.dom.Node.ELEMENT_NODE:
            # get primary currency code
            code = node1.tagName.encode('utf-8')
            primary_currency = CURRENCY[code]
            for node2 in node1.childNodes:
                value = None
                secondary_currency = None
                if node2.nodeType == xml.dom.Node.ELEMENT_NODE:
                    code = node2.tagName.encode('utf-8')
                    secondary_currency = CURRENCY[code]
                    # find value
                    for node3 in node2.childNodes:
                        if node3.nodeType == xml.dom.Node.TEXT_NODE and (node3.nodeValue is not None):
                            value = Decimal(node3.nodeValue)
                if (primary_currency is not None) and (secondary_currency is not None) and (value is not None):
                    rates.append(ExchangeRate(primary_currency, secondary_currency, value))
    dom.unlink()
    return rates
Exemplo n.º 40
0
    def load_persistent_configuration(self):
        (dom, element) = ( None, None )
        for iAttempt in range(10):
            try:     
                (dom, element) = self.find_own_dom_element()
                break
            except:   time.sleep( 0.5 )

        if element <> None:       
            configuration = enter_named_element(element, 'configuration')
            if configuration and self.configuration:
                if self.configuration: self.configuration.set_from_dom_node(configuration)
                else: print>>sys.stderr, "Error, missing configuration in package"
            if dom <> None:  dom.unlink()
        else:
            print>>sys.stderr, "Error reading dom for package"
Exemplo n.º 41
0
def testNamedNodeMapSetItem():
    dom = Document()
    elem = dom.createElement('element')
    attrs = elem.attributes
    attrs["foo"] = "bar"
    a = attrs.item(0)
    confirm(a.ownerDocument is dom,
            "NamedNodeMap.__setitem__() sets ownerDocument")
    confirm(a.ownerElement is elem,
            "NamedNodeMap.__setitem__() sets ownerElement")
    confirm(a.value == "bar",
            "NamedNodeMap.__setitem__() sets value")
    confirm(a.nodeValue == "bar",
            "NamedNodeMap.__setitem__() sets nodeValue")
    elem.unlink()
    dom.unlink()
Exemplo n.º 42
0
    def create_startup_package_node(self):
        """Writes the node to the <packages> section.

        If it was in the <disabledpackages> section, move it, else, create it.
        """
        dom = get_vistrails_application().vistrailsStartup.startup_dom()

        node, section = self._get_package_node(dom, create='enabled')
        if section == 'disabled':
            self._move_package_node(dom, 'enabled', node)

        configuration = enter_named_element(node, 'configuration')
        if configuration:
            self.configuration.set_from_dom_node(configuration)

        dom.unlink()
Exemplo n.º 43
0
    def load_persistent_configuration(self):
        (dom, element) = ( None, None )
        for iAttempt in range(10):
            try:     
                (dom, element) = self.find_own_dom_element()
                break
            except:   time.sleep( 0.5 )

        if element <> None:       
            configuration = enter_named_element(element, 'configuration')
            if configuration and self.configuration:
                if self.configuration: self.configuration.set_from_dom_node(configuration)
                else: debug.warning("Error, missing configuration in package")
            if dom <> None:  dom.unlink()
        else:
            debug.warning("Error reading dom for package")
Exemplo n.º 44
0
    def __init__(self, filename, paths=None):
        self.filename = filename
        if paths is None:
            self.paths = list()
        else:
            self.paths = paths

        self.namespaces = dict()  # map local name to filename
        dom = xml.dom.minidom.parse(filename)
        tag = dom.documentElement
        if tag.tagName != 'resource':
            raise ResourceError('document is <%s> instead of <resource>' %
                                tag.tagName)
        try:
            self.handle(dom.documentElement)
        finally:
            dom.unlink()
    def __init__(self, filename, paths=None):
        self.filename = filename
        if paths is None:
            self.paths = []
        else:
            self.paths = paths

        self.namespaces = {}  # map local name to filename
        dom = xml.dom.minidom.parse(filename)
        tag = dom.documentElement
        if tag.tagName != 'resource':
            raise ResourceError('document is <%s> instead of <resource>' %
                                tag.tagName)
        try:
            self.handle(dom.documentElement)
        finally:
            dom.unlink()
Exemplo n.º 46
0
	def readXML(self, filename):
		dom = xml.dom.minidom.parse(filename)

		msh = dom.getElementsByTagName('mesh')
		if(len(msh) < 1):
			sys.exit(" ERROR: No element with tag name 'mesh' found!")

		self.dim = int  (msh[0].getAttribute('dim'))
		h        = float(msh[0].getElementsByTagName('h')[0].childNodes[0].data.strip())

		for p in msh[0].getElementsByTagName('patch'):
			x = []
			[ x.append(float(z)) for z in p.childNodes[0].data.strip().split(' ')]
			self.add(Cuboid(self.dim,x[0:3],x[3:6]))

		dom.unlink()

		self.createMesh(h)
Exemplo n.º 47
0
def getBindingSites(targets,release):
  import urllib
  from xml.dom.minidom import parse  
  import xml.dom
  import xml.parsers.expat
  import pickle
  bsDict ={}
  for target in targets:
    try:
      print "searching binding sites for %s" % target
      bsDict[target] = {}
      bsDict[target]["ligands"] = []
      bsDict[target]["positions"] = []
      opener = urllib.FancyURLopener({})                                     
      f = opener.open("http://www.uniprot.org/uniprot/%s.xml" % target) 
      dom = parse(f)
      for uniprot in dom.childNodes:
        if uniprot.nodeName == 'uniprot':
          for entry in uniprot.childNodes:
            if entry.nodeName == 'entry':
              for feature in entry.childNodes:
                if feature.nodeName == 'feature':
                  if feature.getAttribute('type') == 'binding site':
                    ligand = feature.getAttribute('description') 
                    for location in feature.childNodes:
                      if location.nodeName == 'location':
                        for position in location.childNodes:
                          if position.nodeName == 'position':
                            position = position.getAttribute('position')
                            #print target,'\t',ligand,'\t',position
                            bsDict[target]['ligands'].append(ligand)
                            bsDict[target]['positions'].append(position)
      dom.unlink()
    except xml.parsers.expat.ExpatError:
      continue
    if len(bsDict[target]["positions"]) == 0:
      del bsDict[target]
      
      
  out  = open('data/bsDictUniprot_chembl%s.pkl'%release, 'w')
  pickle.dump(bsDict, out)
  out.close()
      
  return bsDict
Exemplo n.º 48
0
def testLegalChildren():
    dom = Document()
    elem = dom.createElement('element')
    text = dom.createTextNode('text')

    try:
        dom.appendChild(text)
    except xml.dom.HierarchyRequestErr:
        pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    dom.appendChild(elem)
    try:
        dom.insertBefore(text, elem)
    except xml.dom.HierarchyRequestErr:
        pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    try:
        dom.replaceChild(text, elem)
    except xml.dom.HierarchyRequestErr:
        pass
    else:
        print "dom.appendChild didn't raise HierarchyRequestErr"

    nodemap = elem.attributes
    try:
        nodemap.setNamedItem(text)
    except xml.dom.HierarchyRequestErr:
        pass
    else:
        print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr"

    try:
        nodemap.setNamedItemNS(text)
    except xml.dom.HierarchyRequestErr:
        pass
    else:
        print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr"

    elem.appendChild(text)
    dom.unlink()
    def create_startup_package_node(self):
        (dom, element) = self.find_own_dom_element()
        doc = dom.documentElement
        disabledpackages = enter_named_element(doc, 'disabledpackages')
        packages = enter_named_element(doc, 'packages')

        oldpackage = self.find_disabledpackage_element(doc)

        if oldpackage is not None:
            # Must remove element from oldpackages,
            # _and_ the element that was just created in find_own_dom_element()
            disabledpackages.removeChild(oldpackage)
            packages.removeChild(element)
            packages.appendChild(oldpackage)
            configuration = enter_named_element(oldpackage, 'configuration')
            if configuration:
                self.configuration.set_from_dom_node(configuration)
            get_vistrails_application().vistrailsStartup.write_startup_dom(dom)
        dom.unlink()
Exemplo n.º 50
0
    def create_startup_package_node(self):
        (dom, element) = self.find_own_dom_element()
        doc = dom.documentElement
        disabledpackages = enter_named_element(doc, 'disabledpackages')
        packages = enter_named_element(doc, 'packages')

        oldpackage = self.find_disabledpackage_element(doc)

        if oldpackage is not None:
            # Must remove element from oldpackages,
            # _and_ the element that was just created in find_own_dom_element()
            disabledpackages.removeChild(oldpackage)
            packages.removeChild(element)
            packages.appendChild(oldpackage)
            configuration = enter_named_element(oldpackage, 'configuration')
            if configuration:
                if self.configuration: self.configuration.set_from_dom_node(configuration)
                else: debug.warning("Error, missing configuration in package")
            get_vistrails_application().vistrailsStartup.write_startup_dom(dom)
        dom.unlink()
Exemplo n.º 51
0
def testAddAttr():
    dom = Document()
    child = dom.appendChild(dom.createElement("abc"))

    child.setAttribute("def", "ghi")
    confirm(child.getAttribute("def") == "ghi")
    confirm(child.attributes["def"].value == "ghi")

    child.setAttribute("jkl", "mno")
    confirm(child.getAttribute("jkl") == "mno")
    confirm(child.attributes["jkl"].value == "mno")

    confirm(len(child.attributes) == 2)

    child.setAttribute("def", "newval")
    confirm(child.getAttribute("def") == "newval")
    confirm(child.attributes["def"].value == "newval")

    confirm(len(child.attributes) == 2)
    dom.unlink()
Exemplo n.º 52
0
def testInsertBefore():
    dom = parseString("<doc><foo/></doc>")
    root = dom.documentElement
    elem = root.childNodes[0]
    nelem = dom.createElement("element")
    root.insertBefore(nelem, elem)
    confirm(len(root.childNodes) == 2
            and root.childNodes.length == 2
            and root.childNodes[0] is nelem
            and root.childNodes.item(0) is nelem
            and root.childNodes[1] is elem
            and root.childNodes.item(1) is elem
            and root.firstChild is nelem
            and root.lastChild is elem
            and root.toxml() == "<doc><element/><foo/></doc>"
            , "testInsertBefore -- node properly placed in tree")
    nelem = dom.createElement("element")
    root.insertBefore(nelem, None)
    confirm(len(root.childNodes) == 3
            and root.childNodes.length == 3
            and root.childNodes[1] is elem
            and root.childNodes.item(1) is elem
            and root.childNodes[2] is nelem
            and root.childNodes.item(2) is nelem
            and root.lastChild is nelem
            and nelem.previousSibling is elem
            and root.toxml() == "<doc><element/><foo/><element/></doc>"
            , "testInsertBefore -- node properly placed in tree")
    nelem2 = dom.createElement("bar")
    root.insertBefore(nelem2, nelem)
    confirm(len(root.childNodes) == 4
            and root.childNodes.length == 4
            and root.childNodes[2] is nelem2
            and root.childNodes.item(2) is nelem2
            and root.childNodes[3] is nelem
            and root.childNodes.item(3) is nelem
            and nelem2.nextSibling is nelem
            and nelem.previousSibling is nelem2
            and root.toxml() == "<doc><element/><foo/><bar/><element/></doc>"
            , "testInsertBefore -- node properly placed in tree")
    dom.unlink()
Exemplo n.º 53
0
    def parse_from_xml(self, xml_spec):
        '''Parse a string or file containing an XML specification.

        Example:
        >>> s = RtsProfile()
        >>> s.parse_from_xml(open('test/rtsystem.xml'))
        >>> len(s.components)
        3

        Load of invalid data should throw exception:
        >>> s.parse_from_xml('non-XML string')
        Traceback (most recent call last):
        ...
        ExpatError: syntax error: line 1, column 0
        '''
        if type(xml_spec) in string_types():
            dom = xml.dom.minidom.parseString(xml_spec)
        else:
            dom = xml.dom.minidom.parse(xml_spec)
        self._parse_xml(dom)
        dom.unlink()
Exemplo n.º 54
0
def testUserData():
    dom = Document()
    n = dom.createElement('e')
    confirm(n.getUserData("foo") is None)
    n.setUserData("foo", None, None)
    confirm(n.getUserData("foo") is None)
    n.setUserData("foo", 12, 12)
    n.setUserData("bar", 13, 13)
    confirm(n.getUserData("foo") == 12)
    confirm(n.getUserData("bar") == 13)
    n.setUserData("foo", None, None)
    confirm(n.getUserData("foo") is None)
    confirm(n.getUserData("bar") == 13)

    handler = UserDataHandler()
    n.setUserData("bar", 12, handler)
    c = n.cloneNode(1)
    confirm(handler.called and n.getUserData("bar") is None
            and c.getUserData("bar") == 13)
    n.unlink()
    c.unlink()
    dom.unlink()
Exemplo n.º 55
0
def testChangeAttr():
    dom = parseString("<abc/>")
    el = dom.documentElement
    el.setAttribute("spam", "jam")
    confirm(len(el.attributes) == 1)
    el.setAttribute("spam", "bam")
    # Set this attribute to be an ID and make sure that doesn't change
    # when changing the value:
    el.setIdAttribute("spam")
    confirm(len(el.attributes) == 1
            and el.attributes["spam"].value == "bam"
            and el.attributes["spam"].nodeValue == "bam"
            and el.getAttribute("spam") == "bam"
            and el.getAttributeNode("spam").isId)
    el.attributes["spam"] = "ham"
    confirm(len(el.attributes) == 1
            and el.attributes["spam"].value == "ham"
            and el.attributes["spam"].nodeValue == "ham"
            and el.getAttribute("spam") == "ham"
            and el.attributes["spam"].isId)
    el.setAttribute("spam2", "bam")
    confirm(len(el.attributes) == 2
            and el.attributes["spam"].value == "ham"
            and el.attributes["spam"].nodeValue == "ham"
            and el.getAttribute("spam") == "ham"
            and el.attributes["spam2"].value == "bam"
            and el.attributes["spam2"].nodeValue == "bam"
            and el.getAttribute("spam2") == "bam")
    el.attributes["spam2"] = "bam2"
    confirm(len(el.attributes) == 2
            and el.attributes["spam"].value == "ham"
            and el.attributes["spam"].nodeValue == "ham"
            and el.getAttribute("spam") == "ham"
            and el.attributes["spam2"].value == "bam2"
            and el.attributes["spam2"].nodeValue == "bam2"
            and el.getAttribute("spam2") == "bam2")
    dom.unlink()
Exemplo n.º 56
0
def testAltNewline():
    str = '<?xml version="1.0" ?>\n<a b="c"/>\n'
    dom = parseString(str)
    domstr = dom.toprettyxml(newl="\r\n")
    dom.unlink()
    confirm(domstr == str.replace("\n", "\r\n"))
Exemplo n.º 57
0
def testWriteXML():
    str = '<?xml version="1.0" ?><a b="c"/>'
    dom = parseString(str)
    domstr = dom.toxml()
    dom.unlink()
    confirm(str == domstr)
Exemplo n.º 58
0
def testAttributeRepr():
    dom = Document()
    el = dom.appendChild(dom.createElement(u"abc"))
    node = el.setAttribute("abc", "def")
    confirm(str(node) == repr(node))
    dom.unlink()
Exemplo n.º 59
0
def testGetElementsByTagName():
    dom = parse(tstfile)
    confirm(dom.getElementsByTagName("LI") == \
            dom.documentElement.getElementsByTagName("LI"))
    dom.unlink()
Exemplo n.º 60
0
def testParseFromFile():
    dom = parse(StringIO(open(tstfile).read()))
    dom.unlink()
    confirm(isinstance(dom, Document))