List of usage examples for java.util TreeMap firstKey
public K firstKey()
From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java
@Override public void applyGroupCharge(Map<Integer, String> idsAndValues, Short chargeId, boolean isPenaltyType) { MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserContext userContext = toUserContext(user); TreeMap<Integer, String> idsAndValueAsTreeMap = new TreeMap<Integer, String>(idsAndValues); try {/*from w w w.j a va 2s . c o m*/ AccountBO parentAccount = ((LoanBO) legacyAccountDao.getAccount( new AccountBusinessService().getAccount(idsAndValueAsTreeMap.firstKey()).getAccountId())) .getParentAccount(); BigDecimal parentAmount = ((LoanBO) parentAccount).getLoanAmount().getAmount(); BigDecimal membersAmount = BigDecimal.ZERO; for (Map.Entry<Integer, String> entry : idsAndValues.entrySet()) { LoanBO individual = loanDao.findById(entry.getKey()); Double chargeAmount = Double.valueOf(entry.getValue()); if (chargeAmount.equals(0.0)) { continue; } membersAmount = membersAmount.add(individual.getLoanAmount().getAmount()); individual.updateDetails(userContext); if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); individual.addAccountPenalty(new AccountPenaltiesEntity(individual, penalty, chargeAmount)); } else { individual.applyCharge(chargeId, chargeAmount); } } boolean isRateCharge = false; if (!chargeId.equals(Short.valueOf(AccountConstants.MISC_FEES)) && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) { if (isPenaltyType) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); if (penalty instanceof RatePenaltyBO) { isRateCharge = true; } } else { FeeBO fee = feeDao.findById(chargeId); if (fee.getFeeType().equals(RateAmountFlag.RATE)) { isRateCharge = true; } } } Double chargeAmount = null; if (!isRateCharge) { chargeAmount = sumCharge(idsAndValues); } else { chargeAmount = Double.valueOf(idsAndValueAsTreeMap.firstEntry().getValue()); BigDecimal chargeAmountBig = new BigDecimal(chargeAmount); membersAmount = membersAmount.multiply(chargeAmountBig); int scale = Money.getInternalPrecision(); chargeAmountBig = membersAmount.divide(parentAmount, scale, RoundingMode.HALF_EVEN); chargeAmount = chargeAmountBig.doubleValue(); } parentAccount.updateDetails(userContext); CustomerLevel customerLevel = null; if (parentAccount.isCustomerAccount()) { customerLevel = parentAccount.getCustomer().getLevel(); } if (parentAccount.getPersonnel() != null) { checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), parentAccount.getPersonnel().getPersonnelId()); } else { checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), userContext.getId()); } this.transactionHelper.startTransaction(); if (isPenaltyType && parentAccount instanceof LoanBO) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); ((LoanBO) parentAccount) .addAccountPenalty(new AccountPenaltiesEntity(parentAccount, penalty, chargeAmount)); } else { parentAccount.applyCharge(chargeId, chargeAmount); } this.transactionHelper.commitTransaction(); } catch (ServiceException e) { this.transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } catch (ApplicationException e) { this.transactionHelper.rollbackTransaction(); throw new BusinessRuleException(e.getKey(), e); } }
From source file:edu.mit.mobile.android.appupdater.AppUpdateChecker.java
@SuppressWarnings("unchecked") private void triggerFromJson(JSONObject jo) throws JSONException { final ArrayList<String> changelog = new ArrayList<String>(); // keep a sorted map of versionCode to the version information objects. // Most recent is at the top. final TreeMap<Integer, JSONObject> versionMap = new TreeMap<Integer, JSONObject>(new Comparator<Integer>() { public int compare(Integer object1, Integer object2) { return object2.compareTo(object1); };/*from w ww. j a v a 2s. co m*/ }); for (final Iterator<String> i = jo.keys(); i.hasNext();) { final String versionName = i.next(); if (versionName.equals("package")) { pkgInfo = jo.getJSONObject(versionName); continue; } final JSONObject versionInfo = jo.getJSONObject(versionName); versionInfo.put("versionName", versionName); final int versionCode = versionInfo.getInt("versionCode"); versionMap.put(versionCode, versionInfo); } final int latestVersionNumber = versionMap.firstKey(); final String latestVersionName = versionMap.get(latestVersionNumber).getString("versionName"); final Uri downloadUri = Uri.parse(pkgInfo.getString("downloadUrl")); if (currentAppVersion > latestVersionNumber) { Log.d(TAG, "We're newer than the latest published version (" + latestVersionName + "). Living in the future..."); mUpdateListener.appUpdateStatus(true, latestVersionName, null, downloadUri); return; } if (currentAppVersion == latestVersionNumber) { Log.d(TAG, "We're at the latest version (" + currentAppVersion + ")"); mUpdateListener.appUpdateStatus(true, latestVersionName, null, downloadUri); return; } // construct the changelog. Newest entries are at the top. for (final Entry<Integer, JSONObject> version : versionMap.headMap(currentAppVersion).entrySet()) { final JSONObject versionInfo = version.getValue(); final JSONArray versionChangelog = versionInfo.optJSONArray("changelog"); if (versionChangelog != null) { final int len = versionChangelog.length(); for (int i = 0; i < len; i++) { changelog.add(versionChangelog.getString(i)); } } } mUpdateListener.appUpdateStatus(false, latestVersionName, changelog, downloadUri); }
From source file:org.apache.hadoop.raid.CorruptFileCounterServlet.java
public static String generateTable(Map<String, Map<CorruptFileStatus, Long>> corruptFilesCounterMap, String infoAddr, double numDetectionsPerSec, RaidNode raidNode) throws UnsupportedEncodingException, IOException { StringBuilder htmlSb = new StringBuilder(); int imageSize = 30; htmlSb.append(JspUtils.tr(JspUtils.td("Root Directory") + JspUtils.td(JspUtils.image(raidNode, "RURF.jpg", imageSize, imageSize), "Raid Unrecoverable Files") + JspUtils.td(JspUtils.image(raidNode, "NRURF.jpg", imageSize, imageSize), "Not-Raid Unrecoverable Files") + JspUtils.td(JspUtils.image(raidNode, "PURF.jpg", imageSize, imageSize), "Potential Unrecoverable Files") + JspUtils.td(JspUtils.image(raidNode, "RF.jpg", imageSize, imageSize), "Recoverable Files") + JspUtils.td(JspUtils.image(raidNode, "DL.jpg", imageSize, imageSize), "Detection Lag(s)") + JspUtils.td(/*from ww w. j av a 2s . c om*/ JspUtils.image(raidNode, "RL.jpg", imageSize, imageSize) + " " + getPercentHeader(raidNode), "Recovery Lag(s)") + JspUtils.td(JspUtils.image(raidNode, "RFF.jpg", imageSize, imageSize), "Recovery Failed Files"))); for (String path : corruptFilesCounterMap.keySet()) { Map<CorruptFileStatus, Long> counters = corruptFilesCounterMap.get(path); StringBuilder oneRow = new StringBuilder(); TreeMap<Long, BlockFixStatus> countersMap = raidNode.getBlockIntegrityMonitor().getBlockFixStatus(path, System.currentTimeMillis()); int windowSize = countersMap.keySet().size(); oneRow.append(JspUtils.th(windowSize, path)); // Append corrupt file counters for (CorruptFileStatus cfs : columns) { Long count = counters.get(cfs); String counterDisplay = ""; if (count == null || count <= 0) { counterDisplay = "0"; } else { StringBuffer url = new StringBuffer("http://" + infoAddr + "/corruptfilecounter"); url.append("?root="); url.append(URLEncoder.encode(path, "UTF-8")); url.append("&status="); url.append(URLEncoder.encode(cfs.name(), "UTF-8")); counterDisplay = getHTMLLinksText(url.toString(), String.valueOf(count)); } oneRow.append(JspUtils.th(windowSize, counterDisplay)); } // Append detection lag Long potentialCorruptFiles = counters.get(CorruptFileStatus.POTENTIALLY_CORRUPT); String detectionLag = ""; if (potentialCorruptFiles == null || potentialCorruptFiles <= 0) { detectionLag = "0"; } else if (numDetectionsPerSec < 1e-6) { detectionLag = "-"; } else { long costTime = (long) Math.ceil((double) potentialCorruptFiles / numDetectionsPerSec); detectionLag = Long.toString(costTime); } oneRow.append(JspUtils.th(windowSize, detectionLag)); oneRow.append(JspUtils.tdWithClass(getRecoveryLag(countersMap.firstKey(), countersMap, path, infoAddr), JspUtils.SMALL_CELL)); oneRow.append(JspUtils.tdWithClass(getFailedFiles(countersMap.firstKey(), countersMap, path, infoAddr), JspUtils.SMALL_CELL)); htmlSb.append(JspUtils.tr(oneRow.toString())); // Append recovery lags boolean head = true; for (Long window : countersMap.keySet()) { if (head) { head = false; continue; } StringBuilder sb = new StringBuilder(); sb.append(JspUtils.tdWithClass(getRecoveryLag(window, countersMap, path, infoAddr), JspUtils.SMALL_CELL)); sb.append(JspUtils.tdWithClass(getFailedFiles(window, countersMap, path, infoAddr), JspUtils.SMALL_CELL)); htmlSb.append(JspUtils.tr(sb.toString())); } } return JspUtils.smallTable(htmlSb.toString()); }
From source file:com.google.gwt.benchmarks.viewer.server.ReportImageServer.java
private JFreeChart createChart(String testName, Result result, String title, List<Result> comparativeResults) { // Find the maximum values across both axes for all of the results // (this chart's own results, plus all comparative results). ///*w w w .j av a 2 s . c om*/ // This is a stop-gap solution that helps us compare different charts for // the same benchmark method (usually with different user agents) until we // get real comparative functionality in version two. double maxTime = 0; for (Result r : comparativeResults) { for (Trial t : r.getTrials()) { maxTime = Math.max(maxTime, t.getRunTimeMillis()); } } // Determine the number of variables in this benchmark method List<Trial> trials = result.getTrials(); Trial firstTrial = new Trial(); int numVariables = 0; if (trials.size() > 0) { firstTrial = trials.get(0); numVariables = firstTrial.getVariables().size(); } // Display the trial data. // // First, pick the domain and series variables for our graph. // Right now we only handle up to two "user" variables. // We set the domain variable to the be the one containing the most unique // values. // This might be easier if the results had meta information telling us // how many total variables there are, what types they are of, etc.... String domainVariable = null; String seriesVariable = null; Map<String, Set<String>> variableValues = null; if (numVariables == 1) { domainVariable = firstTrial.getVariables().keySet().iterator().next(); } else { // TODO(tobyr): Do something smarter, like allow the user to specify which // variables are domain and series, along with the variables which are // held constant. variableValues = new HashMap<String, Set<String>>(); for (int i = 0; i < trials.size(); ++i) { Trial trial = trials.get(i); Map<String, String> variables = trial.getVariables(); for (Map.Entry<String, String> entry : variables.entrySet()) { String variable = entry.getKey(); Set<String> set = variableValues.get(variable); if (set == null) { set = new TreeSet<String>(); variableValues.put(variable, set); } set.add(entry.getValue()); } } TreeMap<Integer, List<String>> numValuesMap = new TreeMap<Integer, List<String>>(); for (Map.Entry<String, Set<String>> entry : variableValues.entrySet()) { Integer numValues = new Integer(entry.getValue().size()); List<String> variables = numValuesMap.get(numValues); if (variables == null) { variables = new ArrayList<String>(); numValuesMap.put(numValues, variables); } variables.add(entry.getKey()); } if (numValuesMap.values().size() > 0) { domainVariable = numValuesMap.get(numValuesMap.lastKey()).get(0); seriesVariable = numValuesMap.get(numValuesMap.firstKey()).get(0); } } String valueTitle = "time (ms)"; // This axis is time across all charts. if (numVariables == 0) { // Show a bar graph, with a single centered simple bar // 0 variables means there is only 1 trial DefaultCategoryDataset data = new DefaultCategoryDataset(); data.addValue(firstTrial.getRunTimeMillis(), "result", "result"); JFreeChart chart = ChartFactory.createBarChart(title, testName, valueTitle, data, PlotOrientation.VERTICAL, false, false, false); CategoryPlot p = chart.getCategoryPlot(); ValueAxis axis = p.getRangeAxis(); axis.setUpperBound(maxTime + maxTime * 0.1); return chart; } else if (numVariables == 1) { // Show a line graph with only 1 series // Or.... choose between a line graph and a bar graph depending upon // whether the type of the domain is numeric. XYSeriesCollection data = new XYSeriesCollection(); XYSeries series = new XYSeries(domainVariable); for (Trial trial : trials) { double time = trial.getRunTimeMillis(); String domainValue = trial.getVariables().get(domainVariable); series.add(Double.parseDouble(domainValue), time); } data.addSeries(series); JFreeChart chart = ChartFactory.createXYLineChart(title, domainVariable, valueTitle, data, PlotOrientation.VERTICAL, false, false, false); XYPlot plot = chart.getXYPlot(); plot.getRangeAxis().setUpperBound(maxTime + maxTime * 0.1); double maxDomainValue = getMaxValue(comparativeResults, domainVariable); plot.getDomainAxis().setUpperBound(maxDomainValue + maxDomainValue * 0.1); return chart; } else if (numVariables == 2) { // Show a line graph with two series XYSeriesCollection data = new XYSeriesCollection(); Set<String> seriesValues = variableValues.get(seriesVariable); for (String seriesValue : seriesValues) { XYSeries series = new XYSeries(seriesValue); for (Trial trial : trials) { Map<String, String> variables = trial.getVariables(); if (variables.get(seriesVariable).equals(seriesValue)) { double time = trial.getRunTimeMillis(); String domainValue = trial.getVariables().get(domainVariable); series.add(Double.parseDouble(domainValue), time); } } data.addSeries(series); } // TODO(tobyr) - Handle graphs above 2 variables JFreeChart chart = ChartFactory.createXYLineChart(title, domainVariable, valueTitle, data, PlotOrientation.VERTICAL, true, true, false); XYPlot plot = chart.getXYPlot(); plot.getRangeAxis().setUpperBound(maxTime + maxTime * 0.1); double maxDomainValue = getMaxValue(comparativeResults, domainVariable); plot.getDomainAxis().setUpperBound(maxDomainValue + maxDomainValue * 0.1); return chart; } throw new RuntimeException("The ReportImageServer is not yet able to " + "create charts for benchmarks with more than two variables."); // Sample JFreeChart code for creating certain charts: // Leaving this around until we can handle multivariate charts in dimensions // greater than two. // Code for creating a category data set - probably better with a bar chart // instead of line chart /* * DefaultCategoryDataset data = new DefaultCategoryDataset(); String series * = domainVariable; * * for ( Iterator it = trials.iterator(); it.hasNext(); ) { Trial trial = * (Trial) it.next(); double time = trial.getRunTimeMillis(); String * domainValue = (String) trial.getVariables().get( domainVariable ); * data.addValue( time, series, domainValue ); } * * String title = ""; String categoryTitle = domainVariable; PlotOrientation * orientation = PlotOrientation.VERTICAL; * * chart = ChartFactory.createLineChart( title, categoryTitle, valueTitle, * data, orientation, true, true, false ); */ /* * DefaultCategoryDataset data = new DefaultCategoryDataset(); String * series1 = "firefox"; String series2 = "ie"; * * data.addValue( 1.0, series1, "1024"); data.addValue( 2.0, series1, * "2048"); data.addValue( 4.0, series1, "4096"); data.addValue( 8.0, * series1, "8192"); * * data.addValue( 2.0, series2, "1024"); data.addValue( 4.0, series2, * "2048"); data.addValue( 8.0, series2, "4096"); data.addValue( 16.0, * series2,"8192"); * * String title = ""; String categoryTitle = "size"; PlotOrientation * orientation = PlotOrientation.VERTICAL; * * chart = ChartFactory.createLineChart( title, categoryTitle, valueTitle, * data, orientation, true, true, false ); */ }
From source file:org.starfishrespect.myconsumption.server.business.sensors.SensorsDataRetriever.java
/** * Retrieves and stores the data for one user * * @param onlyThisSensorId retrieve only data for one sensor with this id * @return false if something goes wrong; true otherwise *///from w w w . ja v a 2 s .c o m public boolean retrieve(List<Sensor> sensors, String onlyThisSensorId) { boolean allSuccessful = true; for (Sensor sensor : sensors) { System.out.println("Retrieve data for sensor " + sensor.getId()); try { valuesRepository.setSensor(sensor.getId()); valuesRepository.init(); if (onlyThisSensorId != null) { if (!sensor.getId().equals(onlyThisSensorId)) { continue; } } HashMap<Integer, HashMap<Integer, Integer>> sortedValues = new HashMap<Integer, HashMap<Integer, Integer>>(); Date lastValue = sensor.getLastValue(); SensorRetriever retriever = null; if (sensor instanceof FluksoSensor) { retriever = new FluksoRetriever((FluksoSensor) sensor); } if (retriever == null) { System.out.println("This sensor type has not been found!"); continue; } TreeMap<Integer, Integer> data = retriever.getDataSince(lastValue).getData(); if (data.size() != 0) { for (int key : data.keySet()) { int hour = key - key % 3600; HashMap<Integer, Integer> hourData = sortedValues.get(hour); if (hourData == null) { hourData = new HashMap<Integer, Integer>(); sortedValues.put(hour, hourData); } hourData.put(key % 3600, data.get(key)); } for (int key : sortedValues.keySet()) { Date dateKey = new Date(key * 1000L); SensorDataset newValue = new SensorDataset(dateKey); newValue.addAllValues(sortedValues.get(key)); valuesRepository.insertOrUpdate(newValue); } if (sensor.getLastValue().before(new Date(data.lastKey() * 1000L))) { sensor.setLastValue(new Date(data.lastKey() * 1000L)); } if (sensor.getFirstValue().after(new Date(data.firstKey() * 1000L)) || sensor.getFirstValue().getTime() == 0) { sensor.setFirstValue(new Date(data.firstKey() * 1000L)); } // sync operation, this avoid to insert a sensor who would have been deleted // while retrieving its data int currentUsageCount = sensorRepository.getUsageCount(sensor.getId()); if (currentUsageCount > -1) { // update, the field may have been incremented during retrieving sensor.setUsageCount(currentUsageCount); sensor.setDead(false); sensorRepository.updateSensor(sensor); } System.out.println("Retrieve successful"); } else { System.out.println("No values retrieved for this sensor"); if (!sensor.isDead()) { // test if sensor is dead ? Calendar cal = new GregorianCalendar(); cal.add(Calendar.HOUR, -6); if (sensor.getLastValue().before(new Date(cal.getTimeInMillis()))) { System.out.println( "Sensor has not sent anything in the last 6 hours! Set its status as dead."); sensor.setDead(true); sensorRepository.updateSensor(sensor); } } else { System.out.println("Sensor is still dead"); } } } catch (RetrieveException | DaoException e) { System.err.println(e.getMessage()); allSuccessful = false; } } return allSuccessful; }
From source file:ch.unil.genescore.pathway.GeneSetLibrary.java
License:asdf
/** get a weighted random sample; implementing Efraimidis et al. 2006 */ double[] getWeightedRandomSample(int setLength, double[] totSet, double[] totWeights) { //NaturalRanking ranker = new NaturalRanking(); double[] draws = new double[totWeights.length]; int[] ranks = new int[totWeights.length]; double[] out = new double[setLength]; TreeMap<Double, Integer> myRankTree = new TreeMap<Double, Integer>(); int treesize = 0; for (int i = 0; i < totWeights.length; i++) { draws[i] = Math.log(rand.nextDouble()) / totWeights[i]; if (treesize < setLength) { treesize++;//www . j av a 2 s .c om myRankTree.put(draws[i], i); } else if (treesize == setLength) if (myRankTree.firstKey() < draws[i]) { myRankTree.pollFirstEntry(); myRankTree.put(draws[i], i); } } Iterator<Entry<Double, Integer>> it = myRankTree.entrySet().iterator(); Entry<Double, Integer> ent; int count = 0; while (it.hasNext()) { ent = it.next(); ranks[count] = ent.getValue(); count++; //int rank = it.; } for (int i = 0; i < setLength; i++) { out[i] = totSet[ranks[i]]; } return out; }
From source file:org.openmicroscopy.shoola.agents.measurement.view.IntensityView.java
/** * Outputs the summary information from the shape map. * //from ww w . j a v a2 s . co m * @param writer The Excel writer. * @param shapeMap see above. * @throws IOException */ private void outputSummary(ExcelWriter writer, TreeMap<Coord3D, ROIShape> shapeMap) { int rowIndex = 0; printSummaryHeader(writer, rowIndex); rowIndex++; Coord3D start = shapeMap.firstKey(); Coord3D end = shapeMap.lastKey(); Coord3D coord; List<Integer> channels = new ArrayList<Integer>(channelName.keySet()); Set<Coord3D> keys; Iterator<Coord3D> i; for (Integer c : channels) { keys = shapeMap.keySet(); i = keys.iterator(); while (i.hasNext()) { coord = (Coord3D) i.next(); populateData(coord, c); outputSummaryRow(writer, rowIndex, c, coord.getZSection(), coord.getTimePoint()); rowIndex++; } } }
From source file:de.uzk.hki.da.sb.SIPFactory.java
/** * Creates a list of source folders//from w w w. j av a2 s . c om * * @param folderPath * The main source folder path * @throws Exception */ HashMap<File, String> createFolderList(String folderPath) throws Exception { HashMap<File, String> folderListWithFolderNames = new HashMap<File, String>(); File sourceFolder = new File(folderPath); switch (kindofSIPBuilding) { case MULTIPLE_FOLDERS: List<File> folderContent = Arrays.asList(sourceFolder.listFiles()); for (File file : folderContent) { if (!file.isHidden() && file.isDirectory()) folderListWithFolderNames.put(file, null); } break; case SINGLE_FOLDER: folderListWithFolderNames.put(sourceFolder, null); break; case NESTED_FOLDERS: NestedContentStructure ncs; try { TreeMap<File, String> metadataFileWithType = new FormatDetectionService(sourceFolder) .getMetadataFileWithType(); if (!metadataFileWithType.isEmpty() && (!metadataFileWithType.get(metadataFileWithType.firstKey()) .equals(C.CB_PACKAGETYPE_METS))) { messageWriter.showMessage("Es wurde eine Metadatendatei des Typs " + metadataFileWithType.get(metadataFileWithType.firstKey()) + " auf der obersten Ebene gefunden. " + "\nBitte whlen Sie diese Option ausschlielich fr die Erstellung von SIPs des Typs METS."); } else { ncs = new NestedContentStructure(sourceFolder); folderListWithFolderNames = ncs.getSipCandidates(); if (folderListWithFolderNames.isEmpty()) { messageWriter.showMessage( "Es wurde kein Unterverzeichnis mit einer METS-Metadatendatei gefunden."); } break; } } catch (IOException e) { throw new Exception(e); } default: break; } return folderListWithFolderNames; }
From source file:nars.predict.RNNBeliefPrediction.java
@Override protected void train() { ////from w w w. ja va2 s .c o m //double[] target = {((data[x(i1)] + data[x(i2)])/2.0)}; //new Sample(data, target, 2, length, 1, 1); TreeMap<Integer, double[]> d = new TreeMap(); int cc = 0; int hd = Math.round(predictionTimeSpanFactor * nar.memory.getDuration() / 2f / downSample); for (Concept c : concepts) { for (Sentence s : c.beliefs) { if (s.isEternal()) { continue; } int o = (int) Math.round(((double) s.getOccurenceTime()) / ((double) downSample)); if (o > nar.time()) { continue; //non-future beliefs } for (int oc = o - hd; oc <= o + hd; oc++) { double[] x = d.get(oc); if (x == null) { x = new double[inputSize]; d.put(oc, x); } float freq = 2f * (s.truth.getFrequency() - 0.5f); float conf = s.truth.getConfidence(); if (freq < 0) { } x[cc] += freq * conf; } } cc++; } if (d.size() < 2) { data = null; return; } data = new SampleSet(); int first = d.firstKey(); int last = (int) nar.time(); if (last - first > maxDataFrames * downSample) { first = last - maxDataFrames * downSample; } int frames = (int) (last - first); int bsize = getInputSize() * frames; int isize = getPredictionSize() * frames; if (actual == null || actual.length != bsize) actual = new double[bsize]; else Arrays.fill(actual, 0); if (ideal == null || ideal.length != isize) ideal = new double[isize]; else Arrays.fill(ideal, 0); int idealSize = getPredictionSize(); int ac = 0, id = 0; double[] prevX = null; for (int i = first; i <= last; i++) { double[] x = d.get(i); if (x == null) { x = new double[inputSize]; } else { if (normalizeInputVectors) { x = normalize(x); } } if (prevX != null) { System.arraycopy(prevX, 0, actual, ac, inputSize); ac += inputSize; System.arraycopy(getTrainedPrediction(x), 0, ideal, id, idealSize); id += idealSize; } prevX = x; } Sample s = new Sample(actual, ideal, inputSize, idealSize); data.add(s); //System.out.println(data); if (trainer == null) { trainer = new GradientDescent(); trainer.setNet(net); trainer.setRnd(rnd); trainer.setPermute(true); trainer.setTrainingSet(data); trainer.setLearningRate(learningrate); trainer.setMomentum(momentum); trainer.setEpochs(trainIterationsPerCycle); trainer.setEarlyStopping(false); trainer.setOnline(true); trainer.setTargetError(0); trainer.clearListener(); } else { //trainer.reset(); } trainer.train(); //System.out.println("LSTM error: " + trainer.getTrainingError()); }
From source file:org.kuali.kfs.module.purap.document.web.struts.AccountsPayableActionBase.java
/** * Builds and asks questions which require text input by the user for a payment request or a credit memo. * * @param mapping An ActionMapping/* ww w . jav a 2 s. co m*/ * @param form An ActionForm * @param request The HttpServletRequest * @param response The HttpServletResponse * @param questionType A String used to distinguish which question is being asked * @param notePrefix A String explaining what action was taken, to be prepended to the note containing the reason, which gets * written to the document * @param operation A one-word String description of the action to be taken, to be substituted into the message. (Can be an * empty String for some messages.) * @param messageKey A (whole) key to the message which will appear on the question screen * @param questionsAndCallbacks A TreeMap associating the type of question to be asked and the type of callback which should * happen in that case * @param messagePrefix The most general part of a key to a message text to be retrieved from ConfigurationService, * Describes a collection of questions. * @param redirect An ActionForward to return to if done with questions * @return An ActionForward * @throws Exception */ protected ActionForward askQuestionWithInput(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionType, String notePrefix, String operation, String messageKey, TreeMap<String, PurQuestionCallback> questionsAndCallbacks, String messagePrefix, ActionForward redirect) throws Exception { KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form; AccountsPayableDocumentBase apDocument = (AccountsPayableDocumentBase) kualiDocumentFormBase.getDocument(); String question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME); String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME); String noteText = ""; ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class); String firstQuestion = questionsAndCallbacks.firstKey(); PurQuestionCallback callback = null; Iterator questions = questionsAndCallbacks.keySet().iterator(); String mapQuestion = null; String key = null; // Start in logic for confirming the close. if (question == null) { key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, firstQuestion); String message = StringUtils.replace(key, "{0}", operation); // Ask question if not already asked. return this.performQuestionWithInput(mapping, form, request, response, firstQuestion, message, KFSConstants.CONFIRMATION_QUESTION, questionType, ""); } else { // find callback for this question while (questions.hasNext()) { mapQuestion = (String) questions.next(); if (StringUtils.equals(mapQuestion, question)) { callback = questionsAndCallbacks.get(mapQuestion); break; } } key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, mapQuestion); Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON); if (question.equals(mapQuestion) && buttonClicked.equals(ConfirmationQuestion.NO)) { // If 'No' is the button clicked, just reload the doc String nextQuestion = null; // ask another question if more left if (questions.hasNext()) { nextQuestion = (String) questions.next(); key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, nextQuestion); return this.performQuestionWithInput(mapping, form, request, response, nextQuestion, key, KFSConstants.CONFIRMATION_QUESTION, questionType, ""); } else { return mapping.findForward(KFSConstants.MAPPING_BASIC); } } // Have to check length on value entered. String introNoteMessage = notePrefix + KFSConstants.BLANK_SPACE; // Build out full message. noteText = introNoteMessage + reason; int noteTextLength = noteText.length(); // Get note text max length from DD. int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class) .getAttributeMaxLength(Note.class, KFSConstants.NOTE_TEXT_PROPERTY_NAME).intValue(); if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) { // Figure out exact number of characters that the user can enter. int reasonLimit = noteTextMaxLength - noteTextLength; if (reason == null) { // Prevent a NPE by setting the reason to a blank string. reason = ""; } return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, mapQuestion, key, KFSConstants.CONFIRMATION_QUESTION, questionType, "", reason, PurapKeyConstants.ERROR_PAYMENT_REQUEST_REASON_REQUIRED, KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString()); } } // make callback if (ObjectUtils.isNotNull(callback)) { AccountsPayableDocument refreshedApDocument = callback.doPostQuestion(apDocument, noteText); kualiDocumentFormBase.setDocument(refreshedApDocument); } String nextQuestion = null; // ask another question if more left if (questions.hasNext()) { nextQuestion = (String) questions.next(); key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, nextQuestion); return this.performQuestionWithInput(mapping, form, request, response, nextQuestion, key, KFSConstants.CONFIRMATION_QUESTION, questionType, ""); } return redirect; }