List of usage examples for java.util ArrayList set
public E set(int index, E element)
From source file:ch.icclab.cyclops.support.database.influxdb.client.InfluxDBClient.java
/** * This method gets the data from the database for a parametrized Query, format it and send it back as a TSDBData. * * @param parameterQuery/* w ww. ja v a2s . c o m*/ * @return */ public TSDBData getData(String parameterQuery) { //TODO: check the sense of the TSDBData[] and simplify/split the code logger.debug("Attempting to get Data"); InfluxDB influxDB = InfluxDBFactory.connect(this.url, this.username, this.password); JSONArray resultArray; TSDBData[] dataObj = null; ObjectMapper mapper = new ObjectMapper(); int timeIndex = -1; int usageIndex = -1; Query query = new Query(parameterQuery, dbName); try { logger.debug("Attempting to execute the query: " + parameterQuery + " into the db: " + dbName); resultArray = new JSONArray(influxDB.query(query).getResults()); logger.debug("Obtained results: " + resultArray.toString()); if (!resultArray.isNull(0)) { if (resultArray.toString().equals("[{}]")) { TSDBData data = new TSDBData(); data.setColumns(new ArrayList<String>()); data.setPoints(new ArrayList<ArrayList<Object>>()); data.setTags(new HashMap()); return data; } else { JSONObject obj = (JSONObject) resultArray.get(0); JSONArray series = (JSONArray) obj.get("series"); for (int i = 0; i < series.length(); i++) { String response = series.get(i).toString(); response = response.split("values")[0] + "points" + response.split("values")[1]; series.put(i, new JSONObject(response)); } dataObj = mapper.readValue(series.toString(), TSDBData[].class); //Filter the points for repeated timestamps and add their usage/avg value for (int i = 0; i < dataObj.length; i++) { for (int o = 0; o < dataObj[i].getColumns().size(); o++) { if (dataObj[i].getColumns().get(o).equalsIgnoreCase("time")) timeIndex = o; if (dataObj[i].getColumns().get(o).equalsIgnoreCase("usage") || dataObj[i].getColumns().get(o).equalsIgnoreCase("avg")) usageIndex = o; } if (usageIndex > -1) { //If the json belongs to a meter point, filter and add to another if necessary. TreeMap<String, ArrayList> points = new TreeMap<String, ArrayList>(); for (ArrayList point : dataObj[i].getPoints()) { if (points.containsKey(point.get(timeIndex))) { String time = (String) point.get(timeIndex); Double usage = Double.parseDouble(points.get(time).get(usageIndex).toString()); usage = Double.parseDouble(point.get(usageIndex).toString()) + usage; point.set(usageIndex, usage); } points.put((String) point.get(timeIndex), point); } ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>(); for (String key : points.keySet()) { result.add(points.get(key)); } dataObj[i].setPoints(result); } } } } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dataObj[0]; }
From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.AuditReportPPTData.java
/** * Add an array for the volumetry of projects by profile. The array contains: columns: {Profile, projectName1, * projectName2,..., projectNameN, Total, Comments} rows: {profile1, tre1OfProfile1, ..., treNOfProfileN, ..., * profileN, tre1OfprofileN, ..., treNOfProfileN} * /* w w w.j a v a 2s. com*/ * @param slideToSet slide to modify * @param where place to add shape * @throws IOException if error * @throws PPTGeneratorException */ public void setProfileVolTab(Slide slideToSet, Rectangle where) throws IOException, PPTGeneratorException { log.info("AuditReturn - setProfileVolTab"); // Create a map of map of lists in order to create the volumetry profile array // key: profileName; value: mapTre // mapTre --> key: treName; value: List of String final int nbPredefinedCols = 2; final int nbCols = nbPredefinedCols + projectReports.size(); TreeMap globalMap = new TreeMap(); List titles = new ArrayList(nbCols); // col 1: profile titles.add(WebMessages.getString(request, "export.audit_report.set.volByProfile.profile_col.title")); for (int i = 0; i < projectReports.size(); i++) { ProjectReportDTO curProject = (ProjectReportDTO) projectReports.get(i); log.info("AuditReturn - setProfileVolTab Project n" + i + " : " + curProject.getName()); // add project name on titles line titles.add(curProject.getName()); TreeMap tresMap = (TreeMap) globalMap.get(curProject.getProfileName()); if (null == tresMap) { tresMap = new TreeMap(); } for (Iterator tresIt = curProject.getVolumetryMeasures().keySet().iterator(); tresIt.hasNext();) { String curTre = (String) tresIt.next(); log.debug("AuditReturn - setProfileVolTab Measure : " + curTre); // add line in tab for this tre ArrayList valuesForTre = (ArrayList) tresMap.get(curTre); if (null == valuesForTre) { valuesForTre = createEmptyList(projectReports.size()); } // set value for project cell for this tre valuesForTre.set(i, curProject.getVolumetryMeasures().get(curTre).toString()); tresMap.put(curTre, valuesForTre); } log.debug("AuditReturn - setProfileVolTab Measure iteration done "); globalMap.put(curProject.getProfileName(), tresMap); } // add the two last titles titles.add(WebMessages.getString(request, "export.audit_report.set.volByProfile.total_col.title")); // create table with map // addPicture( slideToSet, htmlToImage( createVolByProfileTable( where, titles, globalMap ).toString() ), where // ); log.debug("AuditReturn - setProfileVolTab end processing "); addHtmlPicture(slideToSet, createVolByProfileTable(where, titles, globalMap).toString(), where.x, where.y); log.info("AuditReturn - setProfileVolTab done"); }
From source file:org.spoutcraft.api.gui.GenericLabel.java
public void recalculateLines() { lines = text.split("\\n"); if (isWrapLines()) { ArrayList<String> linesTmp = new ArrayList<String>(lines.length); for (String line : lines) { linesTmp.add(line);//from w w w. ja v a 2s. c o m } for (int i = 0; i < linesTmp.size(); i++) { boolean wrapForSpace = true; String line = linesTmp.get(i); String lineTmp = new String(line); int brk = -1; while (Spoutcraft.getMinecraftFont().getTextWidth(lineTmp) > super.getWidth() && super.getWidth() >= 5 && !lineTmp.isEmpty()) { brk = lineTmp.lastIndexOf(" "); if (brk == -1) { brk = lineTmp.length() - 2; wrapForSpace = false; } lineTmp = lineTmp.substring(0, brk); } if (brk != -1) { linesTmp.set(i, lineTmp); String otherLine = line.substring(brk + (wrapForSpace ? 1 : 0), line.length()); if (!StringUtils.isEmpty(otherLine.trim())) { linesTmp.add(i + 1, otherLine); } } } lines = linesTmp.toArray(new String[0]); if (isAuto()) { setHeight(lines.length * 11); } } }
From source file:gov.nih.nci.caintegrator.application.gpvisualizer.CaIntegratorRunVisualizer.java
protected String[] doCommandLineSubstitutions() throws IOException { // do input argument substitution in command line String commandLine = (String) params.get(RunVisualizerConstants.COMMAND_LINE); HashMap hmDownloadables = downloadInputURLs(); StringTokenizer stCmd = new StringTokenizer(commandLine, " "); ArrayList cmdArray = new ArrayList(stCmd.countTokens()); int c = 0;/*w w w . j av a 2 s .c o m*/ while (stCmd.hasMoreTokens()) { cmdArray.add(stCmd.nextToken()); } // replace variables in the command line from System.properties and the // params HashMap for (c = 0; c < cmdArray.size(); c++) { String cmd = (String) cmdArray.get(c); cmd = variableSubstitution(cmd, hmDownloadables); cmdArray.set(c, cmd); // if there is nothing in a slot after substitutions, delete the // slot entirely if (cmd.length() == 0) { cmdArray.remove(c); c--; } } cmdArray.trimToSize(); return (String[]) cmdArray.toArray(new String[0]); }
From source file:opennlp.tools.textsimilarity.TextProcessor.java
/** * Splits input text into sentences./*from w w w . ja v a 2 s . c o m*/ * * @param txt * Input text * @return List of sentences */ public static ArrayList<String> splitToSentences(String text) { ArrayList<String> sentences = new ArrayList<String>(); if (text.trim().length() > 0) { String s = "[\\?!\\.]\"?[\\s+][A-Z0-9i]"; text += " XOXOX."; Pattern p = Pattern.compile(s, Pattern.MULTILINE); Matcher m = p.matcher(text); int idx = 0; String cand = ""; // while(m.find()){ // System.out.println(m.group()); // } while (m.find()) { cand += " " + text.substring(idx, m.end() - 1).trim(); boolean hasAbbrev = false; for (int i = 0; i < abbrevs.length; i++) { if (cand.toLowerCase().endsWith(abbrevs[i])) { hasAbbrev = true; break; } } if (!hasAbbrev) { sentences.add(cand.trim()); cand = ""; } idx = m.end() - 1; } if (idx < text.length()) { sentences.add(text.substring(idx).trim()); } if (sentences.size() > 0) { sentences.set(sentences.size() - 1, sentences.get(sentences.size() - 1).replace(" XOXOX.", "")); } } return sentences; }
From source file:edu.harvard.mcz.nametools.ICNafpAuthorNameComparator.java
/** * Given a botanical authorship string, split it into a list of component * authors on parenthetical authors, ex authors, and sanctioning authors. * // w w w. ja va2s .co m * @param authorship to tokenize * @return a list of authorship strings representing the components of the * authorship string. */ public static List<String> tokenizeAuthorship(String authorship) { ArrayList<String> bits = new ArrayList<String>(); ArrayList<String> subbits = new ArrayList<String>(); ArrayList<String> result = new ArrayList<String>(); if (authorship == null || authorship.length() == 0) { return result; } // separate out parenthetical author logger.debug(authorship); if (authorship.matches("^\\(.*\\).+$")) { String[] parBits = authorship.split("\\)"); logger.debug(parBits.length); logger.debug(parBits[0]); bits.add(parBits[0].replaceFirst("^\\(", "")); bits.add(parBits[1]); } else { bits.add(authorship); } // separate out ex author Iterator<String> i = bits.iterator(); while (i.hasNext()) { String bit = i.next(); if (bit.contains(" ex ")) { String[] exBits = bit.split(" ex "); logger.debug(exBits.length); logger.debug(exBits[0]); logger.debug(exBits[1]); subbits.add(exBits[0]); subbits.add(exBits[1]); } else { logger.debug(bit); subbits.add(bit); } } // separate out sanctioning author Iterator<String> ir = subbits.iterator(); while (ir.hasNext()) { String bit = ir.next(); if (bit.contains(":")) { String[] exBits = bit.split(":"); result.add(exBits[0]); result.add(exBits[1]); } else { result.add(bit); } } // strip any leading/trailing spaces for (int j = 0; j < result.size(); j++) { result.set(j, result.get(j).trim()); } return result; }
From source file:com.vgi.mafscaling.Rescale.java
private void updateNewMafScale() { try {/*from w ww .ja v a 2 s. c o m*/ corrMafData.clear(); currMafData.clear(); Utils.clearTable(newMafTable); if (newMaxVFmtTextBox.getValue() == null || maxVUnchangedFmtTextBox.getValue() == null || minVFmtTextBox.getValue() == null || origMafTable.getValueAt(0, 0).toString().isEmpty()) return; if (origVoltArray.size() == 0 || origVoltArray.size() != origGsArray.size()) return; if (origVoltArray.size() < 10) { JOptionPane.showMessageDialog(null, "It looks like you have only partial original MAF scale table", "Invalid Data", JOptionPane.ERROR_MESSAGE); return; } double newMafV = (((Number) newMaxVFmtTextBox.getValue()).doubleValue()); if (newMafV < origVoltArray.get(0)) { JOptionPane.showMessageDialog(null, "New Max V [" + newMafV + "] can't be lower than first MAF table value", "Invalid Data", JOptionPane.ERROR_MESSAGE); return; } if (newMafV > origVoltArray.get(origVoltArray.size() - 1)) { JOptionPane.showMessageDialog(null, "New Max V [" + newMafV + "] can't be higher than last MAF table value", "Invalid Data", JOptionPane.ERROR_MESSAGE); return; } double minV = (((Number) minVFmtTextBox.getValue()).doubleValue()); if (minV <= origVoltArray.get(1)) { JOptionPane.showMessageDialog(null, "Min V [" + minV + "] must be higher than second MAF table value", "Invalid Data", JOptionPane.ERROR_MESSAGE); return; } if (minV > newMafV) { JOptionPane.showMessageDialog(null, "Min V [" + minV + "] can't be higher than new MAF V value", "Invalid Data", JOptionPane.ERROR_MESSAGE); return; } double maxVUnch = (((Number) maxVUnchangedFmtTextBox.getValue()).doubleValue()); if (maxVUnch <= minV) { JOptionPane.showMessageDialog(null, "Max Unchanged [" + maxVUnch + "] must be higher than Min V value", "Invalid Data", JOptionPane.ERROR_MESSAGE); return; } if (maxVUnch > newMafV) { JOptionPane.showMessageDialog(null, "Max Unchanged [" + maxVUnch + "] can't be higher than new MAF V value", "Invalid Data", JOptionPane.ERROR_MESSAGE); return; } int i, j, z; ArrayList<Double> newVoltArray = new ArrayList<Double>(); ArrayList<Double> newGsArray = new ArrayList<Double>(); newVoltArray.add(origVoltArray.get(0)); newGsArray.add(origGsArray.get(0)); // Find first value greater than MinV from original scale, // calculate mid-point and add them as second and third values to the new array. // After that simply copy all original values up until Max Unchanged value. boolean minFound = false; double val; for (i = 2; i < origVoltArray.size(); ++i) { val = origVoltArray.get(i); if (minFound) { if (val <= maxVUnch) newVoltArray.add(val); else break; } else if (minV <= val) { newVoltArray.add((val - origVoltArray.get(0)) / 2.0 + origVoltArray.get(0)); newVoltArray.add(val); minFound = true; } } int newMaxUnchIdx = newVoltArray.size() - 1; // Find avg % change per section in the original scale but for the same number of points as new scale double pointsCount = origVoltArray.size() - newVoltArray.size(); int sectionCount = (int) Math.ceil((double) pointsCount / (double) CellsPerSection); List<Double> modDeltaList = deltaVoltArray.subList(newMaxUnchIdx, deltaVoltArray.size()); double avgDelta = Utils.mean(modDeltaList); double maxDelta = Collections.max(modDeltaList); double minDelta = Collections.min(modDeltaList); double avgSectionChange = (maxDelta - minDelta) / sectionCount; double changePercent = (maxDelta - minDelta) / avgSectionChange; // Calculate delta per section double delta; ArrayList<Double> adj = new ArrayList<Double>(); for (i = 0; i < sectionCount; ++i) adj.add(avgDelta); int end = (int) Math.floor(sectionCount / 2.0); for (i = 0, j = sectionCount - 1; i < j; ++i, --j) { delta = avgDelta / 100.00 * changePercent * (end - i); adj.set(i, avgDelta - delta); adj.set(j, avgDelta + delta); } // Apply diff for each cell of each section for (i = newMaxUnchIdx + 1, j = 0, z = 0; i < origVoltArray.size(); ++i, ++j) { double diff = adj.get(z); if (j >= CellsPerSection) { j = 0; ++z; diff = adj.get(z); } newVoltArray.add(newVoltArray.get(i - 1) + diff); } // Since the above diffs are based of the original scale change simply adjust the new values to fit the new scale double corr = (newMafV - newVoltArray.get(newVoltArray.size() - 1)) / pointsCount; for (i = newMaxUnchIdx + 1, j = 1; i < newVoltArray.size(); ++i, ++j) newVoltArray.set(i, newVoltArray.get(i) + j * corr); calculateNewGs(newVoltArray, newGsArray); Utils.ensureColumnCount(newVoltArray.size(), newMafTable); for (i = 0; i < newVoltArray.size(); ++i) { newMafTable.setValueAt(newVoltArray.get(i), 0, i); newMafTable.setValueAt(newGsArray.get(i), 1, i); } setXYSeries(currMafData, origVoltArray, origGsArray); setXYSeries(corrMafData, newVoltArray, newGsArray); setRanges(mafChartPanel); } catch (Exception e) { logger.error(e); } }
From source file:hrpod.tools.nlp.StopWordRemoval.java
public ArrayList<String> removeStopWords(String[] words) { String newText = null;//from www .ja v a2 s.c om ArrayList<String> wordList = new ArrayList(); wordList.addAll(Arrays.asList(words)); //find stop/common words and remove them for (int w = 0; w < wordList.size(); w++) { String word = wordList.get(w); //break phrases down into individaul words ArrayList<String> subWordList = new ArrayList(); subWordList.addAll(Arrays.asList(wordList.get(w).split(" "))); //remove the stop words for (int swl = 0; swl < subWordList.size(); swl++) { for (int sw = 0; sw < stopWords.length; sw++) { String stopWord = stopWords[sw]; if (stopWords[sw].toLowerCase().contains(subWordList.get(swl).toLowerCase())) { //logger.info("REMOVE WORD: " + stopWords[sw]); subWordList.remove(swl); swl--; break; } } } wordList.set(w, StringUtils.join(subWordList, " ")); if (wordList.get(w).trim().equals("")) { wordList.remove(w); w--; } } //newText = StringUtils.join(wordList, " "); return wordList; }
From source file:org.openmrs.module.accessmonitor.web.controller.AccessMonitorPersonController.java
@RequestMapping(value = "/module/accessmonitor/person", method = RequestMethod.POST) public void postSave(ModelMap model, HttpServletRequest request) throws IOException { if (request.getParameter("offset") != null) { offset = Integer.parseInt(request.getParameter("offset")); }// w w w. ja va 2s. c o m int count = -1; // parse them to Date, null is acceptabl DateFormat format = new SimpleDateFormat("MM/dd/yyyy"); // Get the from date and to date Date to = null; Date from = null; try { from = format.parse(request.getParameter("datepickerFrom")); } catch (Exception e) { //System.out.println("======From Date Empty======="); } try { to = format.parse(request.getParameter("datepickerTo")); } catch (Exception e) { //System.out.println("======To Date Empty======="); } // get all the records in the date range if (personAccessData == null || personAccessData.size() == 0) { personAccessData = ((PersonAccessService) Context.getService(PersonAccessService.class)) .getPersonAccessesByAccessDateOrderByPersonId(from, to); if (personAccessData == null) { personAccessData = new ArrayList<PersonServiceAccess>(); } } // get date for small graph Date toSmall = to; Date fromSmall = null; Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 1); if (toSmall == null) { toSmall = calendar.getTime(); } else { calendar.setTime(toSmall); } calendar.add(Calendar.DATE, -DAYNUM); fromSmall = calendar.getTime(); List<String> dateStrings = new ArrayList<String>(); for (int i = 0; i < DAYNUM; i++) { if (i == DAYNUM - 1) { dateStrings.add(format.format(toSmall)); } else if (i == 0) { dateStrings.add(format.format(fromSmall)); } else { dateStrings.add(""); } } ArrayList<ArrayList<Integer>> tooltip = new ArrayList<ArrayList<Integer>>(); tooltip.add(new ArrayList<Integer>()); for (int j = 0; j < SHOWNUM + 1; j++) { tooltip.get(0).add(1000 + j); } for (int i = 1; i < DAYNUM + 1; i++) { tooltip.add(new ArrayList<Integer>()); tooltip.get(i).add(i); for (int j = 0; j < SHOWNUM; j++) { tooltip.get(i).add(0); } } ArrayList<String> personIds = new ArrayList<String>(); ArrayList<Integer> personCounts = new ArrayList<Integer>(); String last = ""; for (PersonServiceAccess pa : personAccessData) { // data for big graph String idString = (pa.getPersonId() == null) ? "No ID" : pa.getPersonId().toString(); if (!idString.equals(last)) { count++; last = idString; } int index = personIds.indexOf(idString); if (index < 0) { if (count < offset) continue; if (personIds.size() >= SHOWNUM) break; personIds.add(idString); personCounts.add(1); index = personIds.size() - 1;//index = personIds.indexOf(idString); } else { personCounts.set(index, personCounts.get(index) + 1); } // data for small graph if (pa.getAccessDate().after(fromSmall) && pa.getAccessDate().before(toSmall)) { int index2 = (int) ((pa.getAccessDate().getTime() - fromSmall.getTime()) / (1000 * 60 * 60 * 24)); if (index2 < DAYNUM && index2 >= 0) tooltip.get(index2 + 1).set(index + 1, tooltip.get(index2 + 1).get(index + 1) + 1); } } String personIdString = JSONValue.toJSONString(personIds); String personCountString = JSONValue.toJSONString(personCounts); String dateSmallString = JSONValue.toJSONString(dateStrings); String tooltipdata = JSONValue.toJSONString(tooltip); model.addAttribute("personIds", personIdString); model.addAttribute("personCounts", personCountString); model.addAttribute("dateSmallString", dateSmallString); model.addAttribute("tooltipdata", tooltipdata); model.addAttribute("user", Context.getAuthenticatedUser()); //model.addAttribute("tables1", personAccessData); //model.addAttribute("dateSmall", dateStrings); model.addAttribute("currentoffset", String.valueOf(offset)); }
From source file:org.apache.oozie.util.db.SqlStatement.java
/** * Replace the place holders with actual values in the sql statement * * @param oldVal Place holder//from w ww. jav a 2 s. co m * @param newVal Actual Value * @return SQL Statement with oldVal(place holder) replaced with newVal(actual value) */ public SqlStatement setValue(Object oldVal, Object newVal) { ArrayList<Object> temp = new ArrayList<Object>(values); if (values.contains(oldVal)) { int i = temp.indexOf(oldVal); temp.set(i, newVal); } SqlStatement retVal = create(temp); return retVal; }