Get a value from an RDF triple
165255
def _get_triplet_value(self, graph, identity, rdf_type):
        
        value = graph.value(subject=identity, predicate=rdf_type)
        return value.toPython() if value is not None else value
79044
@Override
    public OWLObject getValue() throws OWLException {
        try {
            return translate(ontopBinding.getValue());
        } catch (OntopResultConversionException e) {
            throw new OntopOWLException(e);
        }
    }
451702
def url_from_rdf(rdf, prop):
    '''
    
    '''
    value = rdf.value(prop)
    if isinstance(value, (URIRef, Literal)):
        return value.toPython()
    elif isinstance(value, RdfResource):
        return value.identifier.toPython()
464072
private static RDFNode toNode(Object value) {
    if (value == null) {
      return null;
    } else if (value instanceof RDFNode) {
      return (RDFNode) value;
    } else if (value instanceof IRI) {
      return new NamedNodeImpl(URI.create(((IRI)value).iri.toString()));
    } else if (value instanceof PlainLiteral) {
      PlainLiteral pl = (PlainLiteral)value;
      String lang = pl.language != null ? pl.language.toString() : null;
      return new PlainLiteralImpl(pl.lexical.toString(), lang);
    } else if (value instanceof TypedLiteral) {
      TypedLiteral tl = (TypedLiteral)value;
      return new TypedLiteralImpl(tl.lexical.toString(), URI.create(tl.datatype.toString()));
    } else if (value instanceof BNode) {
      return new BlankNodeImpl(((BNode)value).label.toString());
    } else {
      // Sherpa passes strings as something other than java.lang.String, so convert.
      if (value instanceof CharSequence) {
        value = value.toString();
      }
      // What's left is a primitive Java type, convert it to an XSD-typed literal.
      // Falls back to xsd:anySimpleType for unrecognized classes
      return Conversions.toLiteral(value);
    }
  }
212303
public static Literal getLiteral(ValueConstant literal)
	{
        Objects.requireNonNull(literal);
		TermType type = literal.getType();
		if (!(type instanceof RDFDatatype))
			// TODO: throw a proper exception
			throw new IllegalStateException("A ValueConstant given to OWLAPI must have a RDF datatype");
		RDFDatatype datatype = (RDFDatatype) type;

		return datatype.getLanguageTag()
				.map(lang -> fact.createLiteral(literal.getValue(), lang.getFullString()))
				.orElseGet(() -> fact.createLiteral(literal.getValue(),
						fact.createIRI(datatype.getIRI().getIRIString())));
	}
1197310
def load_from_rdf_string(self, rdf_str):
        
        self.graph = rdflib.Graph()
        self.graph.parse(data=rdf_str, format='nt')
        self.initialize()
818990
def __get_values(self):
        
        array = self._get_target().getDataArray()
        return tuple(itertools.chain.from_iterable(array))
1055664
def get_properties(cls_def):
    
    # pdb.set_trace()
    prop_list = {prop: value for prop, value in cls_def.items() \
                 if 'rdf_Property' in value.get('rdf_type', "") or \
                 value.get('rdfs_domain')}

    return prop_list
39603
def entityTriples(self, aURI):
        

        aURI = aURI
        qres = self.rdfgraph.query(
              """CONSTRUCT {<%s> ?y ?z }
                 WHERE {
                     { <%s> ?y ?z }
                 }
                 """ % (aURI, aURI ))
        lres = list(qres)

        def recurse(triples_list):
            """ uses the rdflib <triples> method to pull out all blank nodes info"""
            out = []
            for tripl in triples_list:
                if isBlankNode(tripl[2]):
                    # print "blank node", str(tripl[2])
                    temp = [x for x in self.rdfgraph.triples((tripl[2], None, None))]
                    out += temp + recurse(temp)
                else:
                    pass
            return out

        try:
            return lres + recurse(lres)
        except:
            printDebug("Error extracting blank nodes info", "important")
            return lres
600308
private Node objectToRDF(Object item) {
        // convert value object to RDF
        if (isValue(item)) {
            final Object value = ((Map<String, Object>) item).get("@value");
            final Object datatype = ((Map<String, Object>) item).get("@type");

            // convert to XSD datatypes as appropriate
            if (value instanceof Boolean || value instanceof Number) {
                // convert to XSD datatype
                if (value instanceof Boolean) {
                    return new Literal(value.toString(),
                            datatype == null ? XSD_BOOLEAN : (String) datatype, null);
                } else if (value instanceof Double || value instanceof Float
                        || XSD_DOUBLE.equals(datatype)) {
                    if (value instanceof Double && !Double.isFinite((double) value)) {
                        return new Literal(Double.toString((double) value),
                                datatype == null ? XSD_DOUBLE : (String) datatype, null);
                    } else if (value instanceof Float && !Float.isFinite((float) value)) {
                        return new Literal(Float.toString((float) value),
                                datatype == null ? XSD_DOUBLE : (String) datatype, null);
                    } else {
                        // canonical double representation
                        final DecimalFormat df = new DecimalFormat("0.0###############E0");
                        df.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.US));
                        return new Literal(df.format(value),
                                datatype == null ? XSD_DOUBLE : (String) datatype, null);
                    }
                } else {
                    final DecimalFormat df = new DecimalFormat("0");
                    return new Literal(df.format(value),
                            datatype == null ? XSD_INTEGER : (String) datatype, null);
                }
            } else if (((Map<String, Object>) item).containsKey("@language")) {
                return new Literal((String) value,
                        datatype == null ? RDF_LANGSTRING : (String) datatype,
                        (String) ((Map<String, Object>) item).get("@language"));
            } else {
                return new Literal((String) value,
                        datatype == null ? XSD_STRING : (String) datatype, null);
            }
        }
        // convert string/node object to RDF
        else {
            final String id;
            if (isObject(item)) {
                id = (String) ((Map<String, Object>) item).get("@id");
                if (JsonLdUtils.isRelativeIri(id)) {
                    return null;
                }
            } else {
                id = (String) item;
            }
            if (id.indexOf("_:") == 0) {
                // NOTE: once again no need to rename existing blank nodes
                return new BlankNode(id);
            } else {
                return new IRI(id);
            }
        }
    }
693507
def find(value):
        
        value = str(value).lower()
        rtn_dict = RegistryDictionary()
        for attr in dir(MODULE.rdfclass):
            if value in attr.lower():
                try:
                    item = getattr(MODULE.rdfclass, attr)
                    if issubclass(item, RdfClassBase):
                        rtn_dict[attr] = item
                except TypeError:
                    pass
        return rtn_dict
1162739
def rdf_source(self, format="turtle"):
        
        s = self.rdflib_graph.serialize(format=format)
        if isinstance(s, bytes):
            s = s.decode('utf-8')
        return s
355586
def get_sparql_dataframe( self ):
        '''  '''
        self.result = self.g.query(self.query)
        cols = set() # set(['qname'])
        indx = set()
        data = {}
        curr_subj = None # place marker for first subj to be processed
        bindings = []

        for i, binding in enumerate(self.result.bindings):
            subj_binding = binding[rdflib.term.Variable('subj')]
            pred_binding = binding[rdflib.term.Variable('pred')]
            obj_binding  = binding[rdflib.term.Variable('obj')]

            subj = subj_binding
            pred = pred_binding # self.qname(pred_binding) if self.predicate_as_qname else pred_binding
            obj  = obj_binding

            # stops at BNodes; could be exanded here
            if isinstance(subj, BNode):
                continue
            elif isinstance(pred, BNode):
                continue
            elif isinstance(obj, BNode) and obj:
                continue
            # else:
            #     subj = str(subj)
            #     pred = str(pred)
            #     obj  = str(obj)

            cols.add(pred)
            indx.add(subj)
            bindings.append(binding)

        bindings = sorted(bindings, key=lambda k: k[rdflib.term.Variable('subj')])
        df = pd.DataFrame(columns=cols, index=indx)

        for i, binding in enumerate(bindings):

            subj_binding = binding[rdflib.term.Variable('subj')]
            pred_binding = binding[rdflib.term.Variable('pred')]
            obj_binding  = binding[rdflib.term.Variable('obj')]

            subj = subj_binding
            pred = pred_binding # self.qname(pred_binding) if self.qname_predicates else pred_binding
            obj  = obj_binding

            # stops at BNodes; could be exanded here
            if isinstance(subj, BNode):
                continue
            elif isinstance(pred, BNode):
                continue
            elif isinstance(obj, BNode) and obj:
                continue
            # elif self.value_type:
            #     subj = str(subj)
            #     pred = str(pred)
            #     obj  = str(obj)

            if curr_subj == None:
                curr_subj = subj
                if not data.get(subj): # Prepare defaultdict home if it doesn't exist
                    data[subj] = defaultdict(list)
                data[subj][pred].append(obj)
            elif curr_subj != subj:
                curr_subj = subj
                for data_subj, data_pred_objs in data.items():
                    for data_pred, data_objs in data_pred_objs.items():
                        if len(data_objs) == 1: # clean lists of just 1 value
                            data_pred_objs[data_pred] = data_objs[0]
                    df.loc[data_subj] = pd.Series(data_pred_objs)
                data = {}
                if not data.get(subj): # Prepare defaultdict home if it doesn't exist
                    data[subj] = defaultdict(list)
                data[subj][pred].append(obj)
            else:
                if not data.get(subj): # Prepare defaultdict home if it doesn't exist
                    data[subj] = defaultdict(list)
                data[subj][pred].append(obj)

        for data_subj, data_pred_objs in data.items():
            for data_pred, data_objs in data_pred_objs.items():
                if len(data_objs) == 1: # clean lists of just 1 value
                    data_pred_objs[data_pred] = data_objs[0]
            df.loc[data_subj] = pd.Series(data_pred_objs)

        df = df.where((pd.notnull(df)), None) # default Null is fricken Float NaN

        return df
337287
def _check_triple(self, triple):
        """"""
        subj, pred, obj = triple

        if self._should_ignore_predicate(pred):
            log.info("Ignoring triple with predicate '{}'"
                     .format(self._field_name_from_uri(pred)))
            return

        classes = []
        log.warning("Possible member %s found" % pred)

        pred = self._expand_qname(pred)

        if self._namespace_from_uri(pred) not in self.allowed_namespaces:
            log.info("Member %s does not use an allowed namespace", pred)
            return

        instanceof = self._is_instance((subj, pred, obj))
        if type(instanceof) == rt.URIRef:
            instanceof = self._expand_qname(instanceof)

        if hasattr(self.schema_def, "attributes_by_class") and \
           not self.schema_def.attributes_by_class:
            log.info("Parsed ontology not found. Parsing...")
            self.schema_def.parse_ontology()

        class_invalid = self._validate_class(instanceof)
        if class_invalid:
            log.warning("Invalid class %s" % instanceof)
            return class_invalid
        # TODO - the above sometimes fails when a single object has more than
        # one rdfa type (eg <span property="schema:creator rnews:creator"
        # typeof="schema:Person rnews:Person">
        # Graph chooses the type in an arbitrary order, so it's unreliable
        # eg: http://semanticweb.com/the-impact-of-rdfa_b35003

        classes = self._superclasses_for_subject(self.graph, instanceof)
        classes.append(instanceof)

        member_invalid = self._validate_member(pred, classes, instanceof)
        if member_invalid:
            log.warning("Invalid member of class")
            return member_invalid

        dupe_invalid = self._validate_duplication((subj, pred), instanceof)
        if dupe_invalid:
            log.warning("Duplication found")
            return dupe_invalid

        # collect a list of checked attributes
        self.checked_attributes.append((subj, pred))
        log.warning("successfully validated triple, no errors")
        return
395171
protected void readEntityIntoDataset(final IRI graphName, final RDFSyntax syntax,
            final TrellisDataset dataset) {
        try (final InputStream input = entity) {
            getServices().getIOService().read(input, syntax, getIdentifier())
                .map(skolemizeTriples(getServices().getResourceService(), getBaseUrl()))
                .filter(triple -> !RDF.type.equals(triple.getPredicate())
                        || !triple.getObject().ntriplesString().startsWith("<" + LDP.getNamespace()))
                .filter(triple -> !LDP.contains.equals(triple.getPredicate())).map(triple ->
                        rdf.createQuad(graphName, triple.getSubject(), triple.getPredicate(), triple.getObject()))
                .forEachOrdered(dataset::add);
        } catch (final RuntimeTrellisException ex) {
            throw new BadRequestException("Invalid RDF content: " + ex.getMessage());
        } catch (final IOException ex) {
            throw new WebApplicationException("Error processing input: " + ex.getMessage());
        }
    }
371016
def rdf(dataset):
    ''''''
    format = RDF_EXTENSIONS[negociate_content()]
    url = url_for('datasets.rdf_format', dataset=dataset.id, format=format)
    return redirect(url)
504981
function getResult(attrNode, dataSourceName, context) {
    const resultId = attrNode.dataSources[dataSourceName].resultId;
    if (typeof resultId === 'undefined') {
        const attrPath = context.attrPath.length > 0 ? context.attrPath.join('.') : '{root}';
        throw new ImplementationError(`Result for "${attrPath}" (DataSource "${dataSourceName}") missing`);
    }
    return context.rawResults[resultId];
}