I have a particular Class URI for which I am trying to get an OntClass. The model is a regular model.
I wrote some code to find out whether the right statements were in the model, and it seems that they are so I can't understand why it won't let me view this as an OntClass. (tblURI is a String passed as a method parameter)
Resource tblR = m.createResource(tblURI);
List<Statement> prp = tblR.listProperties().toList();
for(Statement s : prp)
System.out.println(s);
System.out.println(tblR.canAs(OntClass.class));
OntClass tbl = tblR.as(OntClass.class);
This is the output:
[kps:datasource/EnsembleMS#translation_stable_id, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2002/07/owl#Class]
[kps:datasource/EnsembleMS#translation_stable_id, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2000/01/rdf-schema#Class]
[kps:datasource/EnsembleMS#translation_stable_id, http://www.w3.org/2000/01/rdf-schema#isDefinedBy, kps:datasource/EnsembleMS]
[kps:datasource/EnsembleMS#translation_stable_id, http://www.w3.org/2000/01/rdf-schema#label, "translation_stable_id"]
false
com.hp.hpl.jena.ontology.ConversionException: Cannot convert node kps:datasource/EnsembleMS#translation_stable_id to OntClass: it does not have rdf:type owl:Class or equivalent
at com.hp.hpl.jena.ontology.impl.OntClassImpl$1.wrap(OntClassImpl.java:81)
at com.hp.hpl.jena.enhanced.EnhNode.convertTo(EnhNode.java:155)
at com.hp.hpl.jena.enhanced.EnhNode.convertTo(EnhNode.java:34)
at com.hp.hpl.jena.enhanced.Polymorphic.asInternal(Polymorphic.java:66)
at com.hp.hpl.jena.enhanced.EnhNode.as(EnhNode.java:110)
at com.KPS.myApp.exampleMethod(myApp.java:123)
Why is it throwing an exception and how can I get an OntClass for the resource with uri tblURI?
Thanks for any pointers
You don't say what kind of model m is. In particular, if m was created with the RDFS language profile, the OntModel will be looking for an rdf:type of rdfs:Class, not owl:Class. If that's not the issue, then a complete minimal (i.e. runnable) example would help.
By the way, there's another problem I can see: resource URI's in the model should be in absolute form, not abbreviated form. The fact that you've got q-name URI's in your model, like kps:datasource/EnsembleMS#translation_stable_id, suggest that something is going wrong with your prefix handling. That won't by itself cause the problem you've reported, but it's a red flag to investigate.
Update
Responding to questions:
yes, you need to be using an OntModel, otherwise it's not possible for the OntClass to know which langauge profile to use. Either create the model as OntModel in the first place:
OntModel m = modelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
or wrap your plain model as an OntModel:
OntModel om = modelFactory.createOntologyModel( OntModelSpec.OWM_MEM, m );
Of course, you many use any of the model specifications, as you please, OWL_MEM is just one option.
createResource will not expand prefixes for you. So, you should expand them yourself before creating the resource:
m.createResource( m.expandPrefix( "foo:bar" ) );
Of course, this requires the prefix "foo" to be registered as a prefix. This happens automatically if you read an RDF document that defines the prefix in its syntax, but otherwise can be done manually with setNsPrefix.
Related
I have a Modelica simulation model composed by some models connected to each other.
I would like to save some data of some of the model instances in my simulation model at a given time using the built-in function
Modelica.Utilities.Streams.writeRealMatrix();
To be sure which instance writes which file, I would like to include the instance name in the writeRealMatrix() output file name, e.g., in case I have an instance called myModel, using the name:
myModelOut.mat.
To do this, I need a way to get the instance name and put it into a string.
I know that Modelica allows using instance names in model icons, through a Text record, using the keyword "%name", but I don't know how to do the same in a regular string (I mean outside any record or icon annotation).
Does anyone know if there is a way to do this?
Thank you in advance.
In your case I think the function getInstanceName() should be a good approach. Using it will need you to edit the model, but given you are writing information from with the class using writeRealMatrix() this shouldn't be an issue.
I have created a small example package with a constant block, that stores its name into final parameter of type String. The example then writes the string to the console at the termination of the simulation:
package GetName
block ConstantNamed "Generate constant signal of type Real"
extends Modelica.Blocks.Sources.Constant;
final parameter String name = getInstanceName();
end ConstantNamed;
model Example
extends Modelica.Icons.Example;
ConstantNamed myConst(k=23) annotation (Placement(transformation(extent={{-10,-10},{10,10}})));
equation
when terminal() then
Modelica.Utilities.Streams.print("### Here is the models full path: '" + myConst.name + "'");
end when;
end Example;
annotation (uses(Modelica(version="4.0.0")));
end GetName;
This should result in a simulation log containing the path of the instance of ConstantNamed, which is Example.myConst:
Note: The print function is added to Example in the above code. It could be added to the ConstantNamed as well. For the case from the question, the print shouldn't be necessary anyways...
Besides that, in case you are using Dymola, there is the ModelManagement library, which contains some functions like ModelManagement.Structure.AST.Classes.ComponentsInClass. But these are more intended to be applied from "outside" to a given model.
I was working through some code, and noticed:
return new Uri(host: server, path: apiPath, query: query, queryParameters: queryParams);
This code is executed regularly throughout the application, and the only difference was queryParams. So i printed it out:
{Id:[1234], enabled:false}
shows it is a key:value set of: Id:List, enabled:boolean.
The stack trace i get is:
which shows the map and then the trace. #6 points to the above line.
It is looking at false... something with iterating false is what breaks this.
When dealing with the URI and query parameters, it is looking for numerics, lists, and strings but not booleans. In order to resolve this and allow it to function correctly, you will need to do:
{"enabled": false.toString()}
// or
{"enabled": "false"}
and the uri class will set the query parameter accordingly.
The Uri class is located in core library for Dart. When we are using it, we are passing in the created Uri object into an action for a client class,
Client client = new BrowserClient();
which accepts the url as a part of the parameters.
While looking at the errors above though, the Uri class ultimately is unable to properly parse a false value to an accepted value.
When looking at the Code Docs for Uri as per the Dart languages: https://api.dartlang.org/dev/1.25.0-dev.7.0/dart-core/Uri/Uri.html
The query component is set through either query or queryParameters. When query is used, the provided string should be a valid URI query, but invalid characters, other than general delimiters, will be escaped if necessary. When queryParameters is used the query is built from the provided map. Each key and value in the map is percent-encoded and joined using equal and ampersand characters. A value in the map must be either a string, or an Iterable of strings, where the latter corresponds to multiple values for the same key.
Which makes sense to say all values must be String or an Iterable of Strings. The only thing which I cant figure out is that in Dartpad, true and false have toString functions, and yet you can also pass numerics in there.
The only conclusion is that while it accepts Strings and Iterables of Strings, it will also parse ints and other numerics because they will explicitly check for that type as it is common to see in URI.
One would think that the URI would understand booleans since those are also common place, but that is yet to be seen since I cant take an explicit look at the source code for dartlang. I did however manage to look at the source code for it and narrowed it down. writeComponent points to _Uri._uriEncode but when looking at that function, there is no code as much as just a definition.
HTH.
I have (among others) two domain classes:
class Course {
String name
...
}
class Round {
Course course
String startweek // e.g. '201504'
String endweek // e.g. '201534'
String applcode // e.g. 'DA542133'
...
}
Application codes may be issued at several occasions and are then concatenated with 'applcode's separated by blanks. As I am streaming and parsing large amount of data (in XML format) from different sources, I might stumble on the same data from several sources, so I look up the records in the database to see if I may discard the rest of the stream or not. This is possible as the outermost tag contains data stating the above declared attributes. I search the database using:
def c = Course.findByName(name);
def found =
Round.findByCourseAndStartweekAndEndweekAndApplcodeLike(c, sw, ew,'%'+appc+'%')
where the parameters are fairly obvious and which works well but I find these 'findByBlaAndBlablaAnd...' very long and not very readable. My aim here is to find some more readable and thereby more comprehensible method. I have started to read about Criteria and HQL but I think one example or two would help me on the way.
Edit after reading the pages on the link provided by #injecteer:
It was fairly simple to make out the query above. I have worse thing to figure out but the query in my example became with criteria:
def found = Round.createCriteria().get {
eq ('course', c)
eq ('startweek', sw)
eq ('endweek', ew)
like ('applcode', '%'+appc+'%')
};
Much easier to read and understand than the original question.
I am trying to use Jena framework to edit an existing ontology built with Protoge 4.2. i.e. to change property values or add individuals or classes and then do reasoning. Assume in the ontology we have a rule such that: hasAge(?p,?age)^swrlb:greaterThan(?age,18)->Adult(?p). I would like to be able to change hasAge property on Jena side and see if someone is an Adult or not. Can you please provide me some sample code on this? Any help is appreciated.
Assuming that :
you know how to populate your model by reading in the ontology that you built
You have put Pellet on the classpath
You replace the IRI's below with those from your domain
You have assertions enabled
The following code snippet will add an age to an individual x-test://individual and assert that the property that would be introduced by SWIRL is satisfied.
// create an empty ontology model using Pellet spec
final OntModel model = ModelFactory.createOntologyModel( PelletReasonerFactory.THE_SPEC );
// read the file
model.read( ont );
// Grab a resource and and property, and then set the property on that individual
final Resource Adult = ResourceFactory.createResource("x-domain://Adult");
final Property hasAge = ResourceFactory.createProperty("x-domain://hasAge");
final Resource res = model.createResource("x-test://individual");
res.addLiteral(hasAge, 19);
// Test that the swirl rule has executed
assert( res.hasProperty(RDF.type, Adult) );
I'm working on an application at the moment in ASP.NET MVC which has a number of look-up tables, all of the form
LookUp {
Id
Text
}
As you can see, this just maps the Id to a textual value. These are used for things such as Colours. I now have a number of these, currently 6 and probably soon to be more.
I'm trying to put together an API that can be used via AJAX to allow the user to add/list/remove values from these lookup tables, so for example I could have something like:
http://example.com/Attributes/Colours/[List/Add/Delete]
My current problem is that clearly, regardless of which lookup table I'm using, everything else happens exactly the same. So really there should be no repetition of code whatsoever.
I currently have a custom route which points to an 'AttributeController', which figures out the attribute/look-up table in question based upon the URL (ie http://example.com/Attributes/Colours/List would want the 'Colours' table). I pass the attribute (Colours - a string) and the operation (List/Add/Delete), as well as any other parameters required (say "Red" if I want to add red to the list) back to my repository where the actual work is performed.
Things start getting messy here, as at the moment I've resorted to doing a switch/case on the attribute string, which can then grab the Linq-to-Sql entity corresponding to the particular lookup table. I find this pretty dirty though as I find myself having to write the same operations on each of the look-up entities, ugh!
What I'd really like to do is have some sort of mapping, which I could simply pass in the attribute name and get out some form of generic lookup object, which I could perform the desired operations on without having to care about type.
Is there some way to do this to my Linq-To-Sql entities? I've tried making them implement a basic interface (IAttribute), which simply specifies the Id/Text properties, however doing things like this fails:
System.Data.Linq.Table<IAttribute> table = GetAttribute("Colours");
As I cannot convert System.Data.Linq.Table<Colour> to System.Data.Linq.Table<IAttribute>.
Is there a way to make these look-up tables 'generic'?
Apologies that this is a bit of a brain-dump. There's surely imformation missing here, so just let me know if you'd like any further details. Cheers!
You have 2 options.
Use Expression Trees to dynamically create your lambda expression
Use Dynamic LINQ as detailed on Scott Gu's blog
I've looked at both options and have successfully implemented Expression Trees as my preferred approach.
Here's an example function that i created: (NOT TESTED)
private static bool ValueExists<T>(String Value) where T : class
{
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
Expression value = Expression.Equal(Expression.Property(pe, "ColumnName"), Expression.Constant(Value));
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(value, pe);
return MyDataContext.GetTable<T>().Where(predicate).Count() > 0;
}
Instead of using a switch statement, you can use a lookup dictionary. This is psuedocode-ish, but this is one way to get your table in question. You'll have to manually maintain the dictionary, but it should be much easier than a switch.
It looks like the DataContext.GetTable() method could be the answer to your problem. You can get a table if you know the type of the linq entity that you want to operate upon.
Dictionary<string, Type> lookupDict = new Dictionary<string, Type>
{
"Colour", typeof(MatchingLinqEntity)
...
}
Type entityType = lookupDict[AttributeFromRouteValue];
YourDataContext db = new YourDataContext();
var entityTable = db.GetTable(entityType);
var entity = entityTable.Single(x => x.Id == IdFromRouteValue);
// or whatever operations you need
db.SubmitChanges()
The Suteki Shop project has some very slick work in it. You could look into their implementation of IRepository<T> and IRepositoryResolver for a generic repository pattern. This really works well with an IoC container, but you could create them manually with reflection if the performance is acceptable. I'd use this route if you have or can add an IoC container to the project. You need to make sure your IoC container supports open generics if you go this route, but I'm pretty sure all the major players do.