try to select an ontology NP: the actual load from FS is in <_load_ontology>
5552
def _select_ontology(self, line):
        
        try:
            var = int(line)  # it's a string
            if var in range(1, len(self.all_ontologies)+1):
                self._load_ontology(self.all_ontologies[var-1])
        except ValueError:
            out = []
            for each in self.all_ontologies:
                if line in each:
                    out += [each]
            choice = self._selectFromList(out, line, "ontology")
            if choice:
                self._load_ontology(choice)
1046582
def ontologyShapeTree(self):
        
        treedict = {}
        if self.all_shapes:
            treedict[0] = self.toplayer_shapes
            for element in self.all_shapes:
                if element.children():
                    treedict[element] = element.children()
            return treedict
        return treedict
361000
def get_pickled_ontology(filename):
	
	pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle"
	if GLOBAL_DISABLE_CACHE:
		printDebug("WARNING: DEMO MODE cache has been disabled in __init__.py ==============", "red")
	if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE:
		try:
			return cPickle.load(open(pickledfile, "rb"))
		except:
			print("** WARNING: Cache is out of date ** ...recreating it... ")
			return None
	else:
		return None
948046
def in_general_ns(uri):
    """"""
    RDFuri = RDF.uri
    RDFSuri = RDFS.uri

    for ns in (RDFuri, RDFSuri, OWL, SKOS, DC):
        if uri.startswith(ns):
            return True
    return False
375453
def formatSubclassOf(fmt, cls, ontology, visited):
    # type: (Text, Text, Optional[Graph], Set[Text]) -> bool
    """"""

    if URIRef(fmt) == URIRef(cls):
        return True

    if ontology is None:
        return False

    if fmt in visited:
        return False

    visited.add(fmt)

    uriRefFmt = URIRef(fmt)

    for s, p, o in ontology.triples((uriRefFmt, RDFS.subClassOf, None)):
        # Find parent classes of `fmt` and search upward
        if formatSubclassOf(o, cls, ontology, visited):
            return True

    for s, p, o in ontology.triples((uriRefFmt, OWL.equivalentClass, None)):
        # Find equivalent classes of `fmt` and search horizontally
        if formatSubclassOf(o, cls, ontology, visited):
            return True

    for s, p, o in ontology.triples((None, OWL.equivalentClass, uriRefFmt)):
        # Find equivalent classes of `fmt` and search horizontally
        if formatSubclassOf(s, cls, ontology, visited):
            return True

    return False
12516
def load_facts(self, facts):
        
        facts = facts.encode()

        if os.path.exists(facts):
            ret = lib.EnvLoadFacts(self._env, facts)
            if ret == -1:
                raise CLIPSError(self._env)
        else:
            ret = lib.EnvLoadFactsFromString(self._env, facts, -1)
            if ret == -1:
                raise CLIPSError(self._env)

        return ret
310791
def getOntoCategory(curie, alwaysFetch=False):
    
    
    fileName = os.path.join(os.path.dirname(__file__), "ontoCategories.bin") 
    if not alwaysFetch:
        try:
            with open(fileName, "rb") as catFile:
                ontoCat = pickle.load(catFile)
                
            if curie in ontoCat:
                return ontoCat[curie]                
        except:
            ontoCat = {}
    
    base = bases["KS"] 
    query = base + "/vocabulary/id/" + curie
    response = requests.get(query)
    if not response.ok:
        ontoCat[curie] = []
    else:

        try:
            concepts = response.json()
        except ValueError:
            print(query)
            print(response)
            raise
        
        if len(concepts["categories"]):
            ontoCat[curie] = concepts["categories"]
        else:
            ontoCat[curie] = []


    try:
        with open(fileName, "wb") as catFile:
            pickle.dump(ontoCat, catFile)
    except:
        pass        

    return ontoCat[curie]
738397
def getOntology(self, id=None, uri=None, match=None):
        

        if not id and not uri and not match:
            return None

        if type(id) == type("string"):
            uri = id
            id = None
            if not uri.startswith("http://"):
                match = uri
                uri = None
        if match:
            if type(match) != type("string"):
                return []
            res = []
            for x in self.ontologies:
                if match.lower() in x.uri.lower():
                    res += [x]
            return res
        else:
            for x in self.ontologies:
                if id and x.id == id:
                    return x
                if uri and x.uri.lower() == uri.lower():
                    return x
            return None
1084837
private Model initModel() {
        OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
        try {
            schemaReader.read(m);
        } catch (RdfReaderException e) {
            log.error("Cannot load ontology: {} ", getSchema(), e);
        }
        return m;
    }
340104
def load(self, **kwargs):
        """"""
        if 'name' in kwargs:
            if 'ldns' not in kwargs['name'] or 'server' not in kwargs['name']:
                raise InvalidName("Topology record name should contain both "
                                  "'ldns', 'server' keywords with their "
                                  "proper arguments")
        kwargs['transform_name'] = True

        return self._load(**kwargs)
603010
def ns(self):
        
        ret = libxml2mod.xmlNodeGetNs(self._o)
        if ret is None:return None
        __tmp = xmlNs(_obj=ret)
        return __tmp
1268306
def _discover_ontology(ontology_path):
    
    last_part = os.path.split(os.path.abspath(ontology_path))[1]
    possible_patterns = [last_part, last_part.lower()]
    if not last_part.endswith('.rdf'):
        possible_patterns.append(last_part + '.rdf')
    places = [os.path.join(current_app.instance_path, "classifier"),
              os.path.abspath('.'),
              os.path.join(os.path.dirname(__file__), "classifier")]

    workdir = current_app.config.get('CLASSIFIER_WORKDIR')
    if workdir:
        places.append(workdir)

    current_app.logger.debug(
        "Searching for taxonomy using string: %s" % last_part)
    current_app.logger.debug("Possible patterns: %s" % possible_patterns)
    for path in places:
        try:
            if os.path.isdir(path):
                current_app.logger.debug("Listing: %s" % path)
                for filename in os.listdir(path):
                    for pattern in possible_patterns:
                        filename_lc = filename.lower()
                        if pattern == filename_lc and\
                                os.path.exists(os.path.join(path, filename)):
                            filepath = os.path.abspath(os.path.join(path,
                                                                    filename))
                            if (os.access(filepath, os.R_OK)):
                                current_app.logger.debug(
                                    "Found taxonomy at: {0}".format(filepath))
                                return filepath
                            else:
                                current_app.logger.warning(
                                    'Found taxonomy at: {0}, but it is'
                                    ' not readable. Continue '
                                    'searching...'.format(
                                        filepath
                                    )
                                )
        except OSError as os_error_msg:
            current_app.logger.exception(
                'OS Error when listing path "{0}": {1}'.format(
                    str(path), str(os_error_msg))
            )
    current_app.logger.debug(
        "No taxonomy with pattern '{0}' found".format(ontology_path))
636318
private OWLOntology loadOntologyFromURI(URI uri) throws OWLIOException
    {
        try
        {
            return owlOntologyManager.loadOntologyFromOntologyDocument(IRI.create(uri));
        } catch (OWLOntologyCreationException ex)
        {
            throw new OWLIOException(ioErrorMsg, ex);
        }
    }
452645
def from_any(cls, obj, bucket):
        
        if isinstance(obj, cls):
            return cls(obj.raw)

        return cls({
            'namespace_id': 'default',
            'keyspace_id': bucket,
            'name': obj if obj else N1QL_PRIMARY_INDEX,
            'using': 'gsi'
        })
1128645
def get_random_ontology(TOP_RANGE=10, pattern=""):
    """"""
    choices = get_localontologies(pattern=pattern)
    try:
        ontouri = choices[random.randint(0, TOP_RANGE)]  # [0]
    except:
        ontouri = choices[0]
    print("Testing with URI: %s" % ontouri)
    g = get_pickled_ontology(ontouri)
    if not g:
        g = do_pickle_ontology(ontouri)
    return ontouri, g
1174479
def _get_remote_ontology(onto_url, time_difference=None):
    
    if onto_url is None:
        return False

    dl_dir = os.path.join(
        current_app.config["CLASSIFIER_WORKDIR"] or tempfile.gettempdir(),
        "classifier"
    )
    if not os.path.exists(dl_dir):
        os.makedirs(dl_dir)

    local_file = dl_dir + os.path.basename(onto_url)
    remote_modif_time = _get_last_modification_date(onto_url)
    try:
        local_modif_seconds = os.path.getmtime(local_file)
    except OSError:
        # The local file does not exist. Download the ontology.
        download = True
        current_app.logger.info("The local ontology could not be found.")
    else:
        local_modif_time = datetime(*time.gmtime(local_modif_seconds)[0:6])
        # Let's set a time delta of 1 hour and 10 minutes.
        time_difference = time_difference or timedelta(hours=1, minutes=10)
        download = remote_modif_time > local_modif_time + time_difference
        if download:
            current_app.logger.info(
                "The remote ontology '{0}' is more recent "
                "than the local ontology.".format(onto_url)
            )

    if download:
        if not _download_ontology(onto_url, local_file):
            current_app.logger.warning(
                "Error downloading the ontology from: {0}".format(onto_url)
            )

    return local_file
811514
def NS(domain, resolve=True, nameserver=None):
    '''
    

    '''
    if _has_dig():
        return __salt__['dig.NS'](domain, resolve, nameserver)

    return 'This function requires dig, which is not currently available'