List of usage examples for java.util List removeAll
boolean removeAll(Collection<?> c);
From source file:de.unihannover.l3s.mws.bean.CompareSearches.java
public String refineImgSearch() { // System.out.println("TYPE: REFINE IMG "); searchterms.removeAll(Collections.singleton("")); String q = ""; for (String t : this.searchterms) { q += "\"" + t + "\" "; }//from w ww .ja v a 2 s . c o m List<String> exclude = new ArrayList<String>(siteAvailablelist3); exclude.removeAll(siteSelectedlist3); exclude.addAll(excludeImg); for (String s : exclude) q += " -site:" + s + " "; System.out.println(q); Track track = new Track(); track.setDate((new GregorianCalendar()).getTime()); track.setOperation("search"); track.setParam1(q); track.setParam2("Refine IMG"); track.setParam3("1"); track.setUtente(this.user.getUtente()); TrackDao td = new TrackDao(); td.addTrack(track); List<SearchResult> toremove = new ArrayList<SearchResult>(); searchResult3 = new ArrayList<SearchResult>(searchResultImg); for (SearchResult res : searchResult3) { for (String exc : exclude) if (res.getUrl().contains(exc)) { // System.out.println("removing "+exc); toremove.add(res); } } for (SearchResult sr : toremove) { searchResult3.remove(sr); } if (searchterms.size() == 0) searchterms.add(""); // PIE IMAGE StatsManager sm = new StatsManager(); List<YData> list = sm.getMatcthTable(sm.getSites(searchResult3, null, null)); searchDataPie3 = "var data = [ "; ArrayList<String> datastring = new ArrayList<String>(); for (YData a : list) { datastring.add("{ label: \"" + a.getSite() + "\", data: " + a.getQty() + "} "); } searchDataPie3 += Joiner.on(",").join(datastring); searchDataPie3 += " ]; "; // searchDataPie3+=" var options = { series: { pie: {show: true, label: {show: false} } }, grid: { hoverable: true, clickable: true }, legend: {show: false} }; "; searchDataPie3 += "$.plot($(\"#chartpie3\"), data, options ); \n"; String hover = " $(\"#chartpie3\").bind(\"plothover\", function(event, pos, obj){ if (!obj){return;} percent = parseFloat(obj.series.percent).toFixed(2); var html = []; html.push(\"<div style=\\\"flot:left;width:105px;height:20px;text-align:center;border:0px solid black;background-color:\", obj.series.color, \"\\\">\", \"<span style=\\\"font-weight:bold;color:red\\\">\", obj.series.label, \" (\", percent, \"%)</span>\", \"</div>\"); $(\"#showInteractive\").html(html.join('')); }); "; hover = " $(\"#chartpie3\").bind(\"plothover\", function(event, pos, obj){ if (!obj){return;} percent = parseFloat(obj.series.percent).toFixed(2); var html = []; html.push(\"<div style=\\\"flot:left;width:105px;height:20px;text-align:center;border:0px solid black; \\\">\", \"<span style=\\\"font-weight:bold;color:red\\\">\", obj.series.label, \" (\", percent, \"%)</span>\", \"</div>\"); $(\"#showInteractive\").html(html.join('')); }); "; searchDataPie3 += hover; searchDataPie3 += " var choiceContainer3 = $(\"#chartpie3\");"; searchDataPie3 += " choiceContainer3.find(\"input\").click(plotAccordingToChoices3);"; searchDataPie3 += " function plotAccordingToChoices3() { "; searchDataPie3 += " var key = $(this).attr(\"name\"); "; searchDataPie3 += " $( \"input[value*='\"+key+\"']\" ).trigger('click'); "; searchDataPie3 += " }"; searchDataPie3 += " "; return "basicSearch"; }
From source file:de.biomedical_imaging.traj.math.TrajectorySplineFit.java
/** * Calculates a spline to a trajectory. Attention: The spline is fitted through a rotated version of the trajectory. * To fit the spline the trajectory is rotated into its main direction. You can access this rotated trajectory by * {@link #getRotatedTrajectory() getRotatedTrajectory}. * @return The fitted spline/*www . ja v a 2 s.c o m*/ */ public PolynomialSplineFunction calculateSpline() { successfull = false; /* * 1.Calculate the minimum bounding rectangle */ ArrayList<Point2D.Double> points = new ArrayList<Point2D.Double>(); for (int i = 0; i < t.size(); i++) { Point2D.Double p = new Point2D.Double(); p.setLocation(t.get(i).x, t.get(i).y); points.add(p); } /* * 1.1 Rotate that the major axis is parallel with the xaxis */ Array2DRowRealMatrix gyr = RadiusGyrationTensor2D.getRadiusOfGyrationTensor(t); EigenDecomposition eigdec = new EigenDecomposition(gyr); double inRad = -1 * Math.atan2(eigdec.getEigenvector(0).getEntry(1), eigdec.getEigenvector(0).getEntry(0)); boolean doTransform = (Math.abs(Math.abs(inRad) - Math.PI) > 0.001); if (doTransform) { angleRotated = inRad; for (int i = 0; i < t.size(); i++) { double x = t.get(i).x; double y = t.get(i).y; double newX = x * Math.cos(inRad) - y * Math.sin(inRad); double newY = x * Math.sin(inRad) + y * Math.cos(inRad); rotatedTrajectory.add(newX, newY, 0); points.get(i).setLocation(newX, newY); } //for(int i = 0; i < rect.length; i++){ // rect[i].setLocation(rect[i].x*Math.cos(inRad)-rect[i].y*Math.sin(inRad), rect[i].x*Math.sin(inRad)+rect[i].y*Math.cos(inRad)); //} } else { angleRotated = 0; rotatedTrajectory = t; } /* * 2. Divide the rectangle in n equal segments * 2.1 Calculate line in main direction * 2.2 Project the points in onto this line * 2.3 Calculate the distance between the start of the line and the projected point * 2.4 Assign point to segment according to distance of (2.3) */ List<List<Point2D.Double>> pointsInSegments = null; boolean allSegmentsContainingAtLeastTwoPoints = true; int indexSmallestX = 0; double segmentWidth = 0; do { double smallestX = Double.MAX_VALUE; double largestX = Double.MIN_VALUE; for (int i = 0; i < points.size(); i++) { if (points.get(i).x < smallestX) { smallestX = points.get(i).x; indexSmallestX = i; } if (points.get(i).x > largestX) { largestX = points.get(i).x; } } allSegmentsContainingAtLeastTwoPoints = true; segmentWidth = (largestX - smallestX) / nSegments; pointsInSegments = new ArrayList<List<Point2D.Double>>(nSegments); for (int i = 0; i < nSegments; i++) { pointsInSegments.add(new ArrayList<Point2D.Double>()); } for (int i = 0; i < points.size(); i++) { int index = (int) Math.abs((points.get(i).x / segmentWidth)); if (index > (nSegments - 1)) { index = (nSegments - 1); } pointsInSegments.get(index).add(points.get(i)); } for (int i = 0; i < pointsInSegments.size(); i++) { if (pointsInSegments.get(i).size() < 2) { if (nSegments > 2) { nSegments--; i = pointsInSegments.size(); allSegmentsContainingAtLeastTwoPoints = false; } } } } while (allSegmentsContainingAtLeastTwoPoints == false); /* * 3. Calculate the mean standard deviation over each segment: <s> */ //Point2D.Double eMajorP1 = new Point2D.Double(p1.x - (p3.x-p1.x)/2.0,p1.y - (p3.y-p1.y)/2.0); // Point2D.Double eMajorP2 = new Point2D.Double(p2.x - (p3.x-p1.x)/2.0,p2.y - (p3.y-p1.y)/2.0); double sumSDOrthogonal = 0; int Nsum = 0; CenterOfGravityFeature cogf = new CenterOfGravityFeature(rotatedTrajectory); Point2D.Double cog = new Point2D.Double(cogf.evaluate()[0], cogf.evaluate()[1]); Point2D.Double eMajorP1 = cog; Point2D.Double eMajorP2 = new Point2D.Double(cog.getX() + 1, cog.getY()); for (int i = 0; i < nSegments; i++) { StandardDeviation sd = new StandardDeviation(); double[] distances = new double[pointsInSegments.get(i).size()]; for (int j = 0; j < pointsInSegments.get(i).size(); j++) { int factor = 1; if (isLeft(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j))) { factor = -1; } distances[j] = factor * distancePointLine(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j)); } if (distances.length > 0) { sd.setData(distances); sumSDOrthogonal += sd.evaluate(); Nsum++; } } double s = sumSDOrthogonal / Nsum; if (segmentWidth < Math.pow(10, -15)) { return null; } if (s < Math.pow(10, -15)) { //If standard deviation is zero, replace it with the half of the segment width s = segmentWidth / 2; } //rotatedTrajectory.showTrajectory("rot"); /* * 4. Build a kd-tree */ KDTree<Point2D.Double> kdtree = new KDTree<Point2D.Double>(2); for (int i = 0; i < points.size(); i++) { try { //To ensure that all points have a different key, add small random number kdtree.insert(new double[] { points.get(i).x, points.get(i).y }, points.get(i)); } catch (KeySizeException e) { e.printStackTrace(); } catch (KeyDuplicateException e) { //Do nothing! It is not important } } /* * 5. Using the first point f in trajectory and calculate the center of mass * of all points around f (radius: 3*<s>)) */ List<Point2D.Double> near = null; Point2D.Double first = points.get(indexSmallestX);//minDistancePointToLine(p1, p3, points); double r1 = 3 * s; try { near = kdtree.nearestEuclidean(new double[] { first.x, first.y }, r1); } catch (KeySizeException e) { e.printStackTrace(); } double cx = 0; double cy = 0; for (int i = 0; i < near.size(); i++) { cx += near.get(i).x; cy += near.get(i).y; } cx /= near.size(); cy /= near.size(); splineSupportPoints = new ArrayList<Point2D.Double>(); splineSupportPoints.add(new Point2D.Double(cx, cy)); /* * 6. The second point is determined by finding the center-of-mass of particles in the p/2 radian * section of an annulus, r1 < r < 2r1, that is directed toward the angle with the highest number * of particles within p/2 radians. * 7. This second point is then used as the center of the annulus for choosing the third point, and the process is repeated (6. & 7.). */ /* * 6.1 Find all points in the annolous */ /* * 6.2 Write each point in a coordinate system centered at the center of the sphere, calculate direction and * check if it in the allowed bounds */ int nCircleSegments = 100; double deltaRad = 2 * Math.PI / nCircleSegments; boolean stop = false; int minN = 7; double tempr1 = r1; double allowedDeltaDirection = 0.5 * Math.PI; while (stop == false) { List<Point2D.Double> nearestr1 = null; List<Point2D.Double> nearest2xr1 = null; try { nearestr1 = kdtree .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x, splineSupportPoints.get(splineSupportPoints.size() - 1).y }, tempr1); nearest2xr1 = kdtree .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x, splineSupportPoints.get(splineSupportPoints.size() - 1).y }, 2 * tempr1); } catch (KeySizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } nearest2xr1.removeAll(nearestr1); double lThreshRad = 0; double hThreshRad = Math.PI / 2; double stopThresh = 2 * Math.PI; if (splineSupportPoints.size() > 1) { double directionInRad = Math.atan2( splineSupportPoints.get(splineSupportPoints.size() - 1).y - splineSupportPoints.get(splineSupportPoints.size() - 2).y, splineSupportPoints.get(splineSupportPoints.size() - 1).x - splineSupportPoints.get(splineSupportPoints.size() - 2).x) + Math.PI; lThreshRad = directionInRad - allowedDeltaDirection / 2 - Math.PI / 4; if (lThreshRad < 0) { lThreshRad = 2 * Math.PI + lThreshRad; } if (lThreshRad > 2 * Math.PI) { lThreshRad = lThreshRad - 2 * Math.PI; } hThreshRad = directionInRad + allowedDeltaDirection / 2 + Math.PI / 4; if (hThreshRad < 0) { hThreshRad = 2 * Math.PI + hThreshRad; } if (hThreshRad > 2 * Math.PI) { hThreshRad = hThreshRad - 2 * Math.PI; } stopThresh = directionInRad + allowedDeltaDirection / 2 - Math.PI / 4; if (stopThresh > 2 * Math.PI) { stopThresh = stopThresh - 2 * Math.PI; } } double newCx = 0; double newCy = 0; int newCN = 0; int candN = 0; //Find center with highest density of points double lastDist = 0; double newDist = 0; do { lastDist = Math.min(Math.abs(lThreshRad - stopThresh), 2 * Math.PI - Math.abs(lThreshRad - stopThresh)); candN = 0; double candCx = 0; double candCy = 0; for (int i = 0; i < nearest2xr1.size(); i++) { Point2D.Double centerOfCircle = splineSupportPoints.get(splineSupportPoints.size() - 1); Vector2d relativeToCircle = new Vector2d(nearest2xr1.get(i).x - centerOfCircle.x, nearest2xr1.get(i).y - centerOfCircle.y); relativeToCircle.normalize(); double angleInRadians = Math.atan2(relativeToCircle.y, relativeToCircle.x) + Math.PI; if (lThreshRad < hThreshRad) { if (angleInRadians > lThreshRad && angleInRadians < hThreshRad) { candCx += nearest2xr1.get(i).x; candCy += nearest2xr1.get(i).y; candN++; } } else { if (angleInRadians > lThreshRad || angleInRadians < hThreshRad) { candCx += nearest2xr1.get(i).x; candCy += nearest2xr1.get(i).y; candN++; } } } if (candN > 0 && candN > newCN) { candCx /= candN; candCy /= candN; newCx = candCx; newCy = candCy; newCN = candN; } lThreshRad += deltaRad; hThreshRad += deltaRad; if (lThreshRad > 2 * Math.PI) { lThreshRad = lThreshRad - 2 * Math.PI; } if (hThreshRad > 2 * Math.PI) { hThreshRad = hThreshRad - 2 * Math.PI; } newDist = Math.min(Math.abs(lThreshRad - stopThresh), 2 * Math.PI - Math.abs(lThreshRad - stopThresh)); } while ((newDist - lastDist) > 0); //Check if the new center is valid if (splineSupportPoints.size() > 1) { double currentDirectionInRad = Math.atan2( splineSupportPoints.get(splineSupportPoints.size() - 1).y - splineSupportPoints.get(splineSupportPoints.size() - 2).y, splineSupportPoints.get(splineSupportPoints.size() - 1).x - splineSupportPoints.get(splineSupportPoints.size() - 2).x) + Math.PI; double candDirectionInRad = Math.atan2( newCy - splineSupportPoints.get(splineSupportPoints.size() - 1).y, newCx - splineSupportPoints.get(splineSupportPoints.size() - 1).x) + Math.PI; double dDir = Math.max(currentDirectionInRad, candDirectionInRad) - Math.min(currentDirectionInRad, candDirectionInRad); if (dDir > 2 * Math.PI) { dDir = 2 * Math.PI - dDir; } if (dDir > allowedDeltaDirection) { stop = true; } } boolean enoughPoints = (newCN < minN); boolean isNormalRadius = Math.abs(tempr1 - r1) < Math.pow(10, -18); boolean isExtendedRadius = Math.abs(tempr1 - 3 * r1) < Math.pow(10, -18); if (enoughPoints && isNormalRadius) { //Not enough points, extend search radius tempr1 = 3 * r1; } else if (enoughPoints && isExtendedRadius) { //Despite radius extension: Not enough points! stop = true; } else if (stop == false) { splineSupportPoints.add(new Point2D.Double(newCx, newCy)); tempr1 = r1; } } //Sort Collections.sort(splineSupportPoints, new Comparator<Point2D.Double>() { public int compare(Point2D.Double o1, Point2D.Double o2) { if (o1.x < o2.x) { return -1; } if (o1.x > o2.x) { return 1; } return 0; } }); //Add endpoints if (splineSupportPoints.size() > 1) { Vector2d start = new Vector2d(splineSupportPoints.get(0).x - splineSupportPoints.get(1).x, splineSupportPoints.get(0).y - splineSupportPoints.get(1).y); start.normalize(); start.scale(r1 * 8); splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + start.x, splineSupportPoints.get(0).y + start.y)); Vector2d end = new Vector2d( splineSupportPoints.get(splineSupportPoints.size() - 1).x - splineSupportPoints.get(splineSupportPoints.size() - 2).x, splineSupportPoints.get(splineSupportPoints.size() - 1).y - splineSupportPoints.get(splineSupportPoints.size() - 2).y); end.normalize(); end.scale(r1 * 6); splineSupportPoints .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + end.x, splineSupportPoints.get(splineSupportPoints.size() - 1).y + end.y)); } else { Vector2d majordir = new Vector2d(-1, 0); majordir.normalize(); majordir.scale(r1 * 8); splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + majordir.x, splineSupportPoints.get(0).y + majordir.y)); majordir.scale(-1); splineSupportPoints .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + majordir.x, splineSupportPoints.get(splineSupportPoints.size() - 1).y + majordir.y)); } //Interpolate spline double[] supX = new double[splineSupportPoints.size()]; double[] supY = new double[splineSupportPoints.size()]; for (int i = 0; i < splineSupportPoints.size(); i++) { supX[i] = splineSupportPoints.get(i).x; supY[i] = splineSupportPoints.get(i).y; } SplineInterpolator sIinter = new SplineInterpolator(); spline = sIinter.interpolate(supX, supY); successfull = true; return spline; }
From source file:de.unihannover.l3s.mws.bean.CompareSearches.java
public String refineVideoSearch() { // System.out.println("TYPE: REFINE Video nuovo: "); //String accountKey = "BmbX+6Sy9/VEcS5oOjurccO5MQpKr2ewvLQ2vRHBKXQ"; // TextManager tmgr=new TextManager(); searchterms.removeAll(Collections.singleton("")); String q = ""; for (String t : this.searchterms) { q += "\"" + t + "\" "; }// w w w . ja v a 2 s . c om List<String> exclude = new ArrayList<String>(siteAvailablelist2); exclude.removeAll(siteSelectedlist2); exclude.addAll(excludeVid); for (String s : exclude) q += " -site:" + s + " "; System.out.println(q); Track track = new Track(); track.setDate((new GregorianCalendar()).getTime()); track.setOperation("search"); track.setParam1(q); track.setParam2("Refine Video"); track.setParam3("1"); track.setUtente(this.user.getUtente()); TrackDao td = new TrackDao(); td.addTrack(track); List<SearchResult> toremove = new ArrayList<SearchResult>(); searchResult2 = new ArrayList<SearchResult>(searchResultVideo); for (SearchResult res : searchResult2) { for (String exc : exclude) if (res.getUrl().contains(exc)) { System.out.println("removing " + exc); toremove.add(res); } } for (SearchResult sr : toremove) { searchResult2.remove(sr); } if (searchterms.size() == 0) searchterms.add(""); // PIE VIDEO StatsManager sm = new StatsManager(); List<YData> list = sm.getMatcthTable(sm.getSites(searchResult2, null, null)); searchDataPie2 = "var data = [ "; ArrayList<String> datastring = new ArrayList<String>(); for (YData a : list) { datastring.add("{ label: \"" + a.getSite() + "\", data: " + a.getQty() + "} "); // siteAvailablelist2.add(a.getSite()); // siteSelectedlist2.add(a.getSite()); } searchDataPie2 += Joiner.on(",").join(datastring); searchDataPie2 += " ]; "; // searchDataPie2+=" var options = { series: { pie: {show: true, label: {show: false} } }, grid: { hoverable: true, clickable: true }, legend: {show: false} }; "; searchDataPie2 += "$.plot($(\"#chartpie2\"), data, options ); \n"; String hover = " $(\"#chartpie2\").bind(\"plothover\", function(event, pos, obj){ if (!obj){return;} percent = parseFloat(obj.series.percent).toFixed(2); var html = []; html.push(\"<div style=\\\"flot:left;width:105px;height:20px;text-align:center;border:0px solid black;background-color:\", obj.series.color, \"\\\">\", \"<span style=\\\"font-weight:bold;color:red\\\">\", obj.series.label, \" (\", percent, \"%)</span>\", \"</div>\"); $(\"#showInteractive\").html(html.join('')); }); "; hover = " $(\"#chartpie2\").bind(\"plothover\", function(event, pos, obj){ if (!obj){return;} percent = parseFloat(obj.series.percent).toFixed(2); var html = []; html.push(\"<div style=\\\"flot:left;width:105px;height:20px;text-align:center;border:0px solid black; \\\">\", \"<span style=\\\"font-weight:bold;color:red\\\">\", obj.series.label, \" (\", percent, \"%)</span>\", \"</div>\"); $(\"#showInteractive\").html(html.join('')); }); "; searchDataPie2 += hover; searchDataPie2 += " var choiceContainer2 = $(\"#chartpie2\");"; searchDataPie2 += " choiceContainer2.find(\"input\").click(plotAccordingToChoices2);"; searchDataPie2 += " function plotAccordingToChoices2() { "; searchDataPie2 += " var key = $(this).attr(\"name\"); "; searchDataPie2 += " $( \"input[value*='\"+key+\"']\" ).trigger('click'); "; searchDataPie2 += " }"; searchDataPie2 += " "; return "basicSearch"; }
From source file:fragment.web.ChannelControllerTest.java
@Test public void testEditChannelCurrencyGet() { try {/*from w w w.j av a 2 s . c om*/ Channel channel = channelDAO.find(4L); channelController.editChannelCurrency(channel.getId().toString(), map); List<CurrencyValue> availableCurrencies = (List<CurrencyValue>) map.get("availableCurrencies"); int size = availableCurrencies.size(); List<CurrencyValue> currencyList = channelService.listCurrencies(channel.getParam()); availableCurrencies.removeAll(currencyList); Assert.assertEquals(size, availableCurrencies.size()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } }
From source file:com.flexive.ejb.beans.workflow.WorkflowEngineBean.java
/** * {@inheritDoc}// w ww .jav a2 s . co m */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void update(Workflow workflow) throws FxApplicationException { UserTicket ticket = FxContext.getUserTicket(); // Permission checks FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement); Workflow org = CacheAdmin.getEnvironment().getWorkflow(workflow.getId()).asEditable(); List<Step> dups = new ArrayList<Step>(2); //duplicates (removed and re-added) for (Step check : workflow.getSteps()) { for (Step stp : org.getSteps()) if (check.getId() < 0 && stp.getStepDefinitionId() == check.getStepDefinitionId()) dups.add(check); } if (dups.size() > 0) { //sync steps workflow.getSteps().removeAll(dups); for (Step stp : org.getSteps()) for (Step dp : dups) if (dp.getStepDefinitionId() == stp.getStepDefinitionId()) { workflow.getSteps().add(stp); break; } //sync routes boolean changes = true; while (changes) { changes = false; for (Route r : workflow.getRoutes()) { for (Step s : dups) { if (r.getFromStepId() == s.getId()) { long _from = r.getFromStepId(); for (Step stp : org.getSteps()) if (stp.getStepDefinitionId() == s.getStepDefinitionId()) { _from = stp.getId(); break; } Route nr = new Route(r.getId(), r.getGroupId(), _from, r.getToStepId()); if (!workflow.getRoutes().contains(nr)) { workflow.getRoutes().remove(r); workflow.getRoutes().add(nr); changes = true; } break; } else if (r.getToStepId() == s.getId()) { long _to = r.getToStepId(); for (Step stp : org.getSteps()) if (stp.getStepDefinitionId() == s.getStepDefinitionId()) { _to = stp.getId(); break; } Route nr = new Route(r.getId(), r.getGroupId(), r.getFromStepId(), _to); if (!workflow.getRoutes().contains(nr)) { workflow.getRoutes().remove(r); workflow.getRoutes().add(nr); changes = true; } break; } if (changes) break; } if (changes) break; } } } Connection con = null; PreparedStatement stmt = null; String sql = "UPDATE " + TBL_WORKFLOW + " SET NAME=?, DESCRIPTION=? WHERE ID=?"; boolean success = false; try { // Sanity checks checkIfValid(workflow); // Obtain a database connection con = Database.getDbConnection(); // Update the workflow instance stmt = con.prepareStatement(sql); stmt.setString(1, workflow.getName()); stmt.setString(2, StringUtils.defaultString(workflow.getDescription())); stmt.setLong(3, workflow.getId()); stmt.executeUpdate(); FxEnvironment fxEnvironment = CacheAdmin.getEnvironment(); // Remove steps? List<Step> remove = new ArrayList<Step>(2); for (Step step : fxEnvironment.getStepsByWorkflow(workflow.getId())) { if (!workflow.getSteps().contains(step)) { // remove step remove.add(step); } } if (remove.size() > 0) { int tries = remove.size() * 2; List<Step> tmpRemove = new ArrayList<Step>(remove.size()); while (remove.size() > 0 && --tries > 0) { for (Step step : remove) { try { //remove affected routes as well for (Route route : org.getRoutes()) if (route.getFromStepId() == step.getId() || route.getToStepId() == step.getId()) routeEngine.remove(route.getId()); stepEngine.removeStep(step.getId()); tmpRemove.add(step); } catch (FxApplicationException e) { //ignore since rmeove order matters } } remove.removeAll(tmpRemove); } } // Add/update steps, if necessary Map<Long, Step> createdSteps = new HashMap<Long, Step>(); int index = 1; for (Step step : workflow.getSteps()) { if (step.getId() < 0) { long newStepId = stepEngine.createStep(step); // set position stepEngine.updateStep(newStepId, step.getAclId(), index); // map created steps using the old ID - if routes reference them createdSteps.put(step.getId(), new Step(newStepId, step)); } else { // update ACL and position stepEngine.updateStep(step.getId(), step.getAclId(), index); } index++; } // Remove routes? boolean found; for (Route route : org.getRoutes()) { found = false; for (Route check : workflow.getRoutes()) { if (check.getGroupId() == route.getGroupId() && check.getFromStepId() == route.getFromStepId() && check.getToStepId() == route.getToStepId()) { workflow.getRoutes().remove(check); //dont add this one again found = true; break; } } // remove route if not found if (!found) routeEngine.remove(route.getId()); } // add routes for (Route route : workflow.getRoutes()) { if (route.getId() < 0) { long fromStepId = resolveTemporaryStep(createdSteps, route.getFromStepId()); long toStepId = resolveTemporaryStep(createdSteps, route.getToStepId()); routeEngine.create(fromStepId, toStepId, route.getGroupId()); } } success = true; } catch (SQLException exc) { if (StorageManager.isUniqueConstraintViolation(exc)) { throw new FxEntryExistsException("ex.workflow.exists"); } else { throw new FxUpdateException(LOG, exc, "ex.workflow.update", workflow.getName(), exc.getMessage()); } } catch (Exception exc) { throw new FxUpdateException(LOG, exc, "ex.workflow.update", workflow.getName(), exc.getMessage()); } finally { Database.closeObjects(WorkflowEngineBean.class, con, stmt); if (!success) { EJBUtils.rollback(ctx); } else { StructureLoader.reloadWorkflows(FxContext.get().getDivisionId()); } } }
From source file:de.biomedical_imaging.traj.math.TrajectorySplineFitLegacy.java
/** * Calculates a spline to a trajectory. Attention: The spline is fitted through a rotated version of the trajectory. * To fit the spline the trajectory is rotated into its main direction. You can access this rotated trajectory by * {@link #getRotatedTrajectory() getRotatedTrajectory}. * @return The fitted spline/*from w ww .j a va 2s. c om*/ */ public PolynomialSplineFunction calculateSpline() { /* * 1.Calculate the minimum bounding rectangle */ ArrayList<Point2D.Double> points = new ArrayList<Point2D.Double>(); for (int i = 0; i < t.size(); i++) { Point2D.Double p = new Point2D.Double(); p.setLocation(t.get(i).x, t.get(i).y); points.add(p); } Point2D.Double[] rect = null; try { rect = RotatingCalipers.getMinimumBoundingRectangle(points); } catch (IllegalArgumentException e) { } catch (EmptyStackException e) { } /* * 1.1 Rotate that the major axis is parallel with the xaxis */ Point2D.Double majorDirection = null; Point2D.Double p1 = rect[2]; //top left Point2D.Double p2 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[1] : rect[3]; //Point to long side Point2D.Double p3 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[3] : rect[1]; //Point to short side majorDirection = new Point2D.Double(p2.x - p1.x, p2.y - p1.y); double width = p1.distance(p2); double inRad = -1 * Math.atan2(majorDirection.y, majorDirection.x); boolean doTransform = (Math.abs(Math.abs(inRad) - Math.PI) > 0.001); if (doTransform) { angleRotated = inRad; for (int i = 0; i < t.size(); i++) { double x = t.get(i).x; double y = t.get(i).y; double newX = x * Math.cos(inRad) - y * Math.sin(inRad); double newY = x * Math.sin(inRad) + y * Math.cos(inRad); rotatedTrajectory.add(newX, newY, 0); points.get(i).setLocation(newX, newY); } for (int i = 0; i < rect.length; i++) { rect[i].setLocation(rect[i].x * Math.cos(inRad) - rect[i].y * Math.sin(inRad), rect[i].x * Math.sin(inRad) + rect[i].y * Math.cos(inRad)); } p1 = rect[2]; //top left p2 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[1] : rect[3]; //Point to long side p3 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[3] : rect[1]; //Point to short side } else { angleRotated = 0; rotatedTrajectory = t; } /* * 2. Divide the rectangle in n equal segments * 2.1 Calculate line in main direction * 2.2 Project the points in onto this line * 2.3 Calculate the distance between the start of the line and the projected point * 2.4 Assign point to segment according to distance of (2.3) */ List<List<Point2D.Double>> pointsInSegments = null; boolean allSegmentsContainingAtLeastTwoPoints = true; do { allSegmentsContainingAtLeastTwoPoints = true; double segmentWidth = p1.distance(p2) / nSegments; pointsInSegments = new ArrayList<List<Point2D.Double>>(nSegments); for (int i = 0; i < nSegments; i++) { pointsInSegments.add(new ArrayList<Point2D.Double>()); } for (int i = 0; i < points.size(); i++) { Point2D.Double projPoint = projectPointToLine(p1, p2, points.get(i)); int index = (int) (p1.distance(projPoint) / segmentWidth); if (index > (nSegments - 1)) { index = (nSegments - 1); } pointsInSegments.get(index).add(points.get(i)); } for (int i = 0; i < pointsInSegments.size(); i++) { if (pointsInSegments.get(i).size() < 2) { if (nSegments > 2) { nSegments--; i = pointsInSegments.size(); allSegmentsContainingAtLeastTwoPoints = false; } } } } while (allSegmentsContainingAtLeastTwoPoints == false); /* * 3. Calculate the mean standard deviation over each segment: <s> */ Point2D.Double eMajorP1 = new Point2D.Double(p1.x - (p3.x - p1.x) / 2.0, p1.y - (p3.y - p1.y) / 2.0); Point2D.Double eMajorP2 = new Point2D.Double(p2.x - (p3.x - p1.x) / 2.0, p2.y - (p3.y - p1.y) / 2.0); double sumMean = 0; int Nsum = 0; for (int i = 0; i < nSegments; i++) { StandardDeviation sd = new StandardDeviation(); double[] distances = new double[pointsInSegments.get(i).size()]; for (int j = 0; j < pointsInSegments.get(i).size(); j++) { int factor = 1; if (isLeft(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j))) { factor = -1; } distances[j] = factor * distancePointLine(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j)); } if (distances.length > 0) { sd.setData(distances); sumMean += sd.evaluate(); Nsum++; } } double s = sumMean / Nsum; if (s < 0.000000000001) { s = width / nSegments; } /* * 4. Build a kd-tree */ KDTree<Point2D.Double> kdtree = new KDTree<Point2D.Double>(2); for (int i = 0; i < points.size(); i++) { try { //To ensure that all points have a different key, add small random number kdtree.insert(new double[] { points.get(i).x, points.get(i).y }, points.get(i)); } catch (KeySizeException e) { e.printStackTrace(); } catch (KeyDuplicateException e) { //Do nothing! It is not important } } /* * 5. Using the first point f in trajectory and calculate the center of mass * of all points around f (radius: 3*<s>)) */ List<Point2D.Double> near = null; Point2D.Double first = minDistancePointToLine(p1, p3, points); double r1 = 3 * s; try { near = kdtree.nearestEuclidean(new double[] { first.x, first.y }, r1); } catch (KeySizeException e) { e.printStackTrace(); } double cx = 0; double cy = 0; for (int i = 0; i < near.size(); i++) { cx += near.get(i).x; cy += near.get(i).y; } cx /= near.size(); cy /= near.size(); splineSupportPoints = new ArrayList<Point2D.Double>(); splineSupportPoints.add(new Point2D.Double(cx, cy)); /* * 6. The second point is determined by finding the center-of-mass of particles in the p/2 radian * section of an annulus, r1 < r < 2r1, that is directed toward the angle with the highest number * of particles within p/2 radians. * 7. This second point is then used as the center of the annulus for choosing the third point, and the process is repeated (6. & 7.). */ /* * 6.1 Find all points in the annolous */ /* * 6.2 Write each point in a coordinate system centered at the center of the sphere, calculate direction and * check if it in the allowed bounds */ int nCircleSegments = 100; double deltaRad = 2 * Math.PI / nCircleSegments; boolean stop = false; int minN = 7; double tempr1 = r1; double allowedDeltaDirection = 0.5 * Math.PI; while (stop == false) { List<Point2D.Double> nearestr1 = null; List<Point2D.Double> nearest2xr1 = null; try { nearestr1 = kdtree .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x, splineSupportPoints.get(splineSupportPoints.size() - 1).y }, tempr1); nearest2xr1 = kdtree .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x, splineSupportPoints.get(splineSupportPoints.size() - 1).y }, 2 * tempr1); } catch (KeySizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } nearest2xr1.removeAll(nearestr1); double lThreshRad = 0; double hThreshRad = Math.PI / 2; double stopThresh = 2 * Math.PI; if (splineSupportPoints.size() > 1) { double directionInRad = Math.atan2( splineSupportPoints.get(splineSupportPoints.size() - 1).y - splineSupportPoints.get(splineSupportPoints.size() - 2).y, splineSupportPoints.get(splineSupportPoints.size() - 1).x - splineSupportPoints.get(splineSupportPoints.size() - 2).x) + Math.PI; lThreshRad = directionInRad - allowedDeltaDirection / 2 - Math.PI / 4; if (lThreshRad < 0) { lThreshRad = 2 * Math.PI + lThreshRad; } if (lThreshRad > 2 * Math.PI) { lThreshRad = lThreshRad - 2 * Math.PI; } hThreshRad = directionInRad + allowedDeltaDirection / 2 + Math.PI / 4; if (hThreshRad < 0) { hThreshRad = 2 * Math.PI + hThreshRad; } if (hThreshRad > 2 * Math.PI) { hThreshRad = hThreshRad - 2 * Math.PI; } stopThresh = directionInRad + allowedDeltaDirection / 2 - Math.PI / 4; if (stopThresh > 2 * Math.PI) { stopThresh = stopThresh - 2 * Math.PI; } } double newCx = 0; double newCy = 0; int newCN = 0; int candN = 0; //Find center with highest density of points double lastDist = 0; double newDist = 0; do { lastDist = Math.min(Math.abs(lThreshRad - stopThresh), 2 * Math.PI - Math.abs(lThreshRad - stopThresh)); candN = 0; double candCx = 0; double candCy = 0; for (int i = 0; i < nearest2xr1.size(); i++) { Point2D.Double centerOfCircle = splineSupportPoints.get(splineSupportPoints.size() - 1); Vector2d relativeToCircle = new Vector2d(nearest2xr1.get(i).x - centerOfCircle.x, nearest2xr1.get(i).y - centerOfCircle.y); relativeToCircle.normalize(); double angleInRadians = Math.atan2(relativeToCircle.y, relativeToCircle.x) + Math.PI; if (lThreshRad < hThreshRad) { if (angleInRadians > lThreshRad && angleInRadians < hThreshRad) { candCx += nearest2xr1.get(i).x; candCy += nearest2xr1.get(i).y; candN++; } } else { if (angleInRadians > lThreshRad || angleInRadians < hThreshRad) { candCx += nearest2xr1.get(i).x; candCy += nearest2xr1.get(i).y; candN++; } } } if (candN > 0 && candN > newCN) { candCx /= candN; candCy /= candN; newCx = candCx; newCy = candCy; newCN = candN; } lThreshRad += deltaRad; hThreshRad += deltaRad; if (lThreshRad > 2 * Math.PI) { lThreshRad = lThreshRad - 2 * Math.PI; } if (hThreshRad > 2 * Math.PI) { hThreshRad = hThreshRad - 2 * Math.PI; } newDist = Math.min(Math.abs(lThreshRad - stopThresh), 2 * Math.PI - Math.abs(lThreshRad - stopThresh)); } while ((newDist - lastDist) > 0); //Check if the new center is valid if (splineSupportPoints.size() > 1) { double currentDirectionInRad = Math.atan2( splineSupportPoints.get(splineSupportPoints.size() - 1).y - splineSupportPoints.get(splineSupportPoints.size() - 2).y, splineSupportPoints.get(splineSupportPoints.size() - 1).x - splineSupportPoints.get(splineSupportPoints.size() - 2).x) + Math.PI; double candDirectionInRad = Math.atan2( newCy - splineSupportPoints.get(splineSupportPoints.size() - 1).y, newCx - splineSupportPoints.get(splineSupportPoints.size() - 1).x) + Math.PI; double dDir = Math.max(currentDirectionInRad, candDirectionInRad) - Math.min(currentDirectionInRad, candDirectionInRad); if (dDir > 2 * Math.PI) { dDir = 2 * Math.PI - dDir; } if (dDir > allowedDeltaDirection) { stop = true; } } boolean enoughPoints = (newCN < minN); boolean isNormalRadius = Math.abs(tempr1 - r1) < Math.pow(10, -18); boolean isExtendedRadius = Math.abs(tempr1 - 3 * r1) < Math.pow(10, -18); if (enoughPoints && isNormalRadius) { //Not enough points, extend search radius tempr1 = 3 * r1; } else if (enoughPoints && isExtendedRadius) { //Despite radius extension: Not enough points! stop = true; } else if (stop == false) { splineSupportPoints.add(new Point2D.Double(newCx, newCy)); tempr1 = r1; } } //Sort Collections.sort(splineSupportPoints, new Comparator<Point2D.Double>() { public int compare(Point2D.Double o1, Point2D.Double o2) { if (o1.x < o2.x) { return -1; } if (o1.x > o2.x) { return 1; } return 0; } }); //Add endpoints if (splineSupportPoints.size() > 1) { Vector2d start = new Vector2d(splineSupportPoints.get(0).x - splineSupportPoints.get(1).x, splineSupportPoints.get(0).y - splineSupportPoints.get(1).y); start.normalize(); start.scale(r1 * 8); splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + start.x, splineSupportPoints.get(0).y + start.y)); Vector2d end = new Vector2d( splineSupportPoints.get(splineSupportPoints.size() - 1).x - splineSupportPoints.get(splineSupportPoints.size() - 2).x, splineSupportPoints.get(splineSupportPoints.size() - 1).y - splineSupportPoints.get(splineSupportPoints.size() - 2).y); end.normalize(); end.scale(r1 * 6); splineSupportPoints .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + end.x, splineSupportPoints.get(splineSupportPoints.size() - 1).y + end.y)); } else { Vector2d majordir = new Vector2d(-1, 0); majordir.normalize(); majordir.scale(r1 * 8); splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + majordir.x, splineSupportPoints.get(0).y + majordir.y)); majordir.scale(-1); splineSupportPoints .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + majordir.x, splineSupportPoints.get(splineSupportPoints.size() - 1).y + majordir.y)); } //Interpolate spline double[] supX = new double[splineSupportPoints.size()]; double[] supY = new double[splineSupportPoints.size()]; for (int i = 0; i < splineSupportPoints.size(); i++) { supX[i] = splineSupportPoints.get(i).x; supY[i] = splineSupportPoints.get(i).y; } SplineInterpolator sIinter = new SplineInterpolator(); spline = sIinter.interpolate(supX, supY); return spline; }
From source file:com.inkubator.hrm.web.flow.JobJabatanFormController.java
public void initJabatanProcessFlow(RequestContext context) { try {/* ww w. j a v a2s. c om*/ //binding value to model Long id = context.getFlowScope().getLong("id"); jobJabatanModel = new JobJabatanModel(); if (id != null) { Jabatan jabatan = jabatanService.getByIdWithKlasifikasiKerja(id); jobJabatanModel = getJabatanModelFromEntity(jabatan); List<EducationLevel> listSourceEducationLevel = educationLevelService.getAllData(); List<JabatanEdukasi> listTargetJabatanEdukasi = jabatanEdukasiService .getAllDataByJabatanId(jabatan.getId()); List<EducationLevel> listTargetEducationLevel = Lambda.extract(listTargetJabatanEdukasi, Lambda.on(JabatanEdukasi.class).getEducationLevel()); listSourceEducationLevel.removeAll(listTargetEducationLevel); dualListModelEducationLevel = new DualListModel<EducationLevel>(listSourceEducationLevel, listTargetEducationLevel); List<OccupationType> listSourceOccupationType = occupationTypeService.getAllData(); List<JabatanProfesi> listTargetJabatanProfesi = jabatanProfesiService .getAllDataByJabatanId(jabatan.getId()); List<OccupationType> listTargetOccupationType = Lambda.extract(listTargetJabatanProfesi, Lambda.on(JabatanProfesi.class).getOccupationType()); listSourceOccupationType.removeAll(listTargetOccupationType); dualListModelOccupationType = new DualListModel<OccupationType>(listSourceOccupationType, listTargetOccupationType); List<Major> listSourceMajor = majorService.getAllData(); List<JabatanMajor> listTargetJabatanMajor = jabatanMajorService .getAllDataByJabatanId(jabatan.getId()); List<Major> listTargetMajor = Lambda.extract(listTargetJabatanMajor, Lambda.on(JabatanMajor.class).getMajor()); listSourceMajor.removeAll(listTargetMajor); dualListModelMajor = new DualListModel<Major>(listSourceMajor, listTargetMajor); List<Faculty> listSourceFaculty = facultyService.getAllData(); List<JabatanFakulty> listTargetJabatanFakulty = jabatanFacultyService .getAllDataByJabatanId(jabatan.getId()); List<Faculty> listTargetFaculty = Lambda.extract(listTargetJabatanFakulty, Lambda.on(JabatanFakulty.class).getFaculty()); listSourceFaculty.removeAll(listTargetFaculty); dualListModelFaculty = new DualListModel<Faculty>(listSourceFaculty, listTargetFaculty); List<KlasifikasiKerja> listSourceKlasifikasiKerja = klasifikasiKerjaService.getAllData(); List<KlasifikasiKerjaJabatan> listTargetKlasifikasiKerjaJabatan = klasifikasiKerjaJabatanService .getAllDataByJabatanId(jobJabatanModel.getId()); List<KlasifikasiKerja> listTargetKlasifikasiKerja = Lambda.extract( listTargetKlasifikasiKerjaJabatan, Lambda.on(KlasifikasiKerjaJabatan.class).getKlasifikasiKerja()); listSourceKlasifikasiKerja.removeAll(listTargetKlasifikasiKerja); dualListModelKlasifikasiKerja = new DualListModel<KlasifikasiKerja>(listSourceKlasifikasiKerja, listTargetKlasifikasiKerja); List<JabatanDeskripsi> listJabatanDeskripsi = jabatanDeskripsiService .getAllDataByJabatanId(jobJabatanModel.getId()); jobJabatanModel.setListJabatanDeskripsi(listJabatanDeskripsi); List<JabatanSpesifikasi> listJabatanSpesifikasi = jabatanSpesifikasiService .getAllDataByJabatanId(jobJabatanModel.getId()); jobJabatanModel.setListJabatanSpesifikasi(listJabatanSpesifikasi); List<OrgTypeOfSpecJabatan> listOrgTypeOfSpecJabatan = orgTypeOfSpecJabatanService .getAllDataByJabatanId(jobJabatanModel.getId()); jobJabatanModel.setListOrgTypeOfSpecJabatan(listOrgTypeOfSpecJabatan); isEdit = Boolean.TRUE; } else { jobJabatanModel = new JobJabatanModel(); isEdit = Boolean.FALSE; List<KlasifikasiKerja> source = klasifikasiKerjaService.getAllData(); dualListModelKlasifikasiKerja.setSource(source); dualListModelKlasifikasiKerja.setTarget(new ArrayList<>()); List<EducationLevel> listSourceEducationLevel = educationLevelService.getAllData(); dualListModelEducationLevel.setSource(listSourceEducationLevel); dualListModelEducationLevel.setTarget(new ArrayList<>()); List<OccupationType> listSourceOccupationType = occupationTypeService.getAllData(); dualListModelOccupationType.setSource(listSourceOccupationType); dualListModelOccupationType.setTarget(new ArrayList<>()); List<Major> listSourceMajor = majorService.getAllData(); dualListModelMajor.setSource(listSourceMajor); dualListModelMajor.setTarget(new ArrayList<>()); List<Faculty> listSourceFaculty = facultyService.getAllData(); dualListModelFaculty.setSource(listSourceFaculty); dualListModelFaculty.setTarget(new ArrayList<>()); List<KlasifikasiKerja> listSourceKlasifikasiKerja = klasifikasiKerjaService.getAllData(); dualListModelKlasifikasiKerja.setSource(listSourceKlasifikasiKerja); dualListModelKlasifikasiKerja.setTarget(new ArrayList<>()); jobJabatanModel.setListJabatanDeskripsi(new ArrayList<JabatanDeskripsi>()); jobJabatanModel.setListJabatanSpesifikasi(new ArrayList<JabatanSpesifikasi>()); } JabatanDeskripsiModel jabatanDeskripsiModel = new JabatanDeskripsiModel(); context.getFlowScope().put("jabatanDeskripsiModel", jabatanDeskripsiModel); JabatanSpesifikasiModel jabatanSpesifikasiModel = new JabatanSpesifikasiModel(); context.getFlowScope().put("jabatanSpesifikasiModel", jabatanSpesifikasiModel); OrgTypeOfSpecJabatanModel orgTypeOfSpecJabatanModel = new OrgTypeOfSpecJabatanModel(); context.getFlowScope().put("orgTypeOfSpecJabatanModel", orgTypeOfSpecJabatanModel); context.getFlowScope().put("jobJabatanModel", jobJabatanModel); //Inisialisasi List Departemen, list hanya dari company yang sama dengan user yang sedang login, dan statusnya aktif List<Department> listDepartemens = departmentService.getAllWithSpecificCompany(); for (Department department : listDepartemens) { departments.put(department.getDepartmentName(), department.getId()); } MapUtil.sortByValue(departments); context.getFlowScope().put("departments", departments); //Inisialisasi List GolonganJabatan List<GolonganJabatan> listGolonganJabatans = golonganJabatanService.getAllWithDetail(); for (GolonganJabatan golonganJabatan : listGolonganJabatans) { golJabatans.put(golonganJabatan.getCode() + " - " + golonganJabatan.getPangkat().getPangkatName(), golonganJabatan.getId()); } MapUtil.sortByValue(golJabatans); context.getFlowScope().put("golJabatans", golJabatans); //Inisialisasi CostCenter List<CostCenter> listCostCenters = costCenterService.getAllData(); for (CostCenter costCenter : listCostCenters) { posBiayas.put(costCenter.getName(), costCenter.getId()); } MapUtil.sortByValue(posBiayas); context.getFlowScope().put("posBiayas", posBiayas); //Inisialisasi UnitKerja List<UnitKerja> listUnitKerjas = unitKerjaService.getAllData(); for (UnitKerja unitKerja : listUnitKerjas) { untiKerjas.put(unitKerja.getName(), unitKerja.getId()); } MapUtil.sortByValue(untiKerjas); context.getFlowScope().put("untiKerjas", untiKerjas); //Inisialisasi Jabatan (atasan) List<Jabatan> listJabatans = jabatanService.getAllData(); for (Jabatan jabatan : listJabatans) { jabatanAtasans.put(jabatan.getCode() + " | " + jabatan.getName(), jabatan.getId()); } MapUtil.sortByValue(jabatanAtasans); context.getFlowScope().put("jabatanAtasans", jabatanAtasans); //Inisialisasi SpesificationAbility List<SpecificationAbility> listSpecificationAbilities = specificationAbilityService.getAllData(); for (SpecificationAbility specificationAbility : listSpecificationAbilities) { specAbilities.put(specificationAbility.getName(), specificationAbility.getId()); } MapUtil.sortByValue(specAbilities); context.getFlowScope().put("specAbilities", specAbilities); //Inisialisasi OrgTypeOfSpec List<OrgTypeOfSpec> listOrgTypeOfSpecs = orgTypeOfSpecService.getAllData(); for (OrgTypeOfSpec orgTypeOfSpec : listOrgTypeOfSpecs) { orgTypeofSpecs.put(orgTypeOfSpec.getName(), orgTypeOfSpec.getId()); } MapUtil.sortByValue(orgTypeofSpecs); context.getFlowScope().put("orgTypeofSpecs", orgTypeofSpecs); context.getFlowScope().put("optionAbilities", optionAbilities); } catch (Exception e) { } }
From source file:de.tudarmstadt.ukp.clarin.webanno.monitoring.page.MonitoringPage.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void updateAgreementTable(AjaxRequestTarget aTarget) { Project project = projectSelectionForm.getModelObject().project; List<User> users = repository.listProjectUsersWithPermissions(project, PermissionLevel.USER); if (features.getModelObject() != null) { TypeAdapter adapter = TypeUtil.getAdapter(annotationService, features.getModelObject().getLayer()); // assume all users finished only one document double[][] multipleDocumentsFinished = new double[users.size()][users.size()]; for (int m = 0; m < users.size(); m++) { for (int j = 0; j < users.size(); j++) { multipleDocumentsFinished[m][j] = 1.0; }/*from w ww .jav a2 s. c o m*/ } List<SourceDocument> sourceDocuments = repository.listSourceDocuments(project); List<SourceDocument> trainingDoc = new ArrayList<SourceDocument>(); for (SourceDocument sdc : sourceDocuments) { if (sdc.isTrainingDocument()) { trainingDoc.add(sdc); } } sourceDocuments.removeAll(trainingDoc); // a map that contains list of finished annotation documents for a given user Map<User, List<SourceDocument>> finishedDocumentLists = new HashMap<User, List<SourceDocument>>(); for (User user : users) { List<SourceDocument> finishedDocuments = new ArrayList<SourceDocument>(); for (SourceDocument document : sourceDocuments) { AnnotationDocument annotationDocument = repository.getAnnotationDocument(document, user); if (annotationDocument.getState().equals(AnnotationDocumentState.FINISHED)) { finishedDocuments.add(document); } } finishedDocumentLists.put(user, finishedDocuments); } if (documentJCases == null) { documentJCases = getJCases(users, sourceDocuments); } // Users with some annotations of this type // Convert to structure required by CasDiff - FIXME should be removed Map<String, List<JCas>> casMap = new LinkedHashMap<>(); for (Entry<SourceDocument, Map<User, JCas>> e1 : documentJCases.entrySet()) { for (User user : users) { List<JCas> casList = casMap.get(user.getUsername()); if (casList == null) { casList = new ArrayList<>(); casMap.put(user.getUsername(), casList); } // The next line can enter null values into the list if a user didn't work // on a CAS yet. casList.add(e1.getValue().get(user)); } } List<DiffAdapter> adapters = new ArrayList<>(); for (AnnotationLayer layer : annotationService.listAnnotationLayer(project)) { Set<String> labelFeatures = new LinkedHashSet<>(); for (AnnotationFeature f : annotationService.listAnnotationFeature(layer)) { if (!f.isEnabled()) { continue; } // FIXME Ignoring link features if (!LinkMode.NONE.equals(f.getLinkMode())) { continue; } } switch (layer.getType()) { case SPAN_TYPE: { SpanDiffAdapter adpt = new SpanDiffAdapter(layer.getName(), labelFeatures); adapters.add(adpt); break; } case RELATION_TYPE: { ArcAdapter typeAdpt = (ArcAdapter) TypeUtil.getAdapter(annotationService, layer); ArcDiffAdapter adpt = new ArcDiffAdapter(layer.getName(), typeAdpt.getSourceFeatureName(), typeAdpt.getTargetFeatureName(), labelFeatures); adapters.add(adpt); break; } case CHAIN_TYPE: // FIXME Currently, these are ignored. break; } } DiffResult diff = CasDiff2.doDiff(asList(features.getModelObject().getLayer().getName()), adapters, casMap); AgreementResult[][] agreements = AgreementUtils.getPairwiseCohenKappaAgreement(diff, features.getModelObject().getLayer().getName(), features.getModelObject().getName(), casMap); List<String> usersListAsColumnHeader = new ArrayList<>(); usersListAsColumnHeader.add("users"); usersListAsColumnHeader.addAll(casMap.keySet()); List<List<String>> agreementResults = new ArrayList<>(); int i = 0; for (String username : casMap.keySet()) { List<String> agreementResult = new ArrayList<>(); agreementResult.add(username); for (int j = 0; j < casMap.size(); j++) { if (j == i) { agreementResult.add("-"); } else if (j < i) { agreementResult.add(String.format("%d/%d", agreements[i][j].getCompleteSetCount(), agreements[i][j].getTotalSetCount())); } else { if (agreements[i][j].getStudy().getItemCount() == 0) { agreementResult.add("no data"); } else { agreementResult.add(String.format("%.2f", agreements[i][j].getAgreement())); } } } i++; agreementResults.add(agreementResult); } TableDataProvider provider = new TableDataProvider(usersListAsColumnHeader, agreementResults); List<IColumn<?, ?>> columns = new ArrayList<IColumn<?, ?>>(); for (int m = 0; m < provider.getColumnCount(); m++) { columns.add(new DynamicColumnMetaData(provider, m)); } agreementTable.remove(); agreementTable = new DefaultDataTable("agreementTable", columns, provider, 10); agreementForm.add(agreementTable); aTarget.add(agreementForm); } }
From source file:de.hska.ld.recommendation.controller.RecommendationController.java
@Secured(Core.ROLE_USER) @RequestMapping(method = RequestMethod.GET, value = "/{documentId}") @Transactional(readOnly = false, noRollbackFor = NoSuchElementException.class) public ResponseEntity<LDRecommendationDto> getRecommendations(@PathVariable Long documentId) throws IOException { Document document = documentService.findById(documentId); if (document.getTagList().size() == 0) { return new ResponseEntity<LDRecommendationDto>(HttpStatus.INTERNAL_SERVER_ERROR); }/*from ww w. j a v a 2 s. c om*/ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); OIDCAuthenticationToken token = (OIDCAuthenticationToken) auth; SSSRecommResponseDto sssRecommResponseDto = sssClient.retrieveRecommendations(documentId, token.getAccessTokenValue()); if (sssRecommResponseDto == null) { return new ResponseEntity<LDRecommendationDto>(HttpStatus.INTERNAL_SERVER_ERROR); } List<SSSUserRecommendationDto> sssUserRecommendationDtoList = sssRecommResponseDto.getUsers(); List<LDRecommendationUserDto> userIdList = new ArrayList<>(); List<LDRecommendationDocumentDto> documentIdList = new ArrayList<>(); sssUserRecommendationDtoList.forEach(ur -> { String userUri = ur.getUser().getId(); // 1. Determine if the result is a user or a document if (userUri != null && userUri.contains("/user/")) { // 1.1 it is a user instance String[] splittedUserId = userUri.split("/user/"); String userId = splittedUserId[splittedUserId.length - 1]; Double likelihood = ur.getLikelihood(); try { LDRecommendationUserDto ldRecommendationUserDto = new LDRecommendationUserDto(); ldRecommendationUserDto.setUserId(Long.parseLong(userId)); ldRecommendationUserDto.setLikelihood(likelihood); userIdList.add(ldRecommendationUserDto); } catch (Exception e) { // } } else if (userUri != null && userUri.contains("/document/")) { // 1.2 it is a document instance String[] splittedDocumentId = userUri.split("/document/"); String documentIdRecommended = splittedDocumentId[splittedDocumentId.length - 1]; Double likelihood = ur.getLikelihood(); try { LDRecommendationDocumentDto ldRecommendationDocumentDto = new LDRecommendationDocumentDto(); ldRecommendationDocumentDto.setDocumentId(Long.parseLong(documentIdRecommended)); ldRecommendationDocumentDto.setLikelihood(likelihood); documentIdList.add(ldRecommendationDocumentDto); } catch (Exception e) { // } } }); // fetch the related data sets from the living documents db List<LDRecommendationUserDto> userList = documentRecommInfoService .fetchUserRecommendationDatasets(userIdList); List<LDRecommendationDocumentDto> documentList = documentRecommInfoService .fetchDocumentRecommendationDatasets(documentIdList); try { Collections.sort(userList); Collections.sort(documentList); } catch (Exception e) { e.printStackTrace(); } Long currenUserId = Core.currentUser().getId(); User initialLoadUser = userService.findByUsername("aur0rp3"); // filter out current user LDRecommendationUserDto found1 = null; LDRecommendationUserDto foundInit = null; List<LDRecommendationUserDto> likelihood0Users = new ArrayList<LDRecommendationUserDto>(); for (LDRecommendationUserDto userRecomm : userList) { /*if (0d == userRecomm.getLikelihood()) { likelihood0Users.add(userRecomm); }*/ if (currenUserId.equals(userRecomm.getUserId())) { found1 = userRecomm; } if (initialLoadUser != null && initialLoadUser.getId().equals(userRecomm.getUserId())) { foundInit = userRecomm; } } if (found1 != null) { userList.remove(found1); } if (foundInit != null) { userIdList.remove(foundInit); } if (likelihood0Users.size() > 0) { userList.removeAll(likelihood0Users); } // filter out current document LDRecommendationDocumentDto found = null; List<LDRecommendationDocumentDto> likelihood0Documents = new ArrayList<LDRecommendationDocumentDto>(); for (LDRecommendationDocumentDto documentRecomm : documentList) { if (0d == documentRecomm.getLikelihood()) { likelihood0Documents.add(documentRecomm); } if (documentId.equals(documentRecomm.getDocumentId())) { found = documentRecomm; } } if (found != null) { documentList.remove(found); } if (likelihood0Documents.size() > 0) { documentList.removeAll(likelihood0Documents); } // filter out documents the current user has no access to List<LDRecommendationDocumentDto> noPermissionDocuments = new ArrayList<LDRecommendationDocumentDto>(); for (LDRecommendationDocumentDto documentRecomm : documentList) { Long documentIdPermissionCheck = documentRecomm.getDocumentId(); Document document2 = documentService.findById(documentIdPermissionCheck); if (!documentService.checkPermissionSave(document2, Access.Permission.READ)) { noPermissionDocuments.add(documentRecomm); } } if (noPermissionDocuments.size() > 0) { documentList.removeAll(noPermissionDocuments); } LDRecommendationDto ldRecommendationDto = new LDRecommendationDto(); ldRecommendationDto.setUserList(new ArrayList<>()); ldRecommendationDto.setDocumentList(documentList); ldRecommendationDto.setDocumentId(documentId); return new ResponseEntity<LDRecommendationDto>(ldRecommendationDto, HttpStatus.OK); }
From source file:com.inkubator.hrm.web.flow.JobJabatanFormController.java
public void doResetJobJabatanMajorForm(RequestContext context) { JobJabatanModel jobJabatanModel = (JobJabatanModel) context.getFlowScope().get("jobJabatanModel"); try {//from w w w .java2s . c om if (jobJabatanModel.getId() == null) { List<Major> listSourceMajor = majorService.getAllData(); dualListModelMajor.setSource(listSourceMajor); dualListModelMajor.setTarget(new ArrayList<Major>()); } else { List<Major> listSourceMajor = majorService.getAllData(); List<JabatanMajor> listTargetJabatanMajor = jabatanMajorService .getAllDataByJabatanId(jobJabatanModel.getId()); List<Major> listTargetMajor = Lambda.extract(listTargetJabatanMajor, Lambda.on(JabatanMajor.class).getMajor()); listSourceMajor.removeAll(listTargetMajor); dualListModelMajor = new DualListModel<Major>(listSourceMajor, listTargetMajor); } } catch (Exception e) { e.printStackTrace(); } jobJabatanModel.setListMajor(new ArrayList<Major>()); context.getFlowScope().put("jobJabatanModel", jobJabatanModel); }