In a Libreoffice Spreadsheet's sheet, I can get access to a Cell, but not to its value. I don't find my error, any feedback is welcome. Here is the code:
import java.io.File;
import java.io.IOException;
import org.jopendocument.dom.spreadsheet.MutableCell;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;
public class MyClass {
protected Sheet dataSheet;
protected File dataCalcFile;
public static void main(String[] args) {
MyClass myClassInstance = new MyClass();
myClassInstance.loadData();
}
public void loadData() {
int numRows=0, numColumnas=0;
MutableCell cell=null;
try {
dataCalcFile = new File(""C:\\temp\\Data.ods"");
dataSheet = SpreadSheet.createFromFile(dataCalcFile).getSheet(0);
numRows = dataSheet.getRowCount();
System.out.println("Number of rows: " + numRows);
System.out.println("Cell at 0,0: " + dataSheet.getCellAt(0, 0));
System.out.println("Nullpointer Exception when getting cell value at 0,0: " + dataSheet.getValueAt(0, 0)); // *** THE INFAMOUS ONE ***
} catch (Exception e) {
System.out.println(e);
}
}
}
And here is the output at console:
Number of rows: 107
Cell at 0,0: <table:table-cell xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" table:style-name="ce1" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:value-type="string" xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" calcext:value-type="string"><text:p xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">Carpeta</text:p></table:table-cell>
java.lang.NullPointerException
Just found that:
"Yes, LO 7 switched to OpenDocument 1.3. We're working on supporting it. In the mean time, you can change the format to "1.2 extended". Go to Options, then Load/Save, then General, then ODF format version."
It works for me, but am excited to hear my customers opinion...
I found that it must be some incompatibility between the library jopendocument and the newer versions of Libreoffice (7.x), as the code above:
Works as expected if the spreadsheet is edited with Libreoffice 6.4.3.2
Spits the null pointer exception out if the spreadsheet is edited with Libreoffice 7.0.1.2
In some version in between Calc produces an XML not understood by jopendocument.
Instead of using
getValueAt(0, 0),
you can use
getCellAt(0, 0).getElement().getValue()
It works for me.
Related
(note, I've resolved my problem and posted the code at the bottom)
I'm playing around with TensorFlow and the backend processing must take place in Java. I've taken one of the models from the https://developers.google.com/machine-learning/crash-course and saved it with tf.saved_model.save(my_model,"house_price_median_income") (using a docker container). I copied the model off and loaded it into Java (using the 2.0 stuff built from source because I'm on windows).
I can load the model and run it:
try (SavedModelBundle model = SavedModelBundle.load("./house_price_median_income", "serve")) {
try (Session session = model.session()) {
Session.Runner runner = session.runner();
float[][] in = new float[][]{ {2.1518f} } ;
Tensor<?> jack = Tensor.create(in);
runner.feed("serving_default_layer1_input", jack);
float[][] probabilities = runner.fetch("StatefulPartitionedCall").run().get(0).copyTo(new float[1][1]);
for (int i = 0; i < probabilities.length; ++i) {
System.out.println(String.format("-- Input #%d", i));
for (int j = 0; j < probabilities[i].length; ++j) {
System.out.println(String.format("Class %d - %f", i, probabilities[i][j]));
}
}
}
}
The above is hardcoded to an input and output but I want to be able to read the model and provide some information so the end-user can select the input and output, etc.
I can get the inputs and outputs with the python command: saved_model_cli show --dir ./house_price_median_income --all
What I want to do it get the inputs and outputs via Java so my code doesn't need to execute python script to get them. I can get operations via:
Graph graph = model.graph();
Iterator<Operation> itr = graph.operations();
while (itr.hasNext()) {
GraphOperation e = (GraphOperation)itr.next();
System.out.println(e);
And this outputs both the inputs and outputs as "operations" BUT how do I know that it is an input and\or an output? The python tool uses the SignatureDef but that doesn't seem to appear in the TensorFlow 2.0 java stuff at all. Am I missing something obvious or is it just missing from TensforFlow 2.0 Java library?
NOTE, I've sorted my issue with the answer help below. Here is my full bit of code in case somebody would like it in the future. Note this is TF 2.0 and uses the SNAPSHOT mentioned below. I make a few assumptions but it shows how to pull the input and output and then use them to run a model
import org.tensorflow.SavedModelBundle;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.exceptions.TensorFlowException;
import org.tensorflow.Session.Run;
import org.tensorflow.Graph;
import org.tensorflow.Operation;
import org.tensorflow.Output;
import org.tensorflow.GraphOperation;
import org.tensorflow.proto.framework.SignatureDef;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.tensorflow.proto.framework.MetaGraphDef;
import java.util.Map;
import org.tensorflow.proto.framework.TensorInfo;
import org.tensorflow.types.TFloat32;
import org.tensorflow.tools.Shape;
import java.nio.FloatBuffer;
import org.tensorflow.tools.buffer.DataBuffers;
import org.tensorflow.tools.ndarray.FloatNdArray;
import org.tensorflow.tools.ndarray.StdArrays;
import org.tensorflow.proto.framework.TensorInfo;
public class v2tensor {
public static void main(String[] args) {
try (SavedModelBundle savedModel = SavedModelBundle.load("./house_price_median_income", "serve")) {
SignatureDef modelInfo = savedModel.metaGraphDef().getSignatureDefMap().get("serving_default");
TensorInfo input1 = null;
TensorInfo output1 = null;
Map<String, TensorInfo> inputs = modelInfo.getInputsMap();
for(Map.Entry<String, TensorInfo> input : inputs.entrySet()) {
if (input1 == null) {
input1 = input.getValue();
System.out.println(input1.getName());
}
System.out.println(input);
}
Map<String, TensorInfo> outputs = modelInfo.getOutputsMap();
for(Map.Entry<String, TensorInfo> output : outputs.entrySet()) {
if (output1 == null) {
output1=output.getValue();
}
System.out.println(output);
}
try (Session session = savedModel.session()) {
Session.Runner runner = session.runner();
FloatNdArray matrix = StdArrays.ndCopyOf(new float[][]{ { 2.1518f } } );
try (Tensor<TFloat32> jack = TFloat32.tensorOf(matrix) ) {
runner.feed(input1.getName(), jack);
try ( Tensor<TFloat32> rezz = runner.fetch(output1.getName()).run().get(0).expect(TFloat32.DTYPE) ) {
TFloat32 data = rezz.data();
data.scalars().forEachIndexed((i, s) -> {
System.out.println(s.getFloat());
} );
}
}
}
} catch (TensorFlowException ex) {
ex.printStackTrace();
}
}
}
What you need to do is to read the SavedModelBundle metadata as a MetaGraphDef, from there you can retrieve input and output names from the SignatureDef, like in Python.
In TF Java 1.* (i.e. the client you are using in your example), the proto definitions are not available out-of-the-box from the tensorflow artifact, you need to add a dependency to org.tensorflow:proto as well and deserialize the result of SavedModelBundle.metaGraphDef() into a MetaGraphDef proto.
In TF Java 2.* (the new client actually only available as snapshots from here), the protos are present right away so you can simply call this line to retrieve the right SignatureDef:
savedModel.metaGraphDef().signatureDefMap.getValue("serving_default")
thanks for taking the time to read this. I'm fairly new to JavaFX and have a weird error in my compiler that I would like some insight on.
Here's the error:
2018-09-13 19:09:36.387 java[8040:660455] unrecognized type is 4294967295
2018-09-13 19:09:36.387 java[8040:660455] *** Assertion failure in -[NSEvent _initWithCGEvent:eventRef:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1652/AppKit.subproj/NSEvent.m:1969
Here is the code I am working with:
This is in a .java file named applicationSettings
public static double lookupUser(String name, String password) throws IOException {
InputStream inputStream = applicationSettings.class.getResourceAsStream("/files/users.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
Integer lastRow = sheet.getPhysicalNumberOfRows();
int currentRow = 1;
while(currentRow < lastRow) {
if(sheet.getRow(currentRow).getCell(0).getStringCellValue().toLowerCase().equals(name.toLowerCase())) {
if(sheet.getRow(currentRow).getCell(1).getStringCellValue().toLowerCase().equals(password.toLowerCase())) {
double accessLevel = sheet.getRow(currentRow).getCell(2).getNumericCellValue();
System.out.println(accessLevel);
return accessLevel;
}
}
currentRow++;
}
return 4.0;
}
}
This is in a .java file named loginScreen
EventHandler<ActionEvent> loginClicked = new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
double userFound = 0.0;
try {
userFound = applicationSettings.lookupUser(usernameField.getText(), passwordField.getText());
} catch (IOException e) {
e.printStackTrace();
}//END of Try/Catch
if(userFound == 1.0) { //1 is Admin Access
//TODO: Implement Login
System.out.println("Admin Login");
errorLabel.setVisible(false);
}else if(userFound == 2.0){ //2 is Elevated Access
//TODO: Elevated Access
System.out.println("Elevated Login");
errorLabel.setVisible(false);
}else if(userFound == 3.0){
//TODO: Basic Access
System.out.println("Basic Login");
errorLabel.setVisible(false);
}else{//Show Error
errorLabel.setVisible(true);
//TODO: Show Error
}//End If Statement
}
};
My Excel File is basically structured like this:
NAME PASSWORD ACCESS LEVEL
So for my login it would be like:
Trey Carey March3199; 1
This isn't going anywhere besides by church where it's not really doing anything besides automating some tedious tasks, so security isn't an issue.
Also, if there's anyway I can clean up some of these if statements and my code in general I would appreciate any tips or help!
Edit 2 13.11.2018:
This bug has been officially fixed now in JavaFX 12, was backported to JDK8 and approved to be backported to JFX 11. You can have a look at the bug report to find more information about it.JDK-8211304 Here is a link to the changes they've made. openjfx I'm personally not sure about the current license situation of JDK8 so I would advise to switch to the newest OpenJDK and OpenJFX if possible.
Hey there I'm experiencing the same issue you have and I can constantly reproduce it. The issue appears for me on JavaFX on macOS 10.14. You can simply create an application with a button that opens a second stage. If you invoke stage.showAndWait() (could be related to anything that holds the thread) on the second stage and then switch focus between different applications (I just alt-tab between my JavaFX app and Safari), the JavaFX Application crashes. Also reproducible in any IDE.
I actually found a bug report on the OpenJDK/OpenJFX bug tracker but there isn't much going on at the moment. JDK-8211137 Mac: JVM Crash due to uncaught exception
I don't have a solution yet as I'm having troubles pinning down the exact problem but I found a workaround that works in my specific case.
Edit:
If I'm using "stage.show()" I'm only getting the error but when using stage.showAndWait() or anything that does some kind of waiting loop, the application completely crashes.
I am trying to get the total number of unresolved bugs and Vulnerabilities in the particular project using sonar-ws-5.6.jar.
I tried to pass the type as BUG to the search query. But still I am getting all the unresolved stuff. It is not taking the parameter type.
How to get the exact number of bugs and Vulnerabilities using Webservice?
Here is my code to connect to sonar and get the data.
import java.util.ArrayList;
import java.util.List;
import org.sonarqube.ws.Issues.SearchWsResponse;
import org.sonarqube.ws.client.HttpConnector;
import org.sonarqube.ws.client.WsClient;
import org.sonarqube.ws.client.WsClientFactories;
import org.sonarqube.ws.client.issue.SearchWsRequest;
public class SonarTest {
static String resourceKey = "com.company.projectname:parent";
public static void main(String[] args) {
try {
// Get Issue
HttpConnector httpConnector = HttpConnector.newBuilder().url("http://localhost:9000").credentials("admin", "admin").build();
SearchWsRequest issueSearchRequest = new SearchWsRequest();
issueSearchRequest.setPageSize(1000);
issueSearchRequest.setResolved(false);
List<String> bugTypesList = new ArrayList<String>();
bugTypesList.add("BUG");
issueSearchRequest.setTypes(bugTypesList);
WsClient wsClient = WsClientFactories.getDefault().newClient(httpConnector);
SearchWsResponse issuesResponse = wsClient.issues().search(issueSearchRequest);
System.out.println(issuesResponse.getIssuesList());
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: I am using sonarqube 5.6 with Java 1.8
As of now I am iterating the response and getting the count
List<Issue> issueList = issuesResponse.getIssuesList();
int bugCount = 0;
for(Issue issue : issueList){
if(issue.getType() == RuleType.BUG){
bugCount ++;
}
}
Well, you caught a bug ! I used your code and found out that the types parameter was not properly passed from the WSClient to the actual HTTP query.
So thanks for sharing your issue, SONAR-7871 is opened to have it addressed.
I am using ComponentWsRequest to get the total number of bugs
We can pass the metric key to get the required value.
Here is the code which gives me the total number of bugs.
List<String> VALUE_METRIC_KEYS = Arrays.asList("bugs");
ComponentWsRequest componentWsRequest = new ComponentWsRequest();
componentWsRequest.setComponentKey(resourceKey);
componentWsRequest.setMetricKeys(VALUE_METRIC_KEYS);
ComponentWsResponse componentWsResponse = wsClient.measures().component(componentWsRequest);
List<Measure>measureList = componentWsResponse.getComponent().getMeasuresList();
for(Measure measure : measureList){
System.out.println(measure);
}
We can use any of the metric keys to get the respective values:
"quality_gate_details","reliability_rating","reliability_remediation_effort","vulnerabilities","security_rating","security_remediation_effort","code_smells","sqale_rating","sqale_debt_ratio","effort_to_reach_maintainability_rating_a","sqale_index","ncloc","lines","statements","functions","classes","files","directories","duplicated_lines_density","duplicated_blocks","duplicated_lines","duplicated_files","complexity","function_complexity","file_complexity","class_complexity","comment_lines_density","comment_lines","public_api","public_documented_api_density","public_undocumented_api","violations","open_issues","reopened_issues","confirmed_issues","false_positive_issues","wont_fix_issues"
I'm working with pbf files from the open street maps
I want to parse node, relations, and ways.
when I try to parse nodes I get that message.
The code looks like
package myCode;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import protpbufCode.OsmPbf;
import protpbufCode.OsmPbf.Node;
import protpbufCode.OsmPbf.PrimitiveGroup;
public class ReadingPBF
{
public static void print(PrimitiveGroup node)
{
for (Node m: node.getNodesList())
{
System.out.print("Person ID: " + m.getId() + " ");
System.out.print(" Lat: " + m.getLat()+ " ");
System.out.print(" Long: "+ m.getLon()+ " ");
System.out.println("");
}
}
public static void main (String args[])
{
try
{
PrimitiveGroup newNode = PrimitiveGroup.parseFrom(new FileInputStream(new File("isle.pbf")));
print(newNode);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println(e.getCause());
}
}
}
the OsmPbf is java class that created using the protobuf compiler.
and that what gets printed.
com.google.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
at com.google.protobuf.InvalidProtocolBufferException.invalidTag(InvalidProtocolBufferException.java:89)
at com.google.protobuf.CodedInputStream.readTag(CodedInputStream.java:158)
at protpbufCode.OsmPbf$PrimitiveGroup.<init>(OsmPbf.java:5230)
at protpbufCode.OsmPbf$PrimitiveGroup.<init>(OsmPbf.java:5219)
at protpbufCode.OsmPbf$PrimitiveGroup$1.parsePartialFrom(OsmPbf.java:5329)
at protpbufCode.OsmPbf$PrimitiveGroup$1.parsePartialFrom(OsmPbf.java:1)
at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:192)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:209)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:215)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
at protpbufCode.OsmPbf$PrimitiveGroup.parseFrom(OsmPbf.java:5627)
at myCode.ReadingPBF.main(ReadingPBF.java:33)
Protocol message contained an invalid tag (zero).
null
OpenStreetMap .pbf files are not simple protobufs. See the documentation here:
http://wiki.openstreetmap.org/wiki/PBF_Format
Under the section "File format", you'll see this:
The format is a repeating sequence of:
int4: length of the BlobHeader message in network byte order
serialized BlobHeader message
serialized Blob message (size is given in the header)
That is, the file starts out with a 4-byte integer before the first protobuf message. Since this integer is probably smaller than 2^24, the first byte will of course be zero, which explains the exact exception you are seeing.
You will need to read this 4-byte value manually, then make sure to read only that many bytes and parse them as a BlobHeader, and so on.
Personally I'd recommend looking for a PBF decoder library that already handles this for you. There must be a few out there.
I used following code to calculating prediction in R using Java that code work fine it shows me output but, I want draw plot using same code on my predicted output code was given below
import org.rosuda.REngine.Rserve.RConnection;
public class demo{
public static void main(String args[]){
try{
System.out.println("INFO: Trying to connect to R ");
RConnection c = new RConnection();
c.eval("library('RMongo')");
c.eval(" db <- mongoDbConnect('dbname', '127.0.0.1', '27017')");
c.eval("query <- dbGetQuery(db,'collection_name','{\"hostId\" : \"300.3.3.3\"}')");
c.eval("date <- query$Date");
c.eval("cpu <- query$cpuUtilization");
c.eval("memory <- query$memory");
c.eval("df <- data.frame(date=1377843220)");
c.eval("res <- lm(cbind(memory,cpu)~ date -1 )");
int[] d= c.eval("predict(res,df)").asIntegers();
for (Integer td : d) {
System.out.println(td);
}
c.close();
}
catch(Exception e){
System.out.println("ERROR: In Connection to R ");
System.out.println("The Exception is "+ e.getMessage());
e.printStackTrace();
}
}
}
So any one knows how to draw plot using R in java code ?
Use a JFrame with a JGDPanel from JavaGD and plot something via JRI.
Look into JGD: http://cran.r-project.org/web/packages/JavaGD/JavaGD.pdf
Look into JRI: http://rosuda.org/JRI/
Another alternative is using R to generate the data you want and using native Java graphics libraries.