2015-06-04: removed sparql 1.1 queries
        2015-06-03: analogous to get classes

        # instantiate properties making sure duplicates are pruned
        # but the most specific rdftype is kept
        # eg OWL:ObjectProperty over RDF:property
336977
def build_properties(self, hide_implicit_preds=True):
        
        self.all_properties = []  # @todo: keep adding?
        self.all_properties_annotation = []
        self.all_properties_object = []
        self.all_properties_datatype = []

        qres = self.sparqlHelper.getAllProperties(hide_implicit_preds)
        # print("rdflib query done")

        for candidate in qres:

            test_existing_prop = self.get_property(uri=candidate[0])
            if not test_existing_prop:
                # create it
                self.all_properties += [OntoProperty(candidate[0], candidate[1], self.namespaces)]
            else:
                # update it
                if candidate[1] and (test_existing_prop.rdftype == rdflib.RDF.Property):
                    test_existing_prop.rdftype = inferMainPropertyType(candidate[1])
        # print("properties created")

        # add more data
        for aProp in self.all_properties:
            # print("enriching prop..", aProp)
            if aProp.rdftype == rdflib.OWL.DatatypeProperty:
                self.all_properties_datatype += [aProp]
            elif aProp.rdftype == rdflib.OWL.AnnotationProperty:
                self.all_properties_annotation += [aProp]
            elif aProp.rdftype == rdflib.OWL.ObjectProperty:
                self.all_properties_object += [aProp]
            else:
                pass

            aProp.triples = self.sparqlHelper.entityTriples(aProp.uri)
            aProp._buildGraph()  # force construction of mini graph

            # attach to an ontology [2015-06-15: no property type distinction yet]
            for uri in aProp.getValuesForProperty(rdflib.RDFS.isDefinedBy):
                onto = self.get_ontology(uri=str(uri))
                if onto:
                    onto.all_properties += [aProp]
                    aProp.ontology = onto

            self.__buildDomainRanges(aProp)

            # add direct Supers
            directSupers = self.sparqlHelper.getPropDirectSupers(aProp.uri)

            for x in directSupers:
                superprop = self.get_property(uri=x[0])
                # note: extra condition to avoid recursive structures
                if superprop and superprop.uri != aProp.uri:
                    aProp._parents.append(superprop)

                    # add inverse relationships (= direct subs for superprop)
                    if aProp not in superprop.children():
                        superprop._children.append(aProp)

        # sort alphabetically
        self.all_properties = sorted(self.all_properties, key=lambda x: x.qname)

        # computer top layer for properties
        # print("calc toplayer")
        exit = []
        for c in self.all_properties:
            if not c.parents():
                exit += [c]
        self.toplayer_properties = exit
961881
def primitive_datatype(self, t: URIRef) -> Optional[URIRef]:
        
        for sco in self._o.objects(t, RDFS.subClassOf):
            sco_type = self._o.value(sco, RDF.type)
            sco_prop = self._o.value(sco, OWL.onProperty)
            if sco_type == OWL.Restriction and sco_prop == FHIR.value:
                # The older versions of fhir.ttl (incorrectly) referenced the datatype directly
                restriction_type = self._o.value(sco, OWL.allValuesFrom)
                if not restriction_type:
                    restriction_dt_entry = self._o.value(sco, OWL.someValuesFrom)
                    restriction_type = self._o.value(restriction_dt_entry, OWL.onDatatype)
                return restriction_type
        return None
738727
def transform_concepts(rdf, typemap):
    """"""

    # find out all the types used in the model
    types = set()
    for s, o in rdf.subject_objects(RDF.type):
        if o not in typemap and in_general_ns(o):
            continue
        types.add(o)

    for t in types:
        if mapping_match(t, typemap):
            newval = mapping_get(t, typemap)
            newuris = [v[0] for v in newval]
            logging.debug("transform class %s -> %s", t, str(newuris))
            if newuris[0] is None:  # delete all instances
                for inst in rdf.subjects(RDF.type, t):
                    delete_uri(rdf, inst)
                delete_uri(rdf, t)
            else:
                replace_object(rdf, t, newuris, predicate=RDF.type)
        else:
            logging.info("Don't know what to do with type %s", t)
1009029
def predicate
      if instance_variable_defined?(:@predicate)
        @predicate
      else
        rdf_node = Redland.librdf_statement_get_predicate(rdf_statement)
        @predicate = rdf_node.null? ? nil : Node.new(rdf_node)
      end
    end
210457
def transform_deprecated_concepts(rdf, cs):
    """"""

    deprecated_concepts = []

    for conc in rdf.subjects(RDF.type, SKOSEXT.DeprecatedConcept):
        rdf.add((conc, RDF.type, SKOS.Concept))
        rdf.add((conc, OWL.deprecated, Literal("true", datatype=XSD.boolean)))
        deprecated_concepts.append(conc)

    if len(deprecated_concepts) > 0:
        ns = cs.replace(localname(cs), '')
        dcs = create_concept_scheme(
            rdf, ns, 'deprecatedconceptscheme')
        logging.debug("creating deprecated concept scheme %s", dcs)
        for conc in deprecated_concepts:
            rdf.add((conc, SKOS.inScheme, dcs))
1144285
def getAllClasses(self, hide_base_schemas=True):
        
        query = """SELECT DISTINCT ?x ?c
                 WHERE {
                         {
                             { ?x a owl:Class }
                             union
                             { ?x a rdfs:Class }
                             union
                             { ?x rdfs:subClassOf ?y }
                             union
                             { ?z rdfs:subClassOf ?x }
                             union
                             { ?y rdfs:domain ?x }
                             union
                             { ?y rdfs:range ?x }
                             # union
                             # { ?y rdf:type ?x }
                         } .

                         ?x a ?c

                    %s

                 }
                 ORDER BY  ?x
                 """
        if hide_base_schemas:
            query = query %  """FILTER(
                     !STRSTARTS(STR(?x), "http://www.w3.org/2002/07/owl")
                     && !STRSTARTS(STR(?x), "http://www.w3.org/1999/02/22-rdf-syntax-ns")
                     && !STRSTARTS(STR(?x), "http://www.w3.org/2000/01/rdf-schema")
                     && !STRSTARTS(STR(?x), "http://www.w3.org/2001/XMLSchema")
                     && !STRSTARTS(STR(?x), "http://www.w3.org/XML/1998/namespace")
                     && (!isBlank(?x))
                      ) ."""
        else:
            query = query % ""

        qres = self.rdfgraph.query(query)
        return list(qres)
1063767
private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) {
		Set<Class<?>> entities = new HashSet<Class<?>>();
		//first build the "entities" set containing all indexed subtypes of "selection".
		for ( Class<?> entityType : selection ) {
			IndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( IndexedTypeSets.fromClass( entityType ) );
			if ( targetedClasses.isEmpty() ) {
				String msg = entityType.getName() + " is not an indexed entity or a subclass of an indexed entity";
				throw new IllegalArgumentException( msg );
			}
			entities.addAll( targetedClasses.toPojosSet() );
		}
		Set<Class<?>> cleaned = new HashSet<Class<?>>();
		Set<Class<?>> toRemove = new HashSet<Class<?>>();
		//now remove all repeated types to avoid duplicate loading by polymorphic query loading
		for ( Class<?> type : entities ) {
			boolean typeIsOk = true;
			for ( Class<?> existing : cleaned ) {
				if ( existing.isAssignableFrom( type ) ) {
					typeIsOk = false;
					break;
				}
				if ( type.isAssignableFrom( existing ) ) {
					toRemove.add( existing );
				}
			}
			if ( typeIsOk ) {
				cleaned.add( type );
			}
		}
		cleaned.removeAll( toRemove );
		log.debugf( "Targets for indexing job: %s", cleaned );
		return IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) );
	}
931849
def range_is_obj(rng, rdfclass):
    
    if rng == 'rdfs_Literal':
        return False
    if hasattr(rdfclass, rng):
        mod_class = getattr(rdfclass, rng)
        for item in mod_class.cls_defs['rdf_type']:
            try:
                if issubclass(getattr(rdfclass, item),
                              rdfclass.rdfs_Literal):
                    return False
            except AttributeError:
                pass
        if isinstance(mod_class, rdfclass.RdfClassMeta):
            return True
    return False
425608
def _GetSqliteSchema(self, proto_struct_class, prefix=""):
    """"""
    schema = collections.OrderedDict()
    for type_info in proto_struct_class.type_infos:
      if type_info.__class__ is rdf_structs.ProtoEmbedded:
        schema.update(
            self._GetSqliteSchema(
                type_info.type, prefix="%s%s." % (prefix, type_info.name)))
      else:
        field_name = utils.SmartStr(prefix + type_info.name)
        schema[field_name] = Rdf2SqliteAdapter.GetConverter(type_info)
    return schema
1184906
def transform_sparql_update(rdf, update_query):
    """"""

    logging.debug("performing SPARQL Update transformation")

    if update_query[0] == '@':  # actual query should be read from file
        update_query = file(update_query[1:]).read()

    logging.debug("update query: %s", update_query)
    rdf.update(update_query)
536736
def _get_rdfclass(self, class_type, **kwargs):
        
        def select_class(class_name):
            """ finds the class in the rdfclass Module"""
            try:
                return getattr(MODULE.rdfclass, class_name.pyuri)
            except AttributeError:
                return RdfClassBase

        if kwargs.get("def_load"):
            return RdfClassBase

        if isinstance(class_type[self.omap], list):
            bases = [select_class(class_name)
                     for class_name in class_type[self.omap]]
            bases = [base for base in bases if base != RdfClassBase]
            if len(bases) == 0:
                return RdfClassBase
            elif len(bases) == 1:
                return bases[0]
            else:
                bases = remove_parents(bases)
                if len(bases) == 1:
                    return bases[0]
                else:
                    name = "_".join(sorted(class_type[self.omap]))
                    # if the the class has already been created return it
                    if hasattr(MODULE.rdfclass, name):
                        return getattr(MODULE.rdfclass, name)
                    new_class = type(name,
                                     tuple(bases),
                                     {})
                    new_class.hierarchy = list_hierarchy(class_type[self.omap][0],
                                                         bases)
                    new_class.class_names = sorted([base.__name__ \
                            for base in bases \
                            if base not in [RdfClassBase, dict]])
                    setattr(MODULE.rdfclass, name, new_class)
                    return new_class
        else:
            return select_class(class_type[self.omap])
456371
def getClassDirectSubs(self, aURI):
        
        aURI = aURI
        qres = self.rdflib_graph.query("""SELECT DISTINCT ?x
                 WHERE {
                     { ?x rdfs:subClassOf <%s> }
                     FILTER (!isBlank(?x))
                 }
                 """ % (aURI))
        return list(qres)
1192900
def link_property(prop, cls_object):
    
    register = False
    cls_name = cls_object.__name__
    if cls_name and cls_name != 'RdfBaseClass':
        new_name = "%s_%s" % (prop._prop_name, cls_name)
    else:
        new_name = prop._prop_name

    new_prop = types.new_class(new_name,
                               (prop,),
                               {'metaclass': RdfLinkedPropertyMeta,
                                'cls_name': cls_name,
                                'prop_name': prop._prop_name,
                                'linked_cls': cls_object})
    return new_prop
1295962
private void removePropertyDocs(
      final Node objLit, PolymerClassDefinition.DefinitionType defType) {
    for (MemberDefinition prop :
        PolymerPassStaticUtils.extractProperties(
            objLit,
            defType,
            compiler,
            /** constructor= */
            null)) {
      prop.name.removeProp(Node.JSDOC_INFO_PROP);
    }
  }
812589
def object
      if instance_variable_defined?(:@object)
        @object
      else
        rdf_node = Redland.librdf_statement_get_object(rdf_statement)
        @object = rdf_node.null? ? nil : Node.new(rdf_node)
      end
    end
531386
def transform_aggregate_concepts(rdf, cs, relationmap, aggregates):
    """"""

    if not aggregates:
        logging.debug("removing aggregate concepts")

    aggregate_concepts = []

    relation = relationmap.get(
        OWL.equivalentClass, [(OWL.equivalentClass, False)])[0][0]
    for conc, eq in rdf.subject_objects(relation):
        eql = rdf.value(eq, OWL.unionOf, None)
        if eql is None:
            continue
        if aggregates:
            aggregate_concepts.append(conc)
            for item in rdf.items(eql):
                rdf.add((conc, SKOS.narrowMatch, item))
        # remove the old equivalentClass-unionOf-rdf:List structure
        rdf.remove((conc, relation, eq))
        rdf.remove((eq, RDF.type, OWL.Class))
        rdf.remove((eq, OWL.unionOf, eql))
        # remove the rdf:List structure
        delete_uri(rdf, eql)
        if not aggregates:
            delete_uri(rdf, conc)

    if len(aggregate_concepts) > 0:
        ns = cs.replace(localname(cs), '')
        acs = create_concept_scheme(rdf, ns, 'aggregateconceptscheme')
        logging.debug("creating aggregate concept scheme %s", acs)
        for conc in aggregate_concepts:
            rdf.add((conc, SKOS.inScheme, acs))
593022
private SimpleGraphResultSet executeDescribeQuery(DescribeQuery inputQuery)
			throws OntopReformulationException, OntopResultConversionException, OntopConnectionException,
			OntopQueryEvaluationException {

		ImmutableSet<String> constants = extractDescribeQueryConstants(inputQuery);

		SimpleGraphResultSet describeResultSet = null;

		try {
			// execute describe <uriconst> in subject position
			for (String constant : constants) {
				// for each constant we execute a construct with
				// the uri as subject, and collect the results
				String str = SPARQLQueryUtility.getConstructSubjQuery(constant);
				ConstructQuery constructQuery = inputQueryFactory.createConstructQuery(str);

				SimpleGraphResultSet set = executeInThread(constructQuery, this::executeDescribeConstructQuery);
				if (describeResultSet == null) { // just for the first time
					describeResultSet = set;
				} else if (set != null) {
					// 2nd and manyth times execute, but collect result into one object
					while (set.hasNext())
						describeResultSet.addNewResult(set.next());
				}
			}
			// execute describe <uriconst> in object position
			for (String constant : constants) {
				String str = SPARQLQueryUtility.getConstructObjQuery(constant);

				ConstructQuery constructQuery = inputQueryFactory.createConstructQuery(str);
				SimpleGraphResultSet set = executeInThread(constructQuery, this::executeDescribeConstructQuery);

				if (describeResultSet == null) { // just for the first time
					describeResultSet = set;
				} else if (set != null) {
					while (set.hasNext())
						describeResultSet.addNewResult(set.next());
				}
			}
			// Exception is re-cast because not due to the initial input query
		} catch (OntopInvalidInputQueryException e) {
			throw new OntopReformulationException(e);
		}
		return describeResultSet;
	}