java.lang.IndexOutOfBoundsException: Index: 38, Size: 38 - java

I'm currently working on a project, and I got this error. I do not know why it stops at Index 38. The error is
org.apache.jasper.JasperException: javax.el.ELException: java.lang.IndexOutOfBoundsException: Index: 38, Size: 38
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:413)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:326)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:253)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
The code that I had used to display was a while loop
var count = ${count};
while (--count) {
var val = ${valueList.get(count)}; //get value from her code
var xValue = ${XValueList.get(count)};
var yValue = ${YValueList.get(count)};
//max = Math.max(max, val);
//
min = 0;
var point = {
x: xValue,
y: yValue,
value: val
};
points.push(point);
}
// var data = { max: max, min:min, data: points };
var data = {data: points };
return data;
};
And I have 41 records in my database. Any help?

Arrays start counting at 0, but their size is given in number of fields. An array of size 38 actually has fields 0 through 37. Accessing field 38 throws an java.lang.IndexOutOfBoundsException.

You somehow missed the fact that JSP is a HTML/CSS/JS code generator and you expected that JSP EL expressions run "in sync" with JavaScript code embedded in JSP file. This is untrue. JSP/EL runs in webserver, produces HTML/CSS/JS output, basically as one large String which get sent from webserver to webbrowser, who in turn runs the JSP/EL-produced HTML/CSS/JS output.
An easy way to realize your mistake is doing a rightclick and View Source in webbrowser (on a JSP page containing tags and EL expressions which doesn't throw a server side exception like this, of course). You'll notice that it does actually not contain any single line of JSP/EL code.
Basically, the --count in your code snippet has only effect in JavaScript, not in JSP, because you basically printed the ${count} as a JavaScript variable var count during generating the HTML output. But the value of var count in JavaScript does in no way affect the value of ${count} which is used further down in ${valueList.get(count)}. The ${count} is still 38 there and has not become 37 or so.
That was the problem. Now we can advance to the solution. I won't post an answer to fix specifically your attempted solution, for the simple reason that this is from high level seen a wrong solution to the underlying problem you tried to solve: converting a Java model object to a JavaScript object.
The right solution to that is converting the Java model object to a string in JSON format in Java side and then letting JSP print it as if it's a JavaScript variable. Your Java model object has also another issue: you seem to have decoupled the X and Y values in two separate lists instead of using a single list with entities in turn having X and Y values.
First create a decent model object:
public class Point {
private int x;
private int y;
// Add/generate constructor+getter+setter+equals+hashcode.
}
Then replace your XValueList and YValueList as below:
List<Point> points = new ArrayList<>();
points.add(new Point(1, 2));
points.add(new Point(3, 4));
points.add(new Point(5, 6));
// ...
Then use one of Java JSON APIs to convert this to a JSON string. I'll pick Gson in below example:
String pointsAsJson = new Gson().toJson(points);
Now let JSP print it as if it's a JS variable, the right way:
var data = {data: ${pointsAsJson} };
No need for a clumsy loop here massaging data forth and back.

Related

From java.util.ArrayList to a dictionary in java

Im using a JBPM to make a SQL query in the DB. The sql output is return to a variable that is java.util.ArrayList. The table that im queryin is like this in MariaDB:
variable value
math 1
physics 4
biology 10
...
sport 5
chemistry 9
The query that I'm making is SELECT * from school_data. It is returning me in a form of list like [math,1,phycics,4,biology,10.....] and only 20 elements.
Is there a way to transform the output in dictionary and then extract the values easly? I python it would be like this:
cur = connection.cursor()
cur.execute("SELECT * from school_data")
result = cur.fetchall()
query_result = dict((x, y) for x, y in result)
math=query_result['math']
physics=query_result['physics']
biology=query_result['biology']
Java does not have lists or dictionaries / maps as built-in data types, so it does not offer syntax or built-in operators for working with them. One can certainly perform transformations such as you describe, but it's a matter of opinion whether it can be done "easily". One way would be something like this:
Map<String, String> query_result = new HashMap<>();
for (int i = 0; i < result_array.length; i += 2) {
query_result.put(result_array[i], result_array[i + 1]);
}
String biology = query_result.get("biology");
// ...
That makes some assumptions about the data types involved, which you might need to adjust for your actual data.

dl4j lstm not successful

Im trying to copy the exrcise about halfway down the page on this link:
https://d2l.ai/chapter_recurrent-neural-networks/sequence.html
The exercise uses a sine function to create 1000 data points between -1 through 1 and use a recurrent network to approximate the function.
Below is the code I used. I'm going back to study more why this isn't working as it doesn't make much sense to me now when I was easily able to use a feed forward network to approximate this function.
//get data
ArrayList<DataSet> list = new ArrayList();
DataSet dss = DataSetFetch.getDataSet(Constants.DataTypes.math, "sine", 20, 500, 0, 0);
DataSet dsMain = dss.copy();
if (!dss.isEmpty()){
list.add(dss);
}
if (list.isEmpty()){
return;
}
//format dataset
list = DataSetFormatter.formatReccurnent(list, 0);
//get network
int history = 10;
ArrayList<LayerDescription> ldlist = new ArrayList<>();
LayerDescription l = new LayerDescription(1,history, Activation.RELU);
ldlist.add(l);
LayerDescription ll = new LayerDescription(history, 1, Activation.IDENTITY, LossFunctions.LossFunction.MSE);
ldlist.add(ll);
ListenerDescription ld = new ListenerDescription(20, true, false);
MultiLayerNetwork network = Reccurent.getLstm(ldlist, 123, WeightInit.XAVIER, new RmsProp(), ld);
//train network
final List<DataSet> lister = list.get(0).asList();
DataSetIterator iter = new ListDataSetIterator<>(lister, 50);
network.fit(iter, 50);
network.rnnClearPreviousState();
//test network
ArrayList<DataSet> resList = new ArrayList<>();
DataSet result = new DataSet();
INDArray arr = Nd4j.zeros(lister.size()+1);
INDArray holder;
if (list.size() > 1){
//test on training data
System.err.println("oops");
}else{
//test on original or scaled data
for (int i = 0; i < lister.size(); i++) {
holder = network.rnnTimeStep(lister.get(i).getFeatures());
arr.putScalar(i,holder.getFloat(0));
}
}
//add originaldata
resList.add(dsMain);
//result
result.setFeatures(dsMain.getFeatures());
result.setLabels(arr);
resList.add(result);
//display
DisplayData.plot2DScatterGraph(resList);
Can you explain the code I would need for a 1 in 10 hidden and 1 out lstm network to approximate a sine function?
Im not using any normalization as function is already -1:1 and Im using the Y input as the feature and the following Y Input as the label to train the network.
You notice i am building a class that allows for easier construction of nets and I have tried throwing many changes at the problem but I am sick of guessing.
Here are some examples of my results. Blue is data red is result
This is one of those times were you go from wondering why was this not working to how in the hell were my original results were as good as they were.
My failing was not understanding the documentation clearly and also not understanding BPTT.
With feed forward networks each iteration is stored as a row and each input as a column. An example is [dataset.size, network inputs.size]
However with recurrent input its reversed with each row being a an input and each column an iteration in time necessary to activate the state of the lstm chain of events. At minimum my input needed to be [0, networkinputs.size, dataset.size] But could also be [dataset.size, networkinputs.size, statelength.size]
In my previous example I was training the network with data in this format [dataset.size, networkinputs.size, 1]. So from my low resolution understanding the lstm network should never have worked at all but somehow produced at least something.
There may have also been some issue with converting the dataset to a list as I also changed how I feed the network but but I think the bulk of the issue was a data structure issue.
Below are my new results
Hard to tell what is going on without seeing the full code. For a start I don't see an RnnOutputLayer specified. You could take a look this which shows you how to build an RNN in DL4J.
If your RNN setup is correct this could be a tuning issue. You can find more on tuning here. Adam is probably a better choice for an updater than RMSProp. And tanh probably is a good choice for the activation for your output layer since it's range is (-1,1). Other things to check/tweak - learning rate, number of epochs, set up of your data (like are you trying to predict to far out?).

Is there a way to select specific characters from a TextView variable?

I am using AWS IoT to read and publish some information from a microelectronic's sensors. I am able to get the json file in the app as a big wall of text, but it is not very readable. I am using TextView as I don't want the user to be able to change the information. My problem is that I can't find a way to remove the parts that are not necessary to the user.
I am new to app creation, so I am trying to do this as simply as possible. I have my xml ready to receive the information; I just need the info in a variable that I can pass to it. I have tried implementing a character array, but haven't been able to get past the fact that I can't edit the text view.
tvLastMessage = (TextView) findViewById(R.id.tvLastMessage);
This is currently the block of text that I am receiving. It looks like this:
{"sensors":[{"name":"steamTemp","data":"181.39","state":1,
{"name":"waterTemp","data":"-713.15","state":0,
{"name":"waterFlow","data":"0.00","state":3,
{"name":"dieselFlow","data":"0.00","state":2,
{"name":"manualResetLevel","data":"1","state":0,
{"name":"waterFeederLevel","data":"1","state":0,
{"name":"autoResetPressure","data":"1","state":0,
{"name":"manualResetPressure","data":"1","state":0},
{"name":"tempLimit","data":"1","state":0,
{"name":"heatEff","data":"0.00","state":2}]}
The text does not look as formatted as this, but it is more understandable and readable to represent it this way. It normally does not have the new lines, so it will just naturally go to one as it runs out of room.
I am hoping that I can get it to simply show the numbers associated with each "name" and "data" as I have those hard-coded into my xml since they don't change. Just getting those numbers into different variables would be ideal, so I can simply reference the variable in my xml file. However, if there is a better way to do this, I am happy to take suggestions!
Try using a loop to find each instance of "name", "data", and "state", and get the values between them.
Assuming input is a string:
String string = "{\"sensors\":[{\"name\":\"steamTemp\",\"data\":\"181.39\",\"state\":1,\n{\"name\":\"waterTemp\",\"data\":\"-713.15\",\"state\":0,\n{\"name\":\"waterFlow\",\"data\":\"0.00\",\"state\":3,\n{\"name\":\"dieselFlow\",\"data\":\"0.00\",\"state\":2,\n{\"name\":\"manualResetLevel\",\"data\":\"1\",\"state\":0,\n{\"name\":\"waterFeederLevel\",\"data\":\"1\",\"state\":0,\n{\"name\":\"autoResetPressure\",\"data\":\"1\",\"state\":0,\n{\"name\":\"manualResetPressure\",\"data\":\"1\",\"state\":0},\n{\"name\":\"tempLimit\",\"data\":\"1\",\"state\":0,\n{\"name\":\"heatEff\",\"data\":\"0.00\",\"state\":2}]}";
Map<String, Double> map = new HashMap<>();
int index0 = 0, index1, index2;
while (true) {
// Get indices
index0 = string.indexOf("name", index0);
index1 = string.indexOf("data", index0);
index2 = string.indexOf("state", index1);
// If "name", "data", or "state" was not found
if (index0 == -1 || index1 == -1 || index2 == -1)
break;
// Get the data from the string and put it into the map
String key = string.substring(index0 + 7, index1 - 3);
Double value = Double.parseDouble(string.substring(index1 + 7, index2 - 3));
map.put(key, value);
// Update index
index0 = index2;
}
System.out.println(map);
Output:
{waterFlow=0.0, manualResetLevel=1.0, waterFeederLevel=1.0, manualResetPressure=1.0, waterTemp=-713.15, autoResetPressure=1.0, tempLimit=1.0, dieselFlow=0.0, heatEff=0.0, steamTemp=181.39}

Getting the inverse of a function that uses summation in Java

I have a program with one class, which looks like this.
public class Functions {
public static void main(String[] args) {
System.out.println(summationFunction(1)); //Prints 13
System.out.println(summationFunction(2)); //Prints 29
System.out.println(summationFunction(3)); //Prints 48
System.out.println(summationFunction(4)); //Prints 70
}
public static int summationFunction(int input) {
int summedNumber = 0;
int i = input;
while (i > 0) {
summedNumber += i * 3;
i--;
}
return 10 * input + (summedNumber);
}
}
So, this program will take in a given number and apply this function to it:
And this all works well (I have run the class Functions and everything prints just as it's supposed to.) BUT, I need to find the inverse of this function, and I need to be able to translate it to code; I do not know how to do this.
I basically need a function that will return values like this:
public static void main(String[] args) {
System.out.println(summationFunction(13)); //Prints 1
System.out.println(summationFunction(29)); //Prints 2
System.out.println(summationFunction(48)); //Prints 3
System.out.println(summationFunction(70)); //Prints 4
}
which, (as you can tell) is the opposite of the original function.
So to sum everything up, I need a function that will return the inverse of my original function (summationFunction), and I would like to know how I would model this or if there is a quick solution, in code.
One more thing: I know that I can have the method take an input and search for the most similar output of the original method, but I would like to see if there is a simpler way to do this which does not involve searching, thus giving a quicker output speed. And if you wish you can safely assume that the input of the inversed function will always be a number which will give an integer output, like 13, 29, 48, 70, etc...
By the way, if you are going to downvote the question, will you at least give a reason somewhere? The comments perhaps? I can not see any reason that this question is eligible for being downvoted, and a reason would help.
Wolfram Alpha to the rescue !
It tells you that this function can be written as :
1/24*(6*x+23)^2-529/24
So if you want to solve f(x)=a, you have :
x = 1/6*(sqrt(24*a+529)-23)
a = 70
# => x = 4
Note : Using Wolfram shouldn't prevent you from finding the answer on your own.
sum(something*i) is equal to something*sum(i) because something (3 in this case ) doesn't depend on i.
sum(i,i=1..n) is equal to n*(n+1)/2, and it's easy to prove (see Wikipedia)
So your function becomes 10*x+3*x*(x+1)/2
Expanded, it is :
(3 x^2)/2+(23 x)/2
You need to solve (3 x^2)/2+(23 x)/2 = 70, in other words :
(3 x^2)/2+(23 x)/2 - 70 = 0
It is a quadratic equation, with a=3/2, b=23/2 and c=-70 or c=-29 or c=....
You sum can be written like this 3*x*(x+1)/2 so you have equation 10*x + 3*x*(x+1)/2 = y you need to solve it.
Wolfram alpha tells that result will be 1/6.0 * (-23.0+sqrt(529.0+24.0 * y))

Java to php, Byte, Type, Array

Here is a small Java Code Snippet.
ConfigData[] cd = new ConfigData[1];
cd[0] = new ConfigData();
byte[] tmpbyte ={1,(byte)0x01};
cd[0].settmpdata(tmpbyte);
"ConfigData" is my custom Type (int, Byte Array).
In my last thread i found the tip how to Build / work with a "ByteArray" in php.
But this seems to be a question of the structure of those objects / array.
So..
How can i depict that in PHP.
I hope that this can make some guidelines for you, in the terms of what you can do in PHP, and in a relation to your code snippet (the code is tested):
<?php
// define class
class ConfigData
{
var $intVal;
var $tmpData;
}
$cData = new ConfigData(); // new ConfigData instance
$array[0] = $cData; // put it in a single element array
$array[0]->intVal = 5; // assign an integer to intVal
$array[0]->tmpData = array(1, 1, 2); // assign an array of whatever to tmpData
foreach($array[0]->tmpData as $val) // iterate through assigned array
echo $val." "; // print array item (and append " " )
?>
Now, you might also want to check how byte manipulation in PHP is achieved. I suggest you to do a little Google search, and maybe check the official manual. You question was not specific enough, so I can't say more.

Categories

Resources