I know that the audience of JIF is very small in numbers, but that's that Stack Overflow is for.
My question has to do with if anyone has a snipset with which I can declassify a String and send it as output to screen.
Example:
String data{Alice:} = "123";
output.println("this is it" + data);
note: more appropriate tag would be JIF, but I can not add tags yet.
Found a partial answer. For the moment I am working in a code stub provided by a friend.
Here there is an output stream created with the lowest restrictions ({}, public):
PrintStream[{}] output = declassify(runtime.stdout(new label{}), {});
if (output == null) return;
Then the declassify(...) must be called to declassify to public and afterwards print.
Therefore later on in the program:
int{Alice:} iAlice = 3;
int aliceDec;
aliceDec = declassify(ziAlice, {});
output.println("aliceDec: " + aliceDec);
Related
Hellow everyone,
I'm using Weka Java API for predictions. I was able to get the expected and actual behavior from the java code. But now what i wanted is to get the 'prediction margin' information from final results. From GUI, i can manage, but i wanted is a Java solution. appreciate if any one can help.What i wanted to get is the below highlighted information using java.
Below code shows the code i'm using as of now to predict actual/predicted.
for (int i = 0; i < testDataSet.numInstances(); i++) {
double actualClass = testDataSet.instance(i).classValue();
String actual = testDataSet.classAttribute().value((int) actualClass);
Instance newInst = testDataSet.instance(i);
double preJ48 = tree.classifyInstance(newInst);
String predictionString = testDataSet.classAttribute().value((int) preJ48);
System.out.println("Actual : " + actual + " Prediction : " + predictionString);
}
############################# Solution i found as below ##########
J48 tree = new J48();
tree.buildClassifier(trainDataSet);
double a = eval.evaluateModelOnceAndRecordPrediction(tree, testDataSet.instance(0));
eval.evaluateModel(tree, testDataSet, plainText);
for (String line : predsBuffer.toString().split("\n")) {
String[] linesplit = line.split("\\s+");
// If there's an error(error flag "+"), the length of linesplit is 6, otherwise 5
System.out.println("linesplit "+linesplit.length);
int id;
String expectedValue, classification;
double probability;
if (line.contains("+")) {
probability = Double.parseDouble(linesplit[5]);
System.out.println("Its Minus "+probability);
} else {
probability = Double.parseDouble(linesplit[4]);
System.out.println("Its Plus "+probability);
}
}
The prediction margin that you are referring to gets generated by the weka.gui.explorer.ClassifierErrorsPlotInstances class. Check the variables probActual and probNext in its process method.
This margin is simply the difference between the probability for the actual class label and the highest probability of the label that isn't the actual class label.
You can use the distributionForInstance method of your classifier to obtain the class distribution array and then determine these two probabilities to calculate the margin for the prediction.
I an coding beginner.I have started practicing SPOJ basic problems.This was the one I was trying to solve , But the code is incorrect.
Please help me where I have coded this question wrong as I am unable to figure out:
public class Print2ndChar {
public static void main(String[] args) throws java.lang.Exception {
Print2ndChar mainObj = new Print2ndChar();
java.io.BufferedReader inputReader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String noOfTestCase;
if(((noOfTestCase = inputReader.readLine()) == null))
System.exit(0);
int noOfLines = 0;
try{
noOfLines = Integer.parseInt(noOfTestCase);
}catch(Exception e){
System.exit(0);
}
if(noOfLines<0 || noOfLines>100)
System.exit(0);
String [] randomWords = new String[noOfLines];
for(int i=0;i<noOfLines;i++){
randomWords[i] = inputReader.readLine();
if(randomWords[i] == null || randomWords[i].length()<2 || randomWords[i].length()%2!=0 || (randomWords[i].length()/2)>100)
System.exit(0);
}
for (String word : randomWords){
mainObj.letsBegin(word.substring(0, word.length() / 2));
System.out.println();
}
}
private void letsBegin(String data) {
if (data.length() <= 0) {
return;
} else {
System.out.print(data.charAt(0));
if (data.length() >= 3)
letsBegin(data.substring(2, data.length()));
}
}
}
EDIT :
I/P : 4
your
progress
is
noticeable
O/P
y
po
i
ntc
OK! So after a lot of hit and trials, I know what is wrong with your code. The code that you have written fails because of the condition randomWords[i].length()%2!=0 inside your if. There is nothing wrong with you putting this condition to check the input, but if you will select sample test case, inside the highlighted blue area you will notice an extra space after every string. Like this :
You can see that other than the last input all other input strings have a space character at the end. So, when you read the string from stdin the length of the string is 2*k + 1 (because of the space), and your program will exit without any output. Hence you get a wrong answer.
This problem exists with other test cases as well probably. And how do I know this? After spoj shows you wrong answer, if you click on the wrong answer, it will show you 2 failed test cases, something like this:
It shows your program's output is empty because your code exited because of the extra space at the end of strings.
So, I believe the person who wrote the test cases should be given a WT Error (Wrong Test Cases) :P :D
So, the possible correction is you remove the mentioned condition from the if and you will get AC. Because now you will be dividing 2*k + 1 by 2, which will not be an integer and which will get rounded to the nearest smallest integer, which will be same as dividing 2*k by 2 and the program will give the correct result.
A few things that you should take care while solving questions on spoj, you do not have to verify that every input lies within the range specified in the question, or if it is a valid data type. The range is given to tell you that Spoj will only test your program with cases which lie between those ranges and will not exceed them. So, even if you remove all the code where you check for exceptions and ranges of input data, you will get an AC. Moreover, writing such code only adds to the burden.
Hope this helps. :)
I find a lot of GLPK for Java examples about how to specify the model (problem/constraints) to the solver and read parameters from a data file, but very little about programmatic parameter input/output.
In my case I need to submit values (array of weights and values) to a knapsack problem programmatically and postprocess the solution as well (perform addtional numeric checks on the solution found) in order to decide whether to proceed or not.
Think of the equivalent of reading a param: line from a data file without calling glp_mpl_read_data or printing details of a solution to a file without calling glp_print_mip/sol/itp.
Can you provide example code or point me to the right resource?
This is only a partial answer. I managed to solve the output part using the
GLPK.get_ipt_obj_val
GLPK.get_mip_obj_val
GLPK.get_ipt_col_val
GLPK.get_mip_col_val
functions as in the following example
static void writeMipSolution(glp_prob lp) {
String name = GLPK.glp_get_obj_name(lp);
double val = GLPK.glp_mip_obj_val(lp);
System.out.println(name + " = " + val);
int n = GLPK.glp_get_num_cols(lp);
for (int i = 1; i <= n; i++) {
name = GLPK.glp_get_col_name(lp, i);
val = GLPK.glp_mip_col_val(lp, i);
System.out.println(name + " = " + val);
}
}
Still investigating the input part, though.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 7 years ago.
Improve this question
I hope the question is suitable for here. I've designed an application layer protocol, say similar to HTTP. How can I define, and set the header fields in Java? Overall, I just want to write a simple client-server program that transfers "Hello World" string, but using my own protocol.
Assume header fields are similar to the following. So the "Hello World!" data comes after this header.
When you write to a socket, you're writing an stream of bytes. It's common, as in the table you included in your question, to start that stream with a standard series of bytes that gives the information needed to make sense of the remaining stream.
For example, of you simply want to send a string the minimum you'd need to add would be the string length like this:
|message length|data|
Which could be written like this:
String data = "Hello, world!";
ByteBuffer buffer = ByteBuffer.allocate(data.length + Integer.BYTES);
buffer.putInt(data.length);
buffer.put(data.getBytes("UTF-8"));
buffer.flip();
channel.write(buffer);
Adding in additional header information is no different, you just need to define a format for it in the stream.
You might for example use a format like this
|message length|header count|header size|header type|header data|data|
Which could be written like this:
Map<Integer, String> headers = ...
String data = "Hello, world - look at my headers!";
int headerBuffersLength = 0;
List<ByteBuffer> headerBuffers = new ArrayList<>();
for(Integer headerType : headers.keySet())
{
String headerData = headers.get(headerType);
ByteBuffer headerBuffer = ByteBuffer.allocation(headerData.size + Integer.BYTES + Integer.BYTES);
headerBuffer.putInt(headerData.length);
headerBuffer.putInt(headerType);
headerBuffer.put(headerData.getBytes("UTF-8"));
headerBuffer.flip();
headerBuffers.add(headerBuffer);
headerBuffersLength += headerBuffer.limit();
}
ByteBuffer buffer = ByteBuffer.allocate(data.length + headerBuffersLength + Integer.BYTES + Integer.BYTES);
buffer.putInt(data.length + headerBuffersLength);
buffer.putInt(headerBuffers.size());
for (ByteBuffer headerBuffer : headerBuffers)
{
buffer.put(headerBuffer);
}
buffer.put(data.getBytes("UTF-8"));
buffer.flip();
channel.write(buffer);
That's the basics, the code is very simple to write, but you might want to look at Google Protocol Buffers if you're doing anything more complicated.
There are many ways. It is quite common that this kind of specification comes with an xsd. If that is the case, you can use JAXB2 to parse it and create a set of Java Classes.
If that is not the case, may be you have the specification in such way you can do text processing and extract attributes and types to automate Java Class construction, using grep, sed, and so on.
If finally you have to build the Java Classes on your own, I will do something like following:
package my.package.ams;
public class ASMHeader {
private Integer version = null;
private Integer msgType = null;
private Integer priority = null;
...
public String getVersionString (){
return String.format("%02d", (version != null)?version:0);
}
public Integer getVersion(){
return version;
}
public void setVersion(Integer version){
if(version >= 0 and version < 100){
this.version = version;
}
}
public Integer getMsgType(){
return msgType;
}
public void setMsgType(Integer MsgType){
if(msgType >= 0 and msgType < 5){
this.msgType = msgType;
}
}
//And so on
....
}
Finally processing rules are not shown in yournpic, but you will have to understand and implements.
Take into account the possibility to thrown exception where version, msgType and other variables, doesn't meet the rules expressed in the document.
Hope it helps!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert String to code
I need to evaluate a string containing valid Java code
eg. I should be able to get 6 from String code="Math.abs(2*3);";
This sounds like quite an interesting idea, can I ask what the purpose of your application will be?
The best bet is to build up a dictionary of known patterns you will support.
My first idea is that you should create an ArrayList of accepted patterns. So for example:
ArrayList<String> acceptedPatterns = new ArrayList<String>();
acceptedPatterns.add("math.abs");
acceptedPatterns.add("math.acos");
etc.
Then you can evaluate this list when you get hold of the string.
String foundPattern = null;
String myStringFromInput = editText.getText();
for (String pattern : acceptedPatterns){
if (myStringFromInput.contains(pattern){
// we have recognised a java method, flag this up
foundPattern = pattern;
break;
}
}
At this point you would have "Math.abs" in your foundPattern variable.
You could then use your knowledge of how this method works to compute it. I can't think of a super efficient way, but a basic way that would at least get you going would be something like a big if/else statement:
int result = 0;
if (foundPattern.contains("Math.abs"){
result = computeMathAbs(myStringFromInput);
}else if (foundPattern.contains("Math.acos"){
// etc
}
And then in your computeMathAbs method you would do something like this:
private int computeMathAbs(String input){
int indexOfBracket = input.indexOf("(");
int indexOfCloseBracket = input.indexOf(")");
String value = input.subString(indexOfBracket,indexOfCloseBracket);
int valueInt = computeFromString(value);
int result = Math.abs(valueInt);
return result;
}
You could then display the result passed back.
The computeFromString() method will do a similar thing, looking for the * symbol or other symbols and turning this into a multiplication like the abs example.
Obviously this is a basic example, so you would only be able to compute one java method at a time, the complexity for more than one method at a time would be quite difficult to program I think.
You would also need to put quite a bit of error handling in, and recognise that the user might not enter perfect java. Can of worms.
You can use Groovy http://groovy.codehaus.org/api/groovy/util/Eval.html
import groovy.util.Eval;
...
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("a", 2);
params.put("b", 3);
Integer res = (Integer) Eval.me("param", params, "Math.abs(param.a * param.b)");
System.out.println("res with params = " + res);
System.out.println("res without params = " + Eval.me("Math.abs(2*3)"));