Returns the <MEMBRANE> tag XML for pdb_id if the tag exists.
14611
def get_membrane_xml(self, pdb_id):
        ''' '''
        self.tmp_string = None
        context = etree.iterparse(io.BytesIO(self.xml_contents), events=('end',), tag=self.PDBTM_entry_tag_type)
        try:
            fast_iter(context, self._get_membrane_xml, pdb_id = pdb_id.upper())
        except EarlyOut: pass
        return self.tmp_string
848191
def _get_status_from_xml_tags(self, root, relevant_tags):
        
        for child in root:
            if child.tag not in relevant_tags.keys():
                continue
            elif child.tag == "Power":
                self._power = child[0].text
                relevant_tags.pop(child.tag, None)
            elif child.tag == "InputFuncSelect":
                inputfunc = child[0].text
                if inputfunc is not None:
                    try:
                        self._input_func = self._input_func_list_rev[inputfunc]
                    except KeyError:
                        _LOGGER.info(
                            "No mapping for source %s found", inputfunc)
                        self._input_func = inputfunc
                    finally:
                        relevant_tags.pop(child.tag, None)
            elif child.tag == "MasterVolume":
                self._volume = child[0].text
                relevant_tags.pop(child.tag, None)
            elif child.tag == "Mute":
                self._mute = child[0].text
                relevant_tags.pop(child.tag, None)
            elif child.tag == "FriendlyName" and self._name is None:
                self._name = child[0].text
                relevant_tags.pop(child.tag, None)
            elif child.tag == "selectSurround" or child.tag == "SurrMode":
                self._sound_mode_raw = child[0].text.rstrip()
                relevant_tags.pop("selectSurround", None)
                relevant_tags.pop("SurrMode", None)

        return relevant_tags
1303551
def retrieve(pdb_id, cache_dir = None):
        ''''''

        pdb_contents = None
        xml_contents = None
        pdb_id = pdb_id.upper()

        if cache_dir:
            # Check to see whether we have a cached copy of the PDB file
            filename = os.path.join(cache_dir, "%s.pdb" % pdb_id)
            if os.path.exists(filename):
                pdb_contents = read_file(filename)

            # Check to see whether we have a cached copy of the XML file
            filename = os.path.join(cache_dir, "%s.xml" % pdb_id)
            if os.path.exists(filename):
                xml_contents = read_file(filename)

        # Get any missing files from the RCSB and create cached copies if appropriate
        if not pdb_contents:
            pdb_contents = rcsb.retrieve_pdb(pdb_id)
            if cache_dir:
                write_file(os.path.join(cache_dir, "%s.pdb" % pdb_id), pdb_contents)

        if not xml_contents:
            xml_contents = rcsb.retrieve_xml(pdb_id)
            if cache_dir:
                write_file(os.path.join(cache_dir, "%s.xml" % pdb_id), xml_contents)

        # Return the object
        return PDBML_slow(xml_contents, pdb_contents)
680234
def load_pdb(self, pdbpath, as_string=False):
        """"""
        if as_string:
            self.sourcefiles['pdbcomplex.original'] = None
            self.sourcefiles['pdbcomplex'] = None
            self.sourcefiles['pdbstring'] = pdbpath
        else:
            self.sourcefiles['pdbcomplex.original'] = pdbpath
            self.sourcefiles['pdbcomplex'] = pdbpath
        self.information['pdbfixes'] = False
        pdbparser = PDBParser(pdbpath, as_string=as_string)  # Parse PDB file to find errors and get additonal data
        # #@todo Refactor and rename here
        self.Mapper.proteinmap = pdbparser.proteinmap
        self.Mapper.reversed_proteinmap = {v: k for k, v in self.Mapper.proteinmap.items()}
        self.modres = pdbparser.modres
        self.covalent = pdbparser.covalent
        self.altconf = pdbparser.altconformations
        self.corrected_pdb = pdbparser.corrected_pdb

        if not config.PLUGIN_MODE:
            if pdbparser.num_fixed_lines > 0:
                write_message('%i lines automatically fixed in PDB input file.\n' % pdbparser.num_fixed_lines)
                # Save modified PDB file
                if not as_string:
                    basename = os.path.basename(pdbpath).split('.')[0]
                else:
                    basename = "from_stdin"
                pdbpath_fixed = tmpfile(prefix='plipfixed.' + basename + '_', direc=self.output_path)
                create_folder_if_not_exists(self.output_path)
                self.sourcefiles['pdbcomplex'] = pdbpath_fixed
                self.corrected_pdb = re.sub(r'[^\x00-\x7F]+', ' ', self.corrected_pdb)  # Strip non-unicode chars
                if not config.NOFIXFILE:  # Only write to file if this option is not activated
                    with open(pdbpath_fixed, 'w') as f:
                        f.write(self.corrected_pdb)
                self.information['pdbfixes'] = True

        if not as_string:
            self.sourcefiles['filename'] = os.path.basename(self.sourcefiles['pdbcomplex'])
        self.protcomplex, self.filetype = read_pdb(self.corrected_pdb, as_string=True)

        # Update the model in the Mapper class instance
        self.Mapper.original_structure = self.protcomplex.OBMol
        write_message('PDB structure successfully read.\n')

        # Determine (temporary) PyMOL Name from Filename
        self.pymol_name = pdbpath.split('/')[-1].split('.')[0] + '-Protein'
        # Replace characters causing problems in PyMOL
        self.pymol_name = self.pymol_name.replace(' ', '').replace('(', '').replace(')', '').replace('-', '_')
        # But if possible, name it after PDBID in Header
        if 'HEADER' in self.protcomplex.data:  # If the PDB file has a proper header
            potential_name = self.protcomplex.data['HEADER'][56:60].lower()
            if extract_pdbid(potential_name) != 'UnknownProtein':
                self.pymol_name = potential_name
        write_message("Pymol Name set as: '%s'\n" % self.pymol_name, mtype='debug')

        # Extract and prepare ligands
        ligandfinder = LigandFinder(self.protcomplex, self.altconf, self.modres, self.covalent, self.Mapper)
        self.ligands = ligandfinder.ligands
        self.excluded = ligandfinder.excluded

        # Add polar hydrogens
        self.protcomplex.OBMol.AddPolarHydrogens()
        for atm in self.protcomplex:
            self.atoms[atm.idx] = atm
        write_message("Assigned polar hydrogens\n", mtype='debug')

        if len(self.excluded) != 0:
            write_message("Excluded molecules as ligands: %s\n" % ','.join([lig for lig in self.excluded]))

        if config.DNARECEPTOR:
            self.resis = [obres for obres in pybel.ob.OBResidueIter(
                self.protcomplex.OBMol) if obres.GetName() in config.DNA+config.RNA]
        else:
            self.resis = [obres for obres in pybel.ob.OBResidueIter(
                self.protcomplex.OBMol) if obres.GetResidueProperty(0)]

        num_ligs = len(self.ligands)
        if num_ligs == 1:
            write_message("Analyzing one ligand...\n")
        elif num_ligs > 1:
            write_message("Analyzing %i ligands...\n" % num_ligs)
        else:
            write_message("Structure contains no ligands.\n\n")
315904
def __get_tag_ids(self, tags):
        """"""

        db_tags = self.fetchall("select * from tags where name in (%s)"
                                            % ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables

        changes = False

        # check if any of tags needs resurrection
        set_complete = [str(tag["id"]) for tag in db_tags if tag["autocomplete"] == "false"]
        if set_complete:
            changes = True
            self.execute("update tags set autocomplete='true' where id in (%s)" % ", ".join(set_complete))


        found_tags = [tag["name"] for tag in db_tags]

        add = set(tags) - set(found_tags)
        if add:
            statement = "insert into tags(name) values(?)"

            self.execute([statement] * len(add), [(tag,) for tag in add])

            return self.__get_tag_ids(tags)[0], True # all done, recurse
        else:
            return db_tags, changes
444911
def _pdb_frame(self):
        """"""
        if self._pdb_obj is not None and self._pdb_obj.curframe is not None:
            return self._pdb_obj.curframe
28298
def get_build_container_tag(self):
        
        if self.__prefix:
            return "{0}-{1}-{2}".format(
                self.__prefix,
                self.__branch,
                self.__version)
        else:
            return "{0}-{1}".format(
                self.__branch,
                self.__version)
1099711
protected DCTree blockTag() {
        int p = bp;
        try {
            nextChar();
            if (isIdentifierStart(ch)) {
                Name name = readTagName();
                TagParser tp = tagParsers.get(name);
                if (tp == null) {
                    List<DCTree> content = blockContent();
                    return m.at(p).UnknownBlockTag(name, content);
                } else {
                    switch (tp.getKind()) {
                        case BLOCK:
                            return tp.parse(p);
                        case INLINE:
                            return erroneous("dc.bad.inline.tag", p);
                    }
                }
            }
            blockContent();

            return erroneous("dc.no.tag.name", p);
        } catch (ParseException e) {
            blockContent();
            return erroneous(e.getMessage(), p);
        }
    }
1089286
def pdb(self):
        """"""
        pdb_str = write_pdb(
            [self], ' ' if not self.tags['chain_id'] else self.tags['chain_id'])
        return pdb_str
71581
def get_synset_xml(self,syn_id):
        

        http, resp, content = self.connect()

        params   = ""
        fragment = ""

        path = "cdb_syn"
        if self.debug:
            printf( "cornettodb/views/query_remote_syn_id: db_opt: %s" % path )

        # output_opt: plain, html, xml
        # 'xml' is actually xhtml (with markup), but it is not valid xml!
        # 'plain' is actually valid xml (without markup)
        output_opt = "plain"
        if self.debug:
            printf( "cornettodb/views/query_remote_syn_id: output_opt: %s" % output_opt )

        action = "runQuery"
        if self.debug:
            printf( "cornettodb/views/query_remote_syn_id: action: %s" % action )
            printf( "cornettodb/views/query_remote_syn_id: query: %s" % syn_id )

        qdict = {}
        qdict[ "action" ]  = action
        qdict[ "query" ]   = syn_id
        qdict[ "outtype" ] = output_opt

        query = urllib.urlencode( qdict )

        db_url_tuple = ( self.scheme, self.host + ':' + str(self.port), path, params, query, fragment )
        db_url = urlparse.urlunparse( db_url_tuple )
        if self.debug:
            printf( "db_url: %s" % db_url )

        resp, content = http.request( db_url, "GET" )
        if self.debug:
            printf( "resp:\n%s" % resp )
        #    printf( "content:\n%s" % content )
        #    printf( "content is of type: %s" % type( content ) )        #<type 'str'>

        xml_data = eval( content )
        return etree.fromstring( xml_data )
1149671
@Override
	public  List<ScopDomain> getDomainsForPDB(String pdbId) {

		try {
			ensureClaInstalled();
		} catch (IOException e) {
			throw new ScopIOException(e);
		}

		List<ScopDomain> doms = domainMap.get(pdbId.toLowerCase());

		List<ScopDomain> retdoms = new ArrayList<ScopDomain>();

		if ( doms == null)
			return retdoms;

		for ( ScopDomain d : doms){
			try {
				ScopDomain n = (ScopDomain) d.clone();
				retdoms.add(n);
			}  catch (CloneNotSupportedException e){
				throw new RuntimeException(ScopDomain.class + " subclass does not support clone()", e);
			}


		}
		return retdoms;
	}
150660
def _get_pdb_id(self, elem, **kwargs):
        ''''''
        id = elem.attrib['ID']
        if self.restrict_to_transmembrane_proteins:
            tmp = elem.attrib['TMP']
            assert(tmp == 'no' or tmp == 'yes' or tmp == 'not')
            if tmp == 'yes':
                self.ids[id] = PDBTM._get_tm_type(elem)
        else:
            self.ids[id] = self.ids.get(id, 0) + 1
791187
def pdbechem_parse(download = False, filename = '/kortemmelab/shared/mirror/PDBeChem/chem_comp.xml'):
    ''''''

    xml_data = None
    if download:
        # this URL will go out of date
        try:
            resource = ['ftp.ebi.ac.uk', '/pub/databases/msd/pdbechem/chem_comp.xml']
            xml_data = get_insecure_resource(resource[0], resource[1])
        except FTPException550, e:
            colortext.error("This resource ftp://%s appears to be missing. The link may need to be updated in the script." % "".join(resource))
            raise
        except Exception, e:
            colortext.error("An error occurred downloading ftp://%s:\n%s" % ("".join(resource), str(e)))
            raise
    else:
        xml_data = read_file(filename)

    _dom = parseString(xml_data)

    main_tag = _dom.getElementsByTagName("chemCompList")
    assert(len(main_tag) == 1)
    main_tag = main_tag[0]
    entries = main_tag.getElementsByTagName("chemComp")

    parsed_dict = {}
    properties = ["id", "name", "formula", "systematicName", "stereoSmiles", "nonStereoSmiles", "InChi"]
    for e in entries:
        d = {}
        for p in properties:
            t = e.getElementsByTagName(p)
            assert(len(t) <= 1)
            if p == "id":
                assert(len(t) == 1 and t[0].childNodes)
            if len(t):
                if t[0].childNodes:
                    d[p] = t[0].firstChild.nodeValue
                else:
                    d[p] = None
            else:
                d[p] = None
        parsed_dict[d['id']] = d
    return parsed_dict
749177
def fetch_pdb(self, pdb_code):
        
        self.pdb_path, self.pdb_text = self._fetch_pdb(pdb_code)
        self._df = self._construct_df(pdb_lines=self.pdb_text.splitlines(True))
        return self
112485
def xml_get_tag(xml, tag, parent_tag=None, multi_line=False):
    
    expr_str = '[<:]' + tag + '.*?>(?P<matched_text>.+?)<'
    if parent_tag:
        expr_str = '[<:]' + parent_tag + '.*?>.*?' + expr_str
    expr = re.compile(expr_str, re.DOTALL | re.IGNORECASE)
    if multi_line:
        return expr.findall(xml)
    else:
        if expr.search(xml):
            return expr.search(xml).group('matched_text').strip()
        else:
            return None
920982
def retrieve(pdb_id, cache_dir = None, acceptable_sequence_percentage_match = 70.0, require_uniprot_residue_mapping = True, bio_cache = None):
        '''
        '''

        pdb_contents = None
        xml_contents = None
        pdb_id = pdb_id.upper()

        l_pdb_id = pdb_id.lower()

        if len(pdb_id) != 4 or not pdb_id.isalnum():
            raise Exception("Bad PDB identifier '%s'." % pdb_id)

        if bio_cache:
            pdb_contents = bio_cache.get_pdb_contents(pdb_id)
            xml_contents = bio_cache.get_sifts_xml_contents(pdb_id)

        if cache_dir:
            if not pdb_contents:
                # Check to see whether we have a cached copy of the PDB file
                filename = os.path.join(cache_dir, "%s.pdb" % pdb_id)
                if os.path.exists(filename):
                    pdb_contents = read_file(filename)

            if not xml_contents:
                # Check to see whether we have a cached copy of the XML file
                filename = os.path.join(cache_dir, "%s.sifts.xml.gz" % l_pdb_id)
                if os.path.exists(filename):
                    xml_contents = read_file(filename)

        # Get any missing files from the RCSB and create cached copies if appropriate
        if not pdb_contents:
            pdb_contents = rcsb.retrieve_pdb(pdb_id)
            if cache_dir:
                write_file(os.path.join(cache_dir, "%s.pdb" % pdb_id), pdb_contents)

        if not xml_contents:
            try:
                xml_contents = retrieve_xml(pdb_id, silent = False)
                if cache_dir:
                    write_file(os.path.join(cache_dir, "%s.sifts.xml.gz" % l_pdb_id), xml_contents)
            except FTPException550:
                raise MissingSIFTSRecord('The file "%s.sifts.xml.gz" could not be found on the EBI FTP server.' % l_pdb_id)

        xml_contents = xml_contents

        # Return the object
        handler = SIFTS(xml_contents, pdb_contents, acceptable_sequence_percentage_match = acceptable_sequence_percentage_match, cache_dir = cache_dir, require_uniprot_residue_mapping = require_uniprot_residue_mapping, bio_cache = bio_cache, pdb_id = pdb_id)
        xml.sax.parseString(xml_contents, handler)
        return handler
368674
def obtain_tag(check = nil) 
      segments = []
      if check.blank?
        return nil if params[:slug].blank?
        segments = params[:slug].split('/')
      end

      # get the taxonomy name and search the database for the record with this as its slug
      t = obtain_term_check(check, segments, 'tag')
      t if !t.blank?

    end