I'm trying to write a Jena built-in to return a value from an algorithm I have been given and then do a comparison against that value, e.g.,
String rule = "[exRule: (?d rdf:type ex:abc)" +
"<-" +
// ...extract ?a, ?b to use as inputs to the rule
"greaterThan(myBuiltIn(?a, ?b), 1)" + // Is return value greater than 1
"]";
So, first the Jena documentation says that the easiest way to experiment with this is to look at the examples in the builtins directory, however I don't seem to have this in my installation, I'm using Jena 2.6.4 on Windows 7. Where can I find this? Do I need to download it from elsewhere?
Secondly, I'm unsure how to pick up the return value from my builtin. If I simply call myBuiltIn(2, 1) using hardwired values I know it's being called due to some debug output I've added to the builtin's bodyCall() method. However, if I pass it to greaterThan(), then I no longer see this. Is it still being called?
#Joshua
I found how to implement this.
First of all, you should create a new class that extend from BaseBuiltin like this http://sadl.sourceforge.net/CustomJenaBuiltins.html
and then add it into builtinRegistry class
Related
I've "inherited" existing Java Selenium & Cucumber framework which was written mostly for OS usage. I'm using Windows and I'm trying to fix & run it on Windows.
My first problem is specifing corrent file path, this is how it was written for OS:
private String getProjectName(Scenario scenario) {
return Arrays.asList(scenario.getUri().getPath().replace(System.getProperty("user.dir"), "").split("/")).get(5);
}
Error which I'm receiving is:
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 1
As for Windows we're using backlashes I've tried switching "/" into "" but as error appears (+ after my investigations) I've tried with "\\\\" but actually error remains the same as above.
I'm aware that providing only portion of my code and it may be hard but for the first glance can you tell me:
If that method may work on Windows or this should be completely refactored?
Is System.getProperty("user.dir") correct solution?
How to correctly pass backslashes?
Why they're taking .get(5)?
I can guess:
This method is taking the project name that is likely the name of a certain folder in the folder structure where scenario file located.
This is why they took 5th element. Because on the 5th level there was the folder which represented the project.
The used approach look very arguable. At least because there are some redundent steps like converting to list.
Now. How would you go:
The proper way is to use java.nio.file.Path (starts from Java 7) that takes care of differnt OS-specific things.
So your code might look like:
private String getProjectName(Scenario scenario) {
return Path.of(scenario.getUri()).getName(5)
}
P.S. - of course you have to change 5 to catch a proper position of the required folder in your structure.
Users submit code (mainly java) on my site to solve simple programming challenges, but sending the code to a server to compile and execute it can sometimes take more than 10 seconds.
To speed up this process, I plan to first check the submissions database to see if equivalent code has been submitted before. I realize this will cause Random methods to always return the same result, but that doesn't matter much. Is there any other potential problem that could be caused by not running the code?
To find matches, I remove comments and whitespace when comparing code. However, the same code can still be written in different ways, such as with different variable names. Is there a way to compare code that will find more equivalent code?
You could store a SHA1 hash of the code to compare with a previous submission. You are right that different variable names would give different hashes. Try running the code through a minifier or obfuscator. That way, variable cat and dog will both end up like a1, then you could see if they are unique. The only other way would be to actually compile it into bytecode, but then it's too late.
Instead of analyzing the source code, why not speed up the compilation? Try having a servlet container always running with a custom ClassLoader, and use the JDK tools.jar to compile on the fly. You could even submit the code via AJAX REST and get the results back the same way.
Consider how Eclipse compiles your files in the background.
Also, consider how http://ideone.com implements their online compiler.
FYI It is a big security risk to allow random code execution. You have to be very careful about hackers.
Variable names:
You can write code to match variable names in one file with the variable names in the other, then you can replace both sets with a consistent variable name.
File 1:
var1 += this(var1 - 1);
File 2:
sum += this(sum - 1);
After you read File 1, you look for what variable name File 2 is using in the place of sum, then make the variable names the same across both files.
*Note, if variables are used in similar ways you may get incorrect substitutions. This is most likely when variables are being declared. To help mitigate this, you can start searching for variable names at the bottom of the file and work up.
Short hands:
Force {} and () braces into each if/else/for/while/etc...
rewrite operations like "i+=..." as "i=i+..."
Functions:
In cases where function order doesn't matter, you can make sure functions are equivalent and then ignore them.
Operator precedence:
"3 + (2 * 4)" is usually equivalent to "2 * 4 + 3"
A way around this could be by determining the precedence of each operation and then matching it to an operation of the same precedence in the other set of code. Once a set of operations have been matched, you can replace them with a variable to represent them.
Ex.
(2+4) * 3 + (2+6) * 5 == someotherequation
//substitute most precedent: (2+4) and (2+6) for a and b
... a * 3 + b * 5
//substitute most precedent: (a*3) and (b*5) for c and d
... c + d
//substitute most precedent....
These are just a couple ways I could think of. If you do it this way, it'll end up being quite a big project... especially if you're working with multiple languages.
I know you can retrieve the username with something like System.getProperty("user.name") but I am looking for a way to retrieve the first and last name of the current user.
Is there a native Java library that does this? Or do you have to plug into the Windows API? Or maybe you have to pull it from Active Directory? This seems relatively easy with .NET but I can't find a way to do it in Java.
As Brian Roach suggested in the comments, it's pretty straight-forward to do this with JNA, since it has a built-in wrapper for Secur32 which wraps the GetUsernameEx() function (which is ultimately the system call wrapped by the .NET library you linked to above).
Use would be something like this:
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.platform.win32.Secur32;
// ...
char[] name = new char[100]; // or whatever is appropriate
Secur32.INSTANCE.GetUserNameEx(
Secur32.EXTENDED_NAME_FORMAT.NameDisplay,
name,
new IntByReference(name.length)
);
String fullName = new String(name).trim();
Note that this will give you the full name in the same format as you'd get typing net user %USERNAME% /domain at the command prompt.
Or just,
String fullName = Secur32Util.getUserNameEx(Secur32.EXTENDED_NAME_FORMAT.NameDisplay);
But it is the same, as the upper answer
I am using a lib which has an enum type with consts like these;
Type.SHORT
Type.LONG
Type.FLOAT
Type.STRING
While I am debugging in Eclipse, I got an error:
No enum const class Type.STRİNG
As I am using a Turkish system, there is a problem on working i>İ but as this is an enum const, even though I put every attributes as UTF-8, nothing could get that STRING is what Eclipse should look for. But it still looks for STRİNG and it can't find and I can't use that. What must I do for that?
Project > Properties > Resouce > Text file encoding is UTF-8 now. Problem keeps.
EDIT: More information may give some clues which I can't get;
I am working on OrientDB. This is my first attempt, so I don't know if the problem could be on OrientDB packages. But I am using many other libs, I have never seen such a problem. There is a OType enum in this package, and I am only trying to connect to the database.
String url = "local:database";
ODatabaseObjectTx db = new ODatabaseObjectTx(url).
Person person = new Person("John");
db.save(person);
db.close();
There is no more code I use yet. Database created but then I get the java.lang.IllegalArgumentException:
Caused by: java.lang.IllegalArgumentException: No enum const class com.orientechnologies.orient.core.metadata.schema.OType.STRİNG
at java.lang.Enum.valueOf(Unknown Source)
at com.orientechnologies.orient.core.metadata.schema.OType.valueOf(OType.java:41)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLCreateProperty.parse(OCommandExecutorSQLCreateProperty.java:81)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLCreateProperty.parse(OCommandExecutorSQLCreateProperty.java:35)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:43)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:28)
at com.orientechnologies.orient.core.storage.OStorageEmbedded.command(OStorageEmbedded.java:63)
at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:63)
at com.orientechnologies.orient.core.metadata.schema.OClassImpl.addProperty(OClassImpl.java:342)
at com.orientechnologies.orient.core.metadata.schema.OClassImpl.createProperty(OClassImpl.java:258)
at com.orientechnologies.orient.core.metadata.security.OSecurityShared.create(OSecurityShared.java:177)
at com.orientechnologies.orient.core.metadata.security.OSecurityProxy.create(OSecurityProxy.java:37)
at com.orientechnologies.orient.core.metadata.OMetadata.create(OMetadata.java:70)
at com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract.create(ODatabaseRecordAbstract.java:142)
... 4 more
Here is OType class: http://code.google.com/p/orient/source/browse/trunk/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OType.java
And other class; OCommandExecutorSQLCreateProperty:
http://code.google.com/p/orient/source/browse/trunk/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java
Line 81 says: type = OType.valueOf(word.toString());
Am I correct to assume you are running this program using a turkish locale? Then it seems the bug is in line 118 of OCommandExecutorSQLCreateProperty:
linkedType = OType.valueOf(linked.toUpperCase());
You would have to specify the Locale whose upper casing rules should be used, probably Locale.ENGLISH as the parameter to toUpperCase.
This problem is related to your database connection. Presumably, there's a string in OrientDB somewhere, and you are reading it, and then trying to use it to select a member of the enum.
I'm assuming in the code that you posted that the variable word comes from data in the database. If it comes from somewhere else, then the problem is the 'somewhere else'. If OrientDB, for some strange reason, returns 'STRİNG' as metadata to tell you the type of something, then that is indeed a defect in OrientDB.
If that string actually contains a İ, then no Eclipse setting will have any effect on the results. You will have to write code to normalize İ to I.
If you dump out the contents of 'word' as a sequence of hex values for the chars of the string, I think you'll see your İ staring right at you. You have to change what's in the DB to have a plain old I.
Unfortunately, it is related with regional setting, locale of your OS which is Turkish.
Two work around options :
1. Change your regional settings to English-US
2. Give encoding to the jvm as command line param for setting locale to English
-Duser.language=en -Duser.region=EN
I have created bug reports for xmlbeans, exist and apache cxf for the same issue. Enumeration toUpper is the point of the exception.
Some related links:
https://issues.apache.org/jira/browse/XMLSCHEMA-22
http://mail-archives.apache.org/mod_mbox/xmlbeans-user/201001.mbox/%3CSNT123-DS11993DD331D6CA7799C46CF6650#phx.gbl%3E
http://mail-archives.apache.org/mod_mbox/cxf-users/201203.mbox/%3CBLU0-SMTP115A668459D9A0DA11EA5FAF6460#phx.gbl%3E
https://vaadin.com/forum/-/message_boards/view_message/793105
http://comments.gmane.org/gmane.comp.apache.cxf.user/18316
One work-around is to type Type.ST and then press Ctrl-space. Eclipse should auto-complete the variable name without you having to figure out how to enter a dotless capital I on a Turkish keyboard. :)
Specifically I am converting a python script into a java helper method. Here is a snippet (slightly modified for simplicity).
# hash of values
vals = {}
vals['a'] = 'a'
vals['b'] = 'b'
vals['1'] = 1
output = sys.stdout
file = open(filename).read()
print >>output, file % vals,
So in the file there are %(a), %(b), %(1) etc that I want substituted with the hash keys. I perused the API but couldn't find anything. Did I miss it or does something like this not exist in the Java API?
You can't do this directly without some additional templating library. I recommend StringTemplate. Very lightweight, easy to use, and very optimized and robust.
I doubt you'll find a pure Java solution that'll do exactly what you want out of the box.
With this in mind, the best answer depends on the complexity and variety of Python formatting strings that appear in your file:
If they're simple and not varied, the easiest way might be to code something up yourself.
If the opposite is true, one way to get the result you want with little work is by embedding Jython into your Java program. This will enable you to use Python's string formatting operator (%) directly. What's more, you'll be able to give it a Java Map as if it were a Python dictionary (vals in your code).