|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
[JAVA] Integrare codice javascript in java
Ciao, è possibile far girare del codice javascript all'interno di una applicazione java?
Desideravo dare in pasto delle variabili ad uno script js, create con java e successivamente recuperarle... Si può fare? |
|
|
|
|
|
#2 |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Ciao
come sai, all'interno di Java 8 c'e' Nashorn, un interprete javascript, il quale permette le operazioni che hai citato. Ti basta googlare un po' per trovare quanto ti serve; per prova ho aperto questo link: http://winterbe.com/posts/2014/04/05...horn-tutorial/ e sembra che quel che vuoi fare sia possibile e facile
__________________
In God we trust; all others bring data |
|
|
|
|
|
#3 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
Beh facile... Mica tanto! Non riesco a capire come mai mi va in eccezione!
Lo script è all'interno della stessa cartella della classe. La funzione che devo chiamare ha bisogno di due parametri. Eppure mi va in eccezione questa linea: Codice:
engine.eval(new FileReader("hull.js"));
Codice:
Exception in thread "main" javax.script.ScriptException: TypeError: Cannot set property "hull" of undefined in <eval> at line number 6 at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:564) at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:548) at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:528) at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:524) at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:189) at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:249) at javaandjavascript.CHull.main(CHull.java:53) Codice:
public class CHull {
static String[][] mat2X ={{"0.064", "0.056", "0.043", "0.052", "0.063", "0.096", "0.101", "0.096", "0.09", "0.09", "0.093" },
{"0.01", "0.008", "0.003", "0.005", "0.025", "0.051", "0.055", "0.057", "0.063", "0.068", "0.064" }};
public static String toJavascriptArray(String[][] arr){
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i=0; i<arr[0].length; i++){
sb.append("[").append(arr[0][i]).append(",");
sb.append(arr[1][i]).append("]");
if(!(i==arr[0].length-1)){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
public static void main(String[] args) throws Exception {
System.out.println("array "+toJavascriptArray(mat2X));
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader("hull.js"));
Invocable invocable = (Invocable) engine;
Object result = invocable.invokeFunction("hull", toJavascriptArray(mat2X), 0.50);
System.out.println(result);
System.out.println(result.getClass());
}
}
|
|
|
|
|
|
#4 |
|
Senior Member
Iscritto dal: Nov 2005
Messaggi: 2788
|
Hai dimenticato di postare il codice di hull.js. L'errore sembra essere lì dentro, in particolare sembra che provi ad accedere alla proprietà "hull" di un oggetto null alla riga 6.
|
|
|
|
|
|
#5 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
eccolo qui in allegato!
Grazie! |
|
|
|
|
|
#6 |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Si, segnala che questa linea e' errata:
Codice:
var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.hull=e() Codice:
f.hull=e()
__________________
In God we trust; all others bring data |
|
|
|
|
|
#7 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
secondo te perché genera l'errore??
|
|
|
|
|
|
#8 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
Dunque, sono riuscito a far andare lo script.
Però ho un problema i risultati non combaciano con un test effettuato attraverso l'implementazione dello stesso su html. Ciò che ottengo dall'html avendo inserito gli stessi parametri, è questo risultato: 0.441,0.229,0.436,0.237,0.386,0.308,0.003,0.02,0.01,0.01,0.064,-0.026,0.228,0.001,0.383,0.159,0.422,0.199,0.441,0.229 Invece attraverso java, pare che non lavori, perché mi restituisce gli stessi identici valori caricati. Ho creato una classe di prova così magari riusciamo a capire meglio dove sbaglio. Grazie! Codice:
import javax.script.*;
public class TestForum {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("var global = this;");
engine.eval("!function(e){\n" +
" if(\"object\"==typeof exports&&\"undefined\"!=typeof module)module.exports=e();\n" +
" else if(\"function\"==typeof define&&define.amd)\n" +
" define([],e);\n" +
" else{\n" +
" var f;\"undefined\"!=typeof window?f=window:\"undefined\"!=typeof global?f=global:\"undefined\"!=typeof self&&(f=self),f.hull=e()\n" +
" }\n" +
" }\n" +
"(function(){\n" +
" var define,module,exports;return (function e(t,n,r){\n" +
" function s(o,u){if(!n[o]){if(!t[o]){\n" +
" var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);\n" +
" if(i)\n" +
" return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");\n" +
" throw f.code=\"MODULE_NOT_FOUND\",f\n" +
" }\n" +
" var l=n[o]={\n" +
" exports:{\n" +
" }\n" +
" };\n" +
" t[o][0].call(l.exports,function(e){\n" +
" var n=t[o][1][e];return s(n?n:e)\n" +
" },l,l.exports,e,t,n,r)\n" +
" }\n" +
" return n[o].exports}var i=typeof require==\"function\"&&require;\n" +
" for(var o=0;o<r.length;o++)s(r[o]);\n" +
" return s\n" +
" }\n" +
" )({\n" +
" 1:[function(require,module,exports){\n" +
"\n" +
"function Grid(points) {\n" +
" var _cells = [];\n" +
"\n" +
" points.forEach(function(point) {\n" +
" var cellXY = this.point2CellXY(point),\n" +
" x = cellXY[0],\n" +
" y = cellXY[1];\n" +
" if (_cells[x] === undefined) {\n" +
" _cells[x] = [];\n" +
" }\n" +
" if (_cells[x][y] === undefined) {\n" +
" _cells[x][y] = [];\n" +
" }\n" +
" _cells[x][y].push(point);\n" +
" }, this);\n" +
"\n" +
" this.cellPoints = function(x, y) { // (Number, Number) -> Array\n" +
" return (_cells[x] !== undefined && _cells[x][y] !== undefined) ? _cells[x][y] : [];\n" +
" };\n" +
"\n" +
" this.removePoint = function(point) { // (Array) -> Array\n" +
" var cellXY = this.point2CellXY(point),\n" +
" cell = _cells[cellXY[0]][cellXY[1]],\n" +
" pointIdxInCell;\n" +
" \n" +
" for (var i = 0; i < cell.length; i++) {\n" +
" if (cell[i][0] === point[0] && cell[i][1] === point[1]) {\n" +
" pointIdxInCell = i;\n" +
" break;\n" +
" }\n" +
" }\n" +
"\n" +
" cell.splice(pointIdxInCell, 1);\n" +
"\n" +
" return cell;\n" +
" };\n" +
"}\n" +
"\n" +
"Grid.prototype = {\n" +
" point2CellXY: function(point) { // (Array) -> Array\n" +
" var x = parseInt(point[0] / Grid.CELL_SIZE),\n" +
" y = parseInt(point[1] / Grid.CELL_SIZE);\n" +
" return [x, y];\n" +
" },\n" +
"\n" +
" rangePoints: function(bbox) { // (Array) -> Array\n" +
" var tlCellXY = this.point2CellXY([bbox[0], bbox[1]]),\n" +
" brCellXY = this.point2CellXY([bbox[2], bbox[3]]),\n" +
" points = [];\n" +
"\n" +
" for (var x = tlCellXY[0]; x <= brCellXY[0]; x++) {\n" +
" for (var y = tlCellXY[1]; y <= brCellXY[1]; y++) {\n" +
" points = points.concat(this.cellPoints(x, y));\n" +
" }\n" +
" }\n" +
"\n" +
" return points;\n" +
" },\n" +
"\n" +
" addBorder2Bbox: function(bbox, border) { // (Array, Number) -> Array\n" +
" return [\n" +
" bbox[0] - (border * Grid.CELL_SIZE),\n" +
" bbox[1] - (border * Grid.CELL_SIZE),\n" +
" bbox[2] + (border * Grid.CELL_SIZE),\n" +
" bbox[3] + (border * Grid.CELL_SIZE)\n" +
" ];\n" +
" }\n" +
"};\n" +
"\n" +
"function grid(points) {\n" +
" return new Grid(points);\n" +
"}\n" +
"\n" +
"Grid.CELL_SIZE = 10;\n" +
"\n" +
"module.exports = grid;\n" +
"},{}],2:[function(require,module,exports){\n" +
"/*\n" +
" (c) 2014-2015, Andrii Heonia\n" +
" Hull.js, a JavaScript library for concave hull generation by set of points.\n" +
" https://github.com/AndriiHeonia/hull\n" +
"*/\n" +
"\n" +
"'use strict';\n" +
"\n" +
"var intersect = require('./intersect.js');\n" +
"var grid = require('./grid.js');\n" +
"\n" +
"function _formatToXy(pointset, format) {\n" +
" if (format === undefined) {\n" +
" return pointset;\n" +
" }\n" +
" return pointset.map(function(pt) {\n" +
" /*jslint evil: true */\n" +
" var _getXY = new Function('pt', 'return [pt' + format[0] + ',' + 'pt' + format[1] + '];');\n" +
" return _getXY(pt);\n" +
" });\n" +
"}\n" +
"\n" +
"function _xyToFormat(pointset, format) {\n" +
" if (format === undefined) {\n" +
" return pointset;\n" +
" }\n" +
" return pointset.map(function(pt) {\n" +
" /*jslint evil: true */\n" +
" var _getObj = new Function('pt', 'var o = {}; o' + format[0] + '= pt[0]; o' + format[1] + '= pt[1]; return o;');\n" +
" return _getObj(pt);\n" +
" });\n" +
"}\n" +
"\n" +
"function _sortByX(pointset) {\n" +
" return pointset.sort(function(a, b) {\n" +
" if (a[0] == b[0]) {\n" +
" return a[1] - b[1]; \n" +
" } else { \n" +
" return a[0] - b[0]; \n" +
" }\n" +
" });\n" +
"}\n" +
"\n" +
"function _getMaxY(pointset) {\n" +
" var maxY = -Infinity;\n" +
" for (var i = pointset.length - 1; i >= 0; i--) {\n" +
" if (pointset[i][1] > maxY) {\n" +
" maxY = pointset[i][1];\n" +
" }\n" +
" }\n" +
" return maxY;\n" +
"}\n" +
"\n" +
"function _upperTangent(pointset) {\n" +
" var lower = [];\n" +
" for (var l = 0; l < pointset.length; l++) {\n" +
" while (lower.length >= 2 && (_cross(lower[lower.length - 2], lower[lower.length - 1], pointset[l]) <= 0)) {\n" +
" lower.pop();\n" +
" }\n" +
" lower.push(pointset[l]);\n" +
" }\n" +
" lower.pop();\n" +
" return lower;\n" +
"}\n" +
"\n" +
"function _lowerTangent(pointset) {\n" +
" var reversed = pointset.reverse(),\n" +
" upper = [];\n" +
" for (var u = 0; u < reversed.length; u++) {\n" +
" while (upper.length >= 2 && (_cross(upper[upper.length - 2], upper[upper.length - 1], reversed[u]) <= 0)) {\n" +
" upper.pop();\n" +
" }\n" +
" upper.push(reversed[u]);\n" +
" }\n" +
" upper.pop();\n" +
" return upper;\n" +
"}\n" +
"\n" +
"function _cross(o, a, b) {\n" +
" return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); \n" +
"}\n" +
"\n" +
"function _sqLength(a, b) {\n" +
" return Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2);\n" +
"}\n" +
"\n" +
"function _cos(o, a, b) {\n" +
" var aShifted = [a[0] - o[0], a[1] - o[1]],\n" +
" bShifted = [b[0] - o[0], b[1] - o[1]],\n" +
" sqALen = _sqLength(o, a),\n" +
" sqBLen = _sqLength(o, b),\n" +
" dot = aShifted[0] * bShifted[0] + aShifted[1] * bShifted[1];\n" +
"\n" +
" return dot / Math.sqrt(sqALen * sqBLen);\n" +
"}\n" +
"\n" +
"function _intersect(segment, pointset) {\n" +
" for (var i = 0; i < pointset.length - 1; i++) {\n" +
" var seg = [pointset[i], pointset[i + 1]];\n" +
" if (segment[0][0] === seg[0][0] && segment[0][1] === seg[0][1] ||\n" +
" segment[0][0] === seg[1][0] && segment[0][1] === seg[1][1]) {\n" +
" continue;\n" +
" }\n" +
" if (intersect(segment, seg)) {\n" +
" return true;\n" +
" }\n" +
" }\n" +
" return false;\n" +
"}\n" +
"\n" +
"function _bBoxAround(edge, boxSize) {\n" +
" var minX, maxX, minY, maxY;\n" +
"\n" +
" if (edge[0][0] < edge[1][0]) {\n" +
" minX = edge[0][0] - boxSize;\n" +
" maxX = edge[1][0] + boxSize;\n" +
" } else {\n" +
" minX = edge[1][0] - boxSize;\n" +
" maxX = edge[0][0] + boxSize;\n" +
" }\n" +
"\n" +
" if (edge[0][1] < edge[1][1]) {\n" +
" minY = edge[0][1] - boxSize;\n" +
" maxY = edge[1][1] + boxSize;\n" +
" } else {\n" +
" minY = edge[1][1] - boxSize;\n" +
" maxY = edge[0][1] + boxSize;\n" +
" }\n" +
"\n" +
" return [\n" +
" minX, minY, // tl\n" +
" maxX, maxY // br\n" +
" ];\n" +
"}\n" +
"\n" +
"function _midPoint(edge, innerPoints, convex) {\n" +
" var point = null,\n" +
" angle1Cos = MAX_CONCAVE_ANGLE_COS,\n" +
" angle2Cos = MAX_CONCAVE_ANGLE_COS,\n" +
" a1Cos, a2Cos;\n" +
"\n" +
" for (var i = 0; i < innerPoints.length; i++) {\n" +
" a1Cos = _cos(edge[0], edge[1], innerPoints[i]);\n" +
" a2Cos = _cos(edge[1], edge[0], innerPoints[i]);\n" +
"\n" +
" if (a1Cos > angle1Cos && a2Cos > angle2Cos &&\n" +
" !_intersect([edge[0], innerPoints[i]], convex) &&\n" +
" !_intersect([edge[1], innerPoints[i]], convex)) {\n" +
"\n" +
" angle1Cos = a1Cos;\n" +
" angle2Cos = a2Cos;\n" +
" point = innerPoints[i];\n" +
" }\n" +
" }\n" +
"\n" +
" return point;\n" +
"}\n" +
"\n" +
"function _concave(convex, maxSqEdgeLen, maxSearchBBoxSize, grid) {\n" +
" var edge,\n" +
" border,\n" +
" bBoxSize,\n" +
" midPoint,\n" +
" bBoxAround, \n" +
" midPointInserted = false;\n" +
"\n" +
" for (var i = 0; i < convex.length - 1; i++) {\n" +
" edge = [convex[i], convex[i + 1]];\n" +
"\n" +
" if (_sqLength(edge[0], edge[1]) < maxSqEdgeLen) { continue; }\n" +
"\n" +
" border = 0;\n" +
" bBoxSize = MIN_SEARCH_BBOX_SIZE;\n" +
" bBoxAround = _bBoxAround(edge, bBoxSize);\n" +
" do {\n" +
" bBoxAround = grid.addBorder2Bbox(bBoxAround, border);\n" +
" bBoxSize = bBoxAround[2] - bBoxAround[0];\n" +
" midPoint = _midPoint(edge, grid.rangePoints(bBoxAround), convex); \n" +
" border++;\n" +
" } while (midPoint === null && maxSearchBBoxSize > bBoxSize);\n" +
"\n" +
" if (midPoint !== null) {\n" +
" convex.splice(i + 1, 0, midPoint);\n" +
" grid.removePoint(midPoint);\n" +
" midPointInserted = true;\n" +
" }\n" +
" }\n" +
"\n" +
" if (midPointInserted) {\n" +
" return _concave(convex, maxSqEdgeLen, maxSearchBBoxSize, grid);\n" +
" }\n" +
"\n" +
" return convex;\n" +
"}\n" +
"\n" +
"function hull(pointset, concavity, format) {\n" +
" var lower, upper, convex,\n" +
" innerPoints,\n" +
" maxSearchBBoxSize,\n" +
" maxEdgeLen = concavity || 20;\n" +
"\n" +
" if (pointset.length < 4) {\n" +
" return pointset;\n" +
" }\n" +
"\n" +
" pointset = _sortByX(_formatToXy(pointset, format));\n" +
" upper = _upperTangent(pointset);\n" +
" lower = _lowerTangent(pointset);\n" +
" convex = lower.concat(upper);\n" +
" convex.push(pointset[0]);\n" +
"\n" +
" maxSearchBBoxSize = Math.max(pointset[pointset.length - 1][0], _getMaxY(convex)) * MAX_SEARCH_BBOX_SIZE_PERCENT;\n" +
" innerPoints = pointset.filter(function(pt) {\n" +
" return convex.indexOf(pt) < 0;\n" +
" });\n" +
" \n" +
" return _xyToFormat(_concave(convex, Math.pow(maxEdgeLen, 2), maxSearchBBoxSize, grid(innerPoints)), format);\n" +
"}\n" +
"\n" +
"var MAX_CONCAVE_ANGLE_COS = Math.cos(90 / (180 / Math.PI)); // angle = 90 deg\n" +
"var MIN_SEARCH_BBOX_SIZE = 5;\n" +
"var MAX_SEARCH_BBOX_SIZE_PERCENT = 0.8;\n" +
"\n" +
"module.exports = hull;\n" +
"},{\"./grid.js\":1,\"./intersect.js\":3}],3:[function(require,module,exports){\n" +
"function ccw(x1, y1, x2, y2, x3, y3) { \n" +
" var cw = ((y3 - y1) * (x2 - x1)) - ((y2 - y1) * (x3 - x1));\n" +
" return cw > 0 ? true : cw < 0 ? false : true; // colinear\n" +
"}\n" +
"\n" +
"function intersect(seg1, seg2) {\n" +
" var x1 = seg1[0][0], y1 = seg1[0][1],\n" +
" x2 = seg1[1][0], y2 = seg1[1][1],\n" +
" x3 = seg2[0][0], y3 = seg2[0][1],\n" +
" x4 = seg2[1][0], y4 = seg2[1][1];\n" +
" return ccw(x1, y1, x3, y3, x4, y4) !== ccw(x2, y2, x3, y3, x4, y4) && ccw(x1, y1, x2, y2, x3, y3) !== ccw(x1, y1, x2, y2, x4, y4);\n" +
"}\n" +
"\n" +
"module.exports = intersect;\n" +
"},{}]},{},[2])(2)\n" +
"})");
Invocable jsInvoke = (Invocable) engine;
Object[] result = (Object[]) jsInvoke.invokeFunction("hull", new Object[][] {
{ 0.441, 0.436, 0.386, 0.389, 0.389, 0.386, 0.386, 0.386, 0.386, 0.383, 0.377, 0.377, 0.377, 0.368, 0.278, 0.26, 0.258, 0.258, 0.257,
0.231, 0.229, 0.226, 0.215, 0.122, 0.114, 0.102, 0.102, 0.093, 0.003, 0.01, 0.064, 0.146, 0.213, 0.228, 0.268, 0.28,
0.345, 0.373, 0.377, 0.378, 0.38, 0.381, 0.383, 0.422, 0.441},
{ 0.229, 0.237, 0.308, 0.273, 0.269, 0.264, 0.252, 0.251, 0.249, 0.244, 0.239, 0.207, 0.204, 0.199, 0.168, 0.154, 0.153, 0.144,
0.128, 0.119, 0.111, 0.105, 0.1, 0.088, 0.087, 0.075, 0.067, 0.049, 0.02, 0.01, -0.026, 0, 0.005, 0.001, 0.081, 0.093,
0.163, 0.16, 0.159, 0.159, 0.159, 0.159, 0.159, 0.199, 0.229}}, 0.50);
// Output Dati
for(Object obj : result) {
Object[] points = (Object[]) obj;
for(Object d : points) System.out.print(d + "; ");
System.out.println();
}
// Devo Ottenere in outPut questi valori:
// 0.441,0.229,0.436,0.237,0.386,0.308,0.003,0.02,0.01,0.01,0.064,-0.026,0.228,0.001,0.383,0.159,0.422,0.199,0.441,0.229
}
}
|
|
|
|
|
|
#9 |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Ciao
prima di smazzare il codice (che non mi sembra proprio banalissimo), farei una prova a stampare i dati di ingresso e di uscita dello script nelle due versioni. Ovviamente le cose devono coincidere. Questo ti permette di verificare subito se ci sono problemi (per esempio, i dati di ingresso non erano passati correttamente, o sono scambiati, ecc). Visto che si tratta di conti, puoi ripetere il procedimento in vari punti ("checkpoint") nel tuo programma per verificare fin dove coincidono. A quel punto avrai abbastanza elementi per isolare un eventuale errore...
__________________
In God we trust; all others bring data |
|
|
|
|
|
#10 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
Il problema è proprio questo. Confrontando i due codici i risultati non coincidono.. L'ho anche scritto nel codice.
|
|
|
|
|
|
#11 | |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Quote:
Un po' quando un elettronico attacca l'oscilloscopio ad un circuito sapendo che in questo punto deve vedere una sinusoide, in quel punto un'onda quadra e via dicendo. Se riesci a trovare dei punti cosi' (dovrebbero esserci, visto che si tratta di conti) e stampi i risultati nelle due versioni, dovresti trovare dove la versione sotto java "sbanda"...
__________________
In God we trust; all others bring data |
|
|
|
|
|
|
#12 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
scolta, credi che non abbia già effettuato un check su tutto?
Ho scannerizzato il codice, riga per riga, debug e non ne vengo fuori. Sarà che JS non lo conosco, ma i tuoi consigli, sinceramente, hanno l'utilità di un pettine per un calvo... ![]() Non credo che entrambi i codici "sbandano", come tu affermi. Se io do in pasto dei dati e la modalità è quella, l'unico mio dubbio è che JS non li "digerisca" per come vengono passati. Quindi chiedo come devono essere passati sempre se quello postato sia il metodo corretto. Ho postato tutto, se vuoi fare una prova e hai la dritta corretta la posti altrimenti è anche inutile scrivere "certi" interventi, comunque utili per chi è alle prime armi, ma non per chi ha un problema da risolvere... Ultima modifica di JohnMarston : 28-10-2015 alle 14:11. |
|
|
|
|
|
#13 | ||
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Quote:
Quote:
Io ho fatto cosi': Codice:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
StringWriter sw=new StringWriter();
engine.getContext().setWriter(sw);
engine.eval("var global = this;");
engine.eval( < qui c'e' il resto del tuo codice > );
System.out.println("Captured output:\n"+sw);
Codice:
...
" print('sono in questo punto, la variabile v vale: ' + v);\n" +
...
__________________
In God we trust; all others bring data Ultima modifica di sottovento : 29-10-2015 alle 09:25. |
||
|
|
|
|
|
#14 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
Avrai trovato l'errore ma non hai postato la soluzione o per lo meno non hai neanche argomentato sulle cause che generano quell'errore che tu hai visto.... Sempre spazzolozza per calvi...
Oltre a ciò, per proseguire nel 3d, sottovaluti un punto molto importante, che comunque ho scritto... Il JS non lo conosco e quindi anche se dai suggerimenti o argomenti, non saprei neanche come intervenire! Improvvisando, mi sono messo a caccia della variabile "v" e non la trovo. Suppongo che tu abbia confuso "v" con "f", quindi al di là del buio totale, printando f ottengo object global. Detto questo, se tu sei riuscito a far andare lo script ottenendo questi risultati (fine codice): Codice:
// Devo Ottenere in outPut questi valori: // 0.441,0.229,0.436,0.237,0.386,0.308,0.003,0.02,0.01,0.01,0.064,-0.026,0.228,0.001,0.383,0.159,0.422,0.199,0.441,0.229 Considera che nel momento in cui tu posti la soluzione, non è mica finita qui, perché successivamente dovrò nuovamente modificare e riadattare il codice in base ai suggerimenti ricevuti, quindi il lavoro che dovrò fare è abbastanza lungo. |
|
|
|
|
|
#15 |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Quello della variabile v era un esempio.
Ovviamente se modificavi il codice cosi': Codice:
"function hull(pointset, concavity, format) {\n" +
" print('Ho chiamato la funzione hull()');\n" +
" print('pointset = ' + pointset);\n" +
" print('concavity = ' + concavity);\n" +
" print('format = ' + format);\n" +
" var lower, upper, convex,\n" +
" innerPoints,\n" +
" maxSearchBBoxSize,\n" +
" maxEdgeLen = concavity || 20;\n" +
"\n" +
" if (pointset.length < 4) {\n" +
" print('Point set length is ' + pointset.length + ' that is < 4; therefore I return it');\n" +
" print('here the pointset:');\n" +
" for (var i = 0; i < pointset.length; i++)\n" +
" print('pointset[' + i + '] = (' + pointset[i][0] + ', ' + pointset[i][1] + ')');\n" +
" return pointset;\n" +
" }\n" +
Codice:
Point set length is 2 that is < 4; therefore I return it here the pointset: pointset[0] = (0.441, 0.436) pointset[1] = (0.229, 0.237)
__________________
In God we trust; all others bring data |
|
|
|
|
|
#16 |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
No, non ti è chiaro un passaggio, di JS non ci capisco una mazza!
Devi passarmi il tuo stesso codice. Non ho i tuoi stessi risultati pur inserendo la modifica che hai fatto nel mio! Non mi printa!!!! Passa il codice!!! |
|
|
|
|
|
#17 |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Codice:
import java.io.*;
import java.nio.*;
import javax.script.*;
public class CHull
{
static String[][] mat2X ={{"0.064", "0.056", "0.043", "0.052", "0.063", "0.096", "0.101", "0.096", "0.09", "0.09", "0.093" },
{"0.01", "0.008", "0.003", "0.005", "0.025", "0.051", "0.055", "0.057", "0.063", "0.068", "0.064" }};
public static String toJavascriptArray(String[][] arr)
{
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i=0; i<arr[0].length; i++){
sb.append("[").append(arr[0][i]).append(",");
sb.append(arr[1][i]).append("]");
if(!(i==arr[0].length-1)){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
public static void main(String[] args) throws Exception
{
System.out.println("array "+toJavascriptArray(mat2X));
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// TEST
StringWriter sw=new StringWriter();
engine.getContext().setWriter(sw);
engine.eval("var global = this;");
engine.eval("!function(e){\n" +
" if(\"object\"==typeof exports&&\"undefined\"!=typeof module)module.exports=e();\n" +
" else if(\"function\"==typeof define&&define.amd)\n" +
" {\n" +
" print('define[] called');\n" +
" define([],e);\n" +
" }\n" +
" else{\n" +
" print('else branch');\n" +
" var f;\"undefined\"!=typeof window?f=window:\"undefined\"!=typeof global?f=global:\"undefined\"!=typeof self&&(f=self),f.hull=e()\n" +
" }\n" +
" }\n" +
"(function(){\n" +
" var define,module,exports;return (function e(t,n,r){\n" +
" function s(o,u){if(!n[o]){if(!t[o]){\n" +
" var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);\n" +
" if(i)\n" +
" return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");\n" +
" throw f.code=\"MODULE_NOT_FOUND\",f\n" +
" }\n" +
" var l=n[o]={\n" +
" exports:{\n" +
" }\n" +
" };\n" +
" t[o][0].call(l.exports,function(e){\n" +
" var n=t[o][1][e];return s(n?n:e)\n" +
" },l,l.exports,e,t,n,r)\n" +
" }\n" +
" return n[o].exports}var i=typeof require==\"function\"&&require;\n" +
" for(var o=0;o<r.length;o++)s(r[o]);\n" +
" return s\n" +
" }\n" +
" )({\n" +
" 1:[function(require,module,exports){\n" +
"\n" +
"function Grid(points) {\n" +
" var _cells = [];\n" +
"\n" +
" points.forEach(function(point) {\n" +
" var cellXY = this.point2CellXY(point),\n" +
" x = cellXY[0],\n" +
" y = cellXY[1];\n" +
" if (_cells[x] === undefined) {\n" +
" _cells[x] = [];\n" +
" }\n" +
" if (_cells[x][y] === undefined) {\n" +
" _cells[x][y] = [];\n" +
" }\n" +
" _cells[x][y].push(point);\n" +
" }, this);\n" +
"\n" +
" this.cellPoints = function(x, y) { // (Number, Number) -> Array\n" +
" return (_cells[x] !== undefined && _cells[x][y] !== undefined) ? _cells[x][y] : [];\n" +
" };\n" +
"\n" +
" this.removePoint = function(point) { // (Array) -> Array\n" +
" var cellXY = this.point2CellXY(point),\n" +
" cell = _cells[cellXY[0]][cellXY[1]],\n" +
" pointIdxInCell;\n" +
" \n" +
" for (var i = 0; i < cell.length; i++) {\n" +
" if (cell[i][0] === point[0] && cell[i][1] === point[1]) {\n" +
" pointIdxInCell = i;\n" +
" break;\n" +
" }\n" +
" }\n" +
"\n" +
" cell.splice(pointIdxInCell, 1);\n" +
"\n" +
" return cell;\n" +
" };\n" +
"}\n" +
"\n" +
"Grid.prototype = {\n" +
" point2CellXY: function(point) { // (Array) -> Array\n" +
" var x = parseInt(point[0] / Grid.CELL_SIZE),\n" +
" y = parseInt(point[1] / Grid.CELL_SIZE);\n" +
" return [x, y];\n" +
" },\n" +
"\n" +
" rangePoints: function(bbox) { // (Array) -> Array\n" +
" var tlCellXY = this.point2CellXY([bbox[0], bbox[1]]),\n" +
" brCellXY = this.point2CellXY([bbox[2], bbox[3]]),\n" +
" points = [];\n" +
"\n" +
" for (var x = tlCellXY[0]; x <= brCellXY[0]; x++) {\n" +
" for (var y = tlCellXY[1]; y <= brCellXY[1]; y++) {\n" +
" points = points.concat(this.cellPoints(x, y));\n" +
" }\n" +
" }\n" +
"\n" +
" return points;\n" +
" },\n" +
"\n" +
" addBorder2Bbox: function(bbox, border) { // (Array, Number) -> Array\n" +
" return [\n" +
" bbox[0] - (border * Grid.CELL_SIZE),\n" +
" bbox[1] - (border * Grid.CELL_SIZE),\n" +
" bbox[2] + (border * Grid.CELL_SIZE),\n" +
" bbox[3] + (border * Grid.CELL_SIZE)\n" +
" ];\n" +
" }\n" +
"};\n" +
"\n" +
"function grid(points) {\n" +
" return new Grid(points);\n" +
"}\n" +
"\n" +
"Grid.CELL_SIZE = 10;\n" +
"\n" +
"module.exports = grid;\n" +
"},{}],2:[function(require,module,exports){\n" +
"/*\n" +
" (c) 2014-2015, Andrii Heonia\n" +
" Hull.js, a JavaScript library for concave hull generation by set of points.\n" +
" https://github.com/AndriiHeonia/hull\n" +
"*/\n" +
"\n" +
"'use strict';\n" +
"\n" +
"var intersect = require('./intersect.js');\n" +
"var grid = require('./grid.js');\n" +
"\n" +
"function _formatToXy(pointset, format) {\n" +
" if (format === undefined) {\n" +
" print('_formatToXy() - format undefined, return the pointset');\n" +
" return pointset;\n" +
" }\n" +
" print('Format is defined, keep going');\n" +
" return pointset.map(function(pt) {\n" +
" /*jslint evil: true */\n" +
" print('_formatToXy check#1');\n" +
" var _getXY = new Function('pt', 'return [pt' + format[0] + ',' + 'pt' + format[1] + '];');\n" +
" print('_formatToXy check#2');\n" +
" return _getXY(pt);\n" +
" });\n" +
"}\n" +
"\n" +
"function _xyToFormat(pointset, format) {\n" +
" if (format === undefined) {\n" +
" return pointset;\n" +
" }\n" +
" return pointset.map(function(pt) {\n" +
" /*jslint evil: true */\n" +
" var _getObj = new Function('pt', 'var o = {}; o' + format[0] + '= pt[0]; o' + format[1] + '= pt[1]; return o;');\n" +
" return _getObj(pt);\n" +
" });\n" +
"}\n" +
"\n" +
"function _sortByX(pointset) {\n" +
" return pointset.sort(function(a, b) {\n" +
" if (a[0] == b[0]) {\n" +
" return a[1] - b[1]; \n" +
" } else { \n" +
" return a[0] - b[0]; \n" +
" }\n" +
" });\n" +
"}\n" +
"\n" +
"function _getMaxY(pointset) {\n" +
" var maxY = -Infinity;\n" +
" for (var i = pointset.length - 1; i >= 0; i--) {\n" +
" if (pointset[i][1] > maxY) {\n" +
" maxY = pointset[i][1];\n" +
" }\n" +
" }\n" +
" return maxY;\n" +
"}\n" +
"\n" +
"function _upperTangent(pointset) {\n" +
" var lower = [];\n" +
" for (var l = 0; l < pointset.length; l++) {\n" +
" while (lower.length >= 2 && (_cross(lower[lower.length - 2], lower[lower.length - 1], pointset[l]) <= 0)) {\n" +
" lower.pop();\n" +
" }\n" +
" lower.push(pointset[l]);\n" +
" }\n" +
" lower.pop();\n" +
" return lower;\n" +
"}\n" +
"\n" +
"function _lowerTangent(pointset) {\n" +
" print('lowerTangent() called with pointset=' + pointset);\n" +
" var reversed = pointset.reverse(),\n" +
" upper = [];\n" +
" for (var u = 0; u < reversed.length; u++) {\n" +
" while (upper.length >= 2 && (_cross(upper[upper.length - 2], upper[upper.length - 1], reversed[u]) <= 0)) {\n" +
" upper.pop();\n" +
" }\n" +
" upper.push(reversed[u]);\n" +
" }\n" +
" upper.pop();\n" +
" return upper;\n" +
"}\n" +
"\n" +
"function _cross(o, a, b) {\n" +
" return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); \n" +
"}\n" +
"\n" +
"function _sqLength(a, b) {\n" +
" return Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2);\n" +
"}\n" +
"\n" +
"function _cos(o, a, b) {\n" +
" var aShifted = [a[0] - o[0], a[1] - o[1]],\n" +
" bShifted = [b[0] - o[0], b[1] - o[1]],\n" +
" sqALen = _sqLength(o, a),\n" +
" sqBLen = _sqLength(o, b),\n" +
" dot = aShifted[0] * bShifted[0] + aShifted[1] * bShifted[1];\n" +
"\n" +
" return dot / Math.sqrt(sqALen * sqBLen);\n" +
"}\n" +
"\n" +
"function _intersect(segment, pointset) {\n" +
" for (var i = 0; i < pointset.length - 1; i++) {\n" +
" var seg = [pointset[i], pointset[i + 1]];\n" +
" if (segment[0][0] === seg[0][0] && segment[0][1] === seg[0][1] ||\n" +
" segment[0][0] === seg[1][0] && segment[0][1] === seg[1][1]) {\n" +
" continue;\n" +
" }\n" +
" if (intersect(segment, seg)) {\n" +
" return true;\n" +
" }\n" +
" }\n" +
" return false;\n" +
"}\n" +
"\n" +
"function _bBoxAround(edge, boxSize) {\n" +
" var minX, maxX, minY, maxY;\n" +
"\n" +
" if (edge[0][0] < edge[1][0]) {\n" +
" minX = edge[0][0] - boxSize;\n" +
" maxX = edge[1][0] + boxSize;\n" +
" } else {\n" +
" minX = edge[1][0] - boxSize;\n" +
" maxX = edge[0][0] + boxSize;\n" +
" }\n" +
"\n" +
" if (edge[0][1] < edge[1][1]) {\n" +
" minY = edge[0][1] - boxSize;\n" +
" maxY = edge[1][1] + boxSize;\n" +
" } else {\n" +
" minY = edge[1][1] - boxSize;\n" +
" maxY = edge[0][1] + boxSize;\n" +
" }\n" +
"\n" +
" return [\n" +
" minX, minY, // tl\n" +
" maxX, maxY // br\n" +
" ];\n" +
"}\n" +
"\n" +
"function _midPoint(edge, innerPoints, convex) {\n" +
" var point = null,\n" +
" angle1Cos = MAX_CONCAVE_ANGLE_COS,\n" +
" angle2Cos = MAX_CONCAVE_ANGLE_COS,\n" +
" a1Cos, a2Cos;\n" +
"\n" +
" for (var i = 0; i < innerPoints.length; i++) {\n" +
" a1Cos = _cos(edge[0], edge[1], innerPoints[i]);\n" +
" a2Cos = _cos(edge[1], edge[0], innerPoints[i]);\n" +
"\n" +
" if (a1Cos > angle1Cos && a2Cos > angle2Cos &&\n" +
" !_intersect([edge[0], innerPoints[i]], convex) &&\n" +
" !_intersect([edge[1], innerPoints[i]], convex)) {\n" +
"\n" +
" angle1Cos = a1Cos;\n" +
" angle2Cos = a2Cos;\n" +
" point = innerPoints[i];\n" +
" }\n" +
" }\n" +
"\n" +
" return point;\n" +
"}\n" +
"\n" +
"function _concave(convex, maxSqEdgeLen, maxSearchBBoxSize, grid) {\n" +
" var edge,\n" +
" border,\n" +
" bBoxSize,\n" +
" midPoint,\n" +
" bBoxAround, \n" +
" midPointInserted = false;\n" +
"\n" +
" for (var i = 0; i < convex.length - 1; i++) {\n" +
" edge = [convex[i], convex[i + 1]];\n" +
"\n" +
" if (_sqLength(edge[0], edge[1]) < maxSqEdgeLen) { continue; }\n" +
"\n" +
" border = 0;\n" +
" bBoxSize = MIN_SEARCH_BBOX_SIZE;\n" +
" bBoxAround = _bBoxAround(edge, bBoxSize);\n" +
" do {\n" +
" bBoxAround = grid.addBorder2Bbox(bBoxAround, border);\n" +
" bBoxSize = bBoxAround[2] - bBoxAround[0];\n" +
" midPoint = _midPoint(edge, grid.rangePoints(bBoxAround), convex); \n" +
" border++;\n" +
" } while (midPoint === null && maxSearchBBoxSize > bBoxSize);\n" +
"\n" +
" if (midPoint !== null) {\n" +
" convex.splice(i + 1, 0, midPoint);\n" +
" grid.removePoint(midPoint);\n" +
" midPointInserted = true;\n" +
" }\n" +
" }\n" +
"\n" +
" if (midPointInserted) {\n" +
" return _concave(convex, maxSqEdgeLen, maxSearchBBoxSize, grid);\n" +
" }\n" +
"\n" +
" return convex;\n" +
"}\n" +
"\n" +
"function hull(pointset, concavity, format) {\n" +
" print('Ho chiamato la funzione hull()');\n" +
" print('pointset = ' + pointset);\n" +
" print('concavity = ' + concavity);\n" +
" print('format = ' + format);\n" +
" var lower, upper, convex,\n" +
" innerPoints,\n" +
" maxSearchBBoxSize,\n" +
" maxEdgeLen = concavity || 20;\n" +
"\n" +
" if (pointset.length < 4) {\n" +
" print('Point set length is ' + pointset.length + ' that is < 4; therefore I return it');\n" +
" print('here the pointset:');\n" +
" for (var i = 0; i < pointset.length; i++)\n" +
" print('pointset[' + i + '] = (' + pointset[i][0] + ', ' + pointset[i][1] + ')');\n" +
" return pointset;\n" +
" }\n" +
"\n" +
" print('Sort the pointset by X');\n" +
" pointset = _sortByX(_formatToXy(pointset, format));\n" +
" upper = _upperTangent(pointset);\n" +
" lower = _lowerTangent(pointset);\n" +
" convex = lower.concat(upper);\n" +
" convex.push(pointset[0]);\n" +
"\n" +
" maxSearchBBoxSize = Math.max(pointset[pointset.length - 1][0], _getMaxY(convex)) * MAX_SEARCH_BBOX_SIZE_PERCENT;\n" +
" innerPoints = pointset.filter(function(pt) {\n" +
" return convex.indexOf(pt) < 0;\n" +
" });\n" +
" \n" +
" return _xyToFormat(_concave(convex, Math.pow(maxEdgeLen, 2), maxSearchBBoxSize, grid(innerPoints)), format);\n" +
"}\n" +
"\n" +
"var MAX_CONCAVE_ANGLE_COS = Math.cos(90 / (180 / Math.PI)); // angle = 90 deg\n" +
"var MIN_SEARCH_BBOX_SIZE = 5;\n" +
"var MAX_SEARCH_BBOX_SIZE_PERCENT = 0.8;\n" +
"\n" +
"module.exports = hull;\n" +
"},{\"./grid.js\":1,\"./intersect.js\":3}],3:[function(require,module,exports){\n" +
"function ccw(x1, y1, x2, y2, x3, y3) { \n" +
" var cw = ((y3 - y1) * (x2 - x1)) - ((y2 - y1) * (x3 - x1));\n" +
" return cw > 0 ? true : cw < 0 ? false : true; // colinear\n" +
"}\n" +
"\n" +
"function intersect(seg1, seg2) {\n" +
" var x1 = seg1[0][0], y1 = seg1[0][1],\n" +
" x2 = seg1[1][0], y2 = seg1[1][1],\n" +
" x3 = seg2[0][0], y3 = seg2[0][1],\n" +
" x4 = seg2[1][0], y4 = seg2[1][1];\n" +
" return ccw(x1, y1, x3, y3, x4, y4) !== ccw(x2, y2, x3, y3, x4, y4) && ccw(x1, y1, x2, y2, x3, y3) !== ccw(x1, y1, x2, y2, x4, y4);\n" +
"}\n" +
"\n" +
"module.exports = intersect;\n" +
"},{}]},{},[2])(2)\n" +
"})");
Invocable jsInvoke = (Invocable) engine;
Object[] result = (Object[]) jsInvoke.invokeFunction("hull", new Object[][] {
{ 0.441, 0.436, 0.386, 0.389, 0.389, 0.386, 0.386, 0.386, 0.386, 0.383, 0.377, 0.377, 0.377, 0.368, 0.278, 0.26, 0.258, 0.258, 0.257,
0.231, 0.229, 0.226, 0.215, 0.122, 0.114, 0.102, 0.102, 0.093, 0.003, 0.01, 0.064, 0.146, 0.213, 0.228, 0.268, 0.28,
0.345, 0.373, 0.377, 0.378, 0.38, 0.381, 0.383, 0.422, 0.441},
{ 0.229, 0.237, 0.308, 0.273, 0.269, 0.264, 0.252, 0.251, 0.249, 0.244, 0.239, 0.207, 0.204, 0.199, 0.168, 0.154, 0.153, 0.144,
0.128, 0.119, 0.111, 0.105, 0.1, 0.088, 0.087, 0.075, 0.067, 0.049, 0.02, 0.01, -0.026, 0, 0.005, 0.001, 0.081, 0.093,
0.163, 0.16, 0.159, 0.159, 0.159, 0.159, 0.159, 0.199, 0.229}}, 0.50);
System.out.println("Captured output:\n"+sw);
// Output Dati
for(Object obj : result) {
Object[] points = (Object[]) obj;
for(Object d : points) System.out.print(d + "; ");
System.out.println();
}
// Devo Ottenere in outPut questi valori:
// 0.441,0.229,0.436,0.237,0.386,0.308,0.003,0.02,0.01,0.01,0.064,-0.026,0.228,0.001,0.383,0.159,0.422,0.199,0.441,0.229
}
}
Non c'e' la correzione, ma a questo punto te la dico: quando passi l'array alla hull, fai cosi: Codice:
Object[] result = (Object[]) jsInvoke.invokeFunction("hull", new Object[][] {
{ 0.441, 0.436, 0.386, 0.389, 0.389, 0.386, 0.386, 0.386, 0.386, 0.383, 0.377, 0.377, 0.377, 0.368, 0.278, 0.26, 0.258, 0.258, 0.257,
0.231, 0.229, 0.226, 0.215, 0.122, 0.114, 0.102, 0.102, 0.093, 0.003, 0.01, 0.064, 0.146, 0.213, 0.228, 0.268, 0.28,
0.345, 0.373, 0.377, 0.378, 0.38, 0.381, 0.383, 0.422, 0.441},
{ 0.229, 0.237, 0.308, 0.273, 0.269, 0.264, 0.252, 0.251, 0.249, 0.244, 0.239, 0.207, 0.204, 0.199, 0.168, 0.154, 0.153, 0.144,
0.128, 0.119, 0.111, 0.105, 0.1, 0.088, 0.087, 0.075, 0.067, 0.049, 0.02, 0.01, -0.026, 0, 0.005, 0.001, 0.081, 0.093,
0.163, 0.16, 0.159, 0.159, 0.159, 0.159, 0.159, 0.199, 0.229}}, 0.50);
Devi fare il contrario, avere un array di n punti con due dimensioni (x,y). Nel tuo array apparentemente hai messo le X nella prima dimensione e le Y nella seconda. Ecco, cambia quell'array di oggetti. Si tratta di Java, non Javascript!!!
__________________
In God we trust; all others bring data |
|
|
|
|
|
#18 | |
|
Member
Iscritto dal: Jun 2013
Messaggi: 133
|
Quote:
Chiaro, nell'array ho X in una dimensione e Y in un altra. E così, non gli va bene!? Lui vuole primo punto[X,Y], secondo punto[X,Y], terzo punto[X,Y]... Ossia un array di 3?? [ [puntoA[x,y]], [puntoB[x,y]], [puntoC[x,y]]....] oppure [[Xa,Ya][Xb,Yb][Xc,Yc]...]?? Questo mi stai dicendo!? Ma l'avevo già fatto e mi andava in eccezione!!! Ma poi cosa cambia se io passo X,Y insieme? Lui dovrebbe leggerli come valori corretti... Ad ogni modo, io non ho proprio idea di come tu consigli di fare, ma se è giusto quello che sto pensando, quello che suggerisci, l'ho già fatto e non va! Hai fatto una prova? Ne sei sicuro?? Apprezzo il tuo interesse, ma ci sto uscendo fuori su questa cosa... Boh, che dirti, prova a vedere... Se ottieni in output i valori riportati hai risolto il mio problema... Le coordinate le hai, i risultati pure. Ma temo che non sia sufficiente. |
|
|
|
|
|
|
#19 | ||||
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Ciao
ti rispondo quotando il tuo messaggio Quote:
Quote:
Dovrei investigare di piu'. Ma magari potresti postare qualche dritta, per esempio cosa deve fare il programma. Quote:
Ho provato a mettere i punti in un array di punti, ma ottengo anch'io un'eccezione. Dice che manca la funzione "sort". E' la stessa eccezione che ottieni tu? Quote:
Alcune domande. Tieni presente che non sono esperto di javascript, lo conosco superficialmente. Ma credo che possiamo arrivare ad una soluzione. - il codice e' uguale a quello del link che hai indicato nel file javascript o hai fatto qualche modifica? - cosa deve fare? Come si usa? - Il fatto di concatenare la stringa in questo modo non ci permette di usare il messaggio di errore in uscita. Infatti java, quando si verifica l'eccezione, riporta il numero di linea corrispondente all'eval() (che non e' molto utile). Per contro, nashorn riporta il numero di linea all'interno della stringa passata in ingresso (e nemmeno questo e' utile). Quindi volevo cambiare il codice in modo che il numero di linea fosse un'informazione valida, in modo da usare tutte le informazioni possibili. Per questo motivo, proverei a tornare alla versione precedente, quella in cui caricavi lo script da un file javascript separato. In questo modo, l'errore riportato da nashorn avra' senso, si riferira' alla linea che ha fallito l'esecuzione. Quindi, provo a dare un'occhiata al codice che hai postato precedentemente, nel quale lo script era in un file .js DIMENTICAVO - nelle due versioni che hai pubblicato, la lista dei punti di ingresso e' molto diversa (nella seconda versione ci sono piu' punti). Qual e' la lista da utilizzare?
__________________
In God we trust; all others bring data Ultima modifica di sottovento : 31-10-2015 alle 21:55. |
||||
|
|
|
|
|
#20 |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Ho fatto dei test ed ho capito perche' hai due funzionamenti cosi' diversi, vale a dire che in un browser funziona ed in java nashorn no.
C'e' il trucco All'inizio del modulo incriminato, c'e' questa definizione (ho aggiunto le newline per renderla comprensibile: Codice:
!function(e)
{
if ("object"==typeof exports && "undefined"!=typeof module)
{
module.exports=e();
}
else if ("function"==typeof define&&define.amd)
define([],e);
else
{
var f;
"undefined"!=typeof window ?
f=window :
"undefined"!=typeof global ?
f=global :
"undefined"!=typeof self&&(f=self),
//console.log('A questo punto, f=' + f); // Questo per loggare nella console del browser
//print('A questo punto, f=' + f); // Questo per loggare in nashorn
f.hull=e()
}
}
Quindi Codice:
f.hull = e() Nashorn non ha quest'oggetto Nashorn non ha nemmeno l'oggetto "global" Ne consegue che f, quando lo script gira sotto nashorn, non ha mai un valore accettabile, quindi l'istruzione f.hull=e() mandera' lo script in crash. Questo e' il motivo per cui il tuo script gira correttamente in un browser e va in crash sotto nashorn!! Come risolvere? Beh, in questo caso e' semplice: basta definire una variabile globale, cancellare quelle linee ed assegnare questa e() alla variabile globale. Per esempio, all'inizio dello script potresti scrivere: Codice:
var entryPoint;
!function(e)
{
if ("object"==typeof exports && "undefined"!=typeof module)
{
console.log('(e) - checkpoint 1');
module.exports=e();
}
else if ("function"==typeof define&&define.amd)
define([],e);
else
{
entryPoint = e();
}
}
Nonostante questa modifica, otterrai ancora una eccezione perche' i parametri non sono passati nel formato corretto. Onestamente e' un po' tardi e voglio andare a dormire, quindi non ho verificato quale fosse il formato corretto, quindi se esegui da Java: Codice:
Object result = invocable.invokeFunction("entryPoint", new Object[][], 0.50);
ottieni un'eccezione. Come faccio ad essere sicuro che siamo sulla strada giusta? Semplice: per prova, ho fissato i dati in una funzione all'interno di javascript, cosi: Codice:
var entryPoint;
function testMydata()
{
print('Call the entry point');
entryPoint([[0.441,0.229], [0.436,0.237], [0.386,0.308], [0.389,0.273], [0.389,0.269], [0.386,0.264], [0.386,0.252], [0.386,0.251], [0.386,0.249], [0.383,0.244], [0.377,0.239], [0.377,0.207], [0.377,0.204], [0.368,0.199], [0.278,0.168], [0.26,0.154], [0.258,0.153], [0.258,0.144], [0.257,0.128], [0.231,0.119], [0.229,0.111], [0.226,0.105], [0.215,0.1], [0.122,0.088], [0.114,0.087], [0.102,0.075], [0.102,0.067], [0.093,0.049], [0.003,0.02], [0.01,0.01], [0.064,-0.026], [0.146,0], [0.213,0.005], [0.228,0.001], [0.268,0.081], [0.28,0.093], [0.345,0.163], [0.373,0.16], [0.377,0.159], [0.378,0.159], [0.38,0.159], [0.381,0.159], [0.383,0.159], [0.422,0.199], [0.441,0.229]], 0.50);
print('Call was successful!');
}
!function(e)
{
if ("object"==typeof exports && "undefined"!=typeof module)
{
module.exports=e();
}
else if ("function"==typeof define&&define.amd)
define([],e);
else
{
entryPoint = e();
}
}
Codice:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader("hull.js"));
Invocable invocable = (Invocable) engine;
Object result = invocable.invokeFunction("testMydata");
Riassumendo i due problemi principali 1 - nashorn esegue javascript ma non mette a disposizione dello script tutti gli oggetti che normalmente lo script ha a disposizione quando gira in un browser, vale a dire l'oggetto "window" e l'oggetto "global". Per questo motivo, andava in crash. Per ovviare, basta una variabile globale; 2 - Il passaggio dei parametri da java a javascript non e' immediato, ma occorre fare delle conversioni. Penso che basti una ricerca in google per capire come passare una matrice Java ad uno script. Ci sara' anche il problema contrario, vale a dire occorrera' tradurre in oggetto java l'output dello script. Le traduzioni non sono immediate. Il problema sembra piu' aggredibile, ora. Fammi sapere
__________________
In God we trust; all others bring data |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 04:01.




















