List of usage examples for java.util ArrayList indexOf
public int indexOf(Object o)
From source file:de.tud.kom.p2psim.impl.network.gnp.topology.GnpSpace.java
/** * Calculates a good positions for the host * // w w w . j a v a 2s . c o m * @param host * to position * @param monitorResheduling * number of rescheduling the downhill simplex * @return gnp position for peer */ private GnpPosition insertCoordinateDownhillSimplex(Host host, int monitorResheduling) { double alpha = 1.0; double beta = 0.5; double gamma = 2; double maxDiversity = 0.5; // N + 1 initial random Solutions ArrayList<GnpPosition> solutions = new ArrayList<GnpPosition>(noOfDimensions + 1); for (int c = -1; c < noOfDimensions; c++) { GnpPosition coord = new GnpPosition(noOfDimensions, host, this); solutions.add(coord); } // best and worst solution GnpPosition bestSolution = Collections.min(solutions); GnpPosition worstSolution = Collections.max(solutions); double bestError = bestSolution.getDownhillSimplexError(); double worstError = worstSolution.getDownhillSimplexError(); double newError = 0.0; for (int z = 0; z < monitorResheduling; z++) { // resheduling for (GnpPosition coord : solutions) { if (coord != bestSolution) { coord.diversify(this.getDimension(), maxDiversity); } } // best and worst solution bestSolution = Collections.min(solutions); worstSolution = Collections.max(solutions); bestError = bestSolution.getDownhillSimplexError(); worstError = worstSolution.getDownhillSimplexError(); // stop criterion while (worstError - bestError > 0.000001 && calculationInProgress) { // move to center ... GnpPosition center = GnpPosition.getCenterSolution(solutions); GnpPosition newSolution1 = GnpPosition.getMovedSolution(worstSolution, center, 1 + alpha); newError = newSolution1.getDownhillSimplexError(); if (newError <= bestError) { GnpPosition newSolution2 = GnpPosition.getMovedSolution(worstSolution, center, 1 + alpha + gamma); int IndexOfWorstSolution = solutions.indexOf(worstSolution); if (newSolution2.getDownhillSimplexError() <= newError) { solutions.set(IndexOfWorstSolution, newSolution2); } else { solutions.set(IndexOfWorstSolution, newSolution1); } bestSolution = solutions.get(IndexOfWorstSolution); bestError = bestSolution.getDownhillSimplexError(); } else if (newError < worstError) { int IndexOfWorstSolution = solutions.indexOf(worstSolution); solutions.set(IndexOfWorstSolution, newSolution1); } else { // ... or contract around best solution for (int c = 0; c < solutions.size(); c++) { if (solutions.get(c) != bestSolution) solutions.set(c, GnpPosition.getMovedSolution(solutions.get(c), bestSolution, beta)); } bestSolution = Collections.min(solutions); bestError = bestSolution.getDownhillSimplexError(); } worstSolution = Collections.max(solutions); worstError = worstSolution.getDownhillSimplexError(); } } // Set the Coordinate Reference to the Peer host.setPositionReference(bestSolution); return bestSolution; }
From source file:ffx.potential.MolecularAssembly.java
/** * {@inheritDoc}//w w w. ja va 2 s . c o m */ @Override public MSNode addMSNode(MSNode o) { ArrayList Polymers = getAtomNodeList(); if (o instanceof Atom) { Atom atom = (Atom) o; if (atom.isModRes()) { return getResidue(atom, true, Residue.ResidueType.AA); } else if (!atom.isHetero()) { return getResidue(atom, true); } else { return getMolecule(atom, true); } } else if (o instanceof Residue) { Residue residue = (Residue) o; Character chainID = residue.getChainID(); String segID = residue.getSegID(); int index = Polymers.indexOf(new Polymer(chainID, segID)); /** * See if the polymer already exists. */ if (index != -1) { Polymer c = (Polymer) Polymers.get(index); setFinalized(false); return c.addMSNode(residue); } else { Polymer newc = new Polymer(chainID, segID); getAtomNode().add(newc); setFinalized(false); return newc.addMSNode(residue); } } else if (o instanceof Polymer) { Polymer c = (Polymer) o; int index = Polymers.indexOf(c); if (index == -1) { getAtomNode().add(c); setFinalized(false); return c; } else { return (Polymer) Polymers.get(index); } } else if (o instanceof Molecule) { Molecule m = (Molecule) o; if (m.getAtomNode().getChildCount() == 1) { ions.add(m); return m; } else if (Utilities.isWaterOxygen((Atom) m.getAtomNode().getChildAt(0))) { water.add(m); return m; } else { molecules.add(m); return m; } } else { String message = "Programming error in MolecularAssembly addNode"; logger.log(Level.SEVERE, message); return o; } }
From source file:org.peerfact.impl.network.gnp.topology.GnpSpace.java
/** * Calculates a good positions for the host * /* w w w. j a v a 2 s.c o m*/ * @param host * to position * @param monitorResheduling * number of rescheduling the downhill simplex * @return gnp position for peer */ private GnpPosition insertCoordinateDownhillSimplex(Host host, int monitorResheduling) { double alpha = 1.0; double beta = 0.5; double gamma = 2; double maxDiversity = 0.5; // N + 1 initial random Solutions ArrayList<GnpPosition> solutions = new ArrayList<GnpPosition>(noOfDimensions + 1); for (int c = -1; c < noOfDimensions; c++) { GnpPosition coord = new GnpPosition(noOfDimensions, host, this); solutions.add(coord); } // best and worst solution GnpPosition bestSolution = Collections.min(solutions); GnpPosition worstSolution = Collections.max(solutions); double bestError = bestSolution.getDownhillSimplexError(); double worstError = worstSolution.getDownhillSimplexError(); double newError = 0.0; for (int z = 0; z < monitorResheduling; z++) { // resheduling for (GnpPosition coord : solutions) { if (coord != bestSolution) { coord.diversify(this.getDimension(), maxDiversity); } } // best and worst solution bestSolution = Collections.min(solutions); worstSolution = Collections.max(solutions); bestError = bestSolution.getDownhillSimplexError(); worstError = worstSolution.getDownhillSimplexError(); // stop criterion while (worstError - bestError > 0.000001 && calculationInProgress) { // move to center ... GnpPosition center = GnpPosition.getCenterSolution(solutions); GnpPosition newSolution1 = GnpPosition.getMovedSolution(worstSolution, center, 1 + alpha); newError = newSolution1.getDownhillSimplexError(); if (newError <= bestError) { GnpPosition newSolution2 = GnpPosition.getMovedSolution(worstSolution, center, 1 + alpha + gamma); int IndexOfWorstSolution = solutions.indexOf(worstSolution); if (newSolution2.getDownhillSimplexError() <= newError) { solutions.set(IndexOfWorstSolution, newSolution2); } else { solutions.set(IndexOfWorstSolution, newSolution1); } bestSolution = solutions.get(IndexOfWorstSolution); bestError = bestSolution.getDownhillSimplexError(); } else if (newError < worstError) { int IndexOfWorstSolution = solutions.indexOf(worstSolution); solutions.set(IndexOfWorstSolution, newSolution1); } else { // ... or contract around best solution for (int c = 0; c < solutions.size(); c++) { if (solutions.get(c) != bestSolution) { solutions.set(c, GnpPosition.getMovedSolution(solutions.get(c), bestSolution, beta)); } } bestSolution = Collections.min(solutions); bestError = bestSolution.getDownhillSimplexError(); } worstSolution = Collections.max(solutions); worstError = worstSolution.getDownhillSimplexError(); } } // Set the Coordinate Reference to the Peer host.setPositionReference(bestSolution); return bestSolution; }
From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java
public void generateFOVs() { if (autoGenerateFOVsCheck.isSelected()) { ArrayList<FOV> fovs = new ArrayList<FOV>(); ArrayList<FOV> preexisting = new ArrayList<FOV>(tableModel_.getData()); tableModel_.clearAllData();/*from w w w .j a v a2s.com*/ for (int cols = 0; cols < pp_.getPlateColumns(); cols++) { ArrayList<Boolean> temp = pmdp_.wellsSelected_.get(cols); for (int rows = 0; rows < pp_.getPlateRows(); rows++) { if (temp.get(rows)) { String wellString = Character.toString((char) (65 + rows)) + Integer.toString(cols + 1); if (FOVPatternCombo.getSelectedIndex() == 0) { // spiral pattern fovs = generateSpiral(Integer.parseInt(noFOVsField.getText()), wellString); } else { fovs = generateRing(Integer.parseInt(noFOVsField.getText()), wellString); } for (FOV fov : fovs) { if (preexisting.contains(fov)) { // int ind = preexisting.indexOf(fov); fov.setGroup(preexisting.get(preexisting.indexOf(fov)).getGroup()); } else { fov.setGroup(groupDescField.getText()); } tableModel_.addRow(fov); // xyzmi_.fovXYtoStageXY(fov); } doZStackGeneration(getZStackParams()); // tableModel_.addRow(new FOV(wellString, pp_, 0)); } } } } }
From source file:output.ExcelM3Upgrad.java
private void writeMigration() { Sheet sheet = workbook.getSheetAt(0); workbook.setSheetName(0, "Migration"); sheet.setDisplayGridlines(false);//www .j ava 2 s . c o m sheet.setPrintGridlines(false); sheet.setFitToPage(true); sheet.setHorizontallyCenter(true); PrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(true); styles = createStyles(workbook); int rownum = beginROW; int cellnum = beginCOL; Row row = sheet.createRow(rownum++); for (int k = 0; k < model.getListColumn().length; k++) { Cell cell = row.createCell(cellnum++); cell.setCellValue(i18n.Language.getLabel(model.getListColumn()[k].getIdLng())); cell.setCellStyle(styles.get("header")); sheet.setColumnHidden(cell.getColumnIndex(), model.getListColumn()[k].isHidden()); sheet.autoSizeColumn(k); dialStatus(); } ArrayList<Integer> listHeader = new ArrayList<>(); for (int i = 0; i < M3UpdObjModel.header.length; i++) { listHeader.add(M3UpdObjModel.header[i]); } String[] listLevel = i18n.Language.traduce(Ressource.listLevel) .toArray(new String[Ressource.listLevel.length]); data = model.getData(); for (int i = 0; i < data.length; i++) { busyDial.setText("Alimentation de la ligne " + (i + 1) + " sur " + data.length); row = sheet.createRow(rownum++); Object[] objArr = data[i]; cellnum = beginCOL; boolean first = true; int j = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof Date) { cell.setCellValue((Date) obj); } else if (obj instanceof Boolean) { if (first) { first = false; if ((Boolean) obj) { cell.setCellValue("Oui"); } else { cell.setCellValue("Non"); } } else { if ((Boolean) obj) { cell.setCellValue("OK"); } else { cell.setCellValue("KO"); } } } else if (obj instanceof String) { cell.setCellValue((String) obj); } else if (obj instanceof Double) { cell.setCellValue((Double) obj); } if (listHeader.indexOf(218) == j) { try { int n = Integer.parseInt(obj.toString().trim()); if (n == -1) { cell.setCellValue("ERROR"); } else { cell.setCellValue(listLevel[n]); } } catch (NumberFormatException ex) { cell.setCellValue(""); } } if (j < objArr.length - 3) { cell.setCellStyle(styles.get("cell_b_centered_locked")); } else { cell.setCellStyle(styles.get("cell_b_centered")); } j++; dialStatus(); } dialStatus(); } dialStatus(); busyDial.setText("Formatage du document"); CellRangeAddressList userList = new CellRangeAddressList(beginROW + 1, beginROW + data.length, beginCOL + data[0].length - 1, beginCOL + data[0].length - 1); DataValidationConstraint userConstraint; DataValidation userValidation; if (type == 0) { userConstraint = DVConstraint.createExplicitListConstraint((String[]) model.getM3UserModel() .getListUserSelect().toArray(new String[model.getM3UserModel().getListUserSelect().size()])); userValidation = new HSSFDataValidation(userList, userConstraint); } else { XSSFDataValidationHelper userHelper = new XSSFDataValidationHelper((XSSFSheet) sheet); userConstraint = (XSSFDataValidationConstraint) userHelper .createExplicitListConstraint((String[]) model.getM3UserModel().getListUserSelect() .toArray(new String[model.getM3UserModel().getListUserSelect().size()])); userValidation = (XSSFDataValidation) userHelper.createValidation(userConstraint, userList); } sheet.addValidationData(userValidation); CellRangeAddressList migList = new CellRangeAddressList(beginROW + 1, beginROW + data.length, beginCOL + data[0].length - 2, beginCOL + data[0].length - 2); DataValidationConstraint migConstraint; DataValidation migValidation; if (type == 0) { migConstraint = DVConstraint.createExplicitListConstraint(new String[] { "OK", "KO" }); migValidation = new HSSFDataValidation(migList, migConstraint); } else { XSSFDataValidationHelper migHelper = new XSSFDataValidationHelper((XSSFSheet) sheet); migConstraint = (XSSFDataValidationConstraint) migHelper .createExplicitListConstraint(new String[] { "OK", "KO" }); migValidation = (XSSFDataValidation) migHelper.createValidation(migConstraint, migList); } sheet.addValidationData(migValidation); CellRangeAddressList levelList = new CellRangeAddressList(beginROW + 1, beginROW + data.length, beginCOL + data[0].length - 3, beginCOL + data[0].length - 3); DataValidationConstraint levelConstraint; DataValidation levelValidation; ArrayList<String> listNameLevel = new ArrayList<>(); listNameLevel.add("ERROR"); listNameLevel.addAll(i18n.Language.traduce(Ressource.listLevel));//.toArray(new String[Ressource.listLevel.length]) if (type == 0) { levelConstraint = DVConstraint .createExplicitListConstraint(listNameLevel.toArray(new String[listNameLevel.size()])); levelValidation = new HSSFDataValidation(levelList, levelConstraint); } else { XSSFDataValidationHelper levelHelper = new XSSFDataValidationHelper((XSSFSheet) sheet); levelConstraint = (XSSFDataValidationConstraint) levelHelper.createExplicitListConstraint( i18n.Language.traduce(Ressource.listLevel).toArray(new String[Ressource.listLevel.length])); levelValidation = (XSSFDataValidation) levelHelper.createValidation(levelConstraint, levelList); } sheet.addValidationData(levelValidation); int irow = beginROW; int icol = beginCOL + model.getListColumn().length + 2; row = sheet.getRow(irow); Cell cell = row.createCell(icol); sheet.addMergedRegion(new CellRangeAddress(irow, irow, icol, icol + 1)); cell.setCellValue("Estimation de la charge"); cell.setCellStyle(styles.get("header")); irow++; row = sheet.getRow(irow); int cpt = 0; ArrayList<String> listStringLevel = i18n.Language.traduce(Ressource.listLevel); for (String s : listStringLevel) { cell = row.createCell(icol); cell.setCellValue(s); cell.setCellStyle(styles.get("cell_b_centered_locked")); cell = row.createCell(icol + 1); cell.setCellType(HSSFCell.CELL_TYPE_FORMULA); String columnLetter = CellReference.convertNumToColString(listHeader.indexOf(218) + beginCOL); cell.setCellFormula( "COUNTIF(" + workbook.getSheetName(0) + "!" + columnLetter + (beginROW + 2) + ":" + columnLetter + (beginROW + data.length + 1) + ",\"" + s + "\")*" + Ressource.listWeightLevel[cpt]); cell.setCellStyle(styles.get("cell_b_centered_locked")); irow++; row = sheet.getRow(irow); cpt++; } row = sheet.getRow(irow); cell = row.createCell(icol); cell.setCellValue("Total des charges"); cell.setCellStyle(styles.get("cell_b_centered_locked")); cell = row.createCell(icol + 1); cell.setCellType(HSSFCell.CELL_TYPE_FORMULA); String columnLetter = CellReference.convertNumToColString(listHeader.indexOf(icol + 1)); cell.setCellFormula("SUM(" + workbook.getSheetName(0) + "!" + columnLetter + (beginROW + 2) + ":" + columnLetter + (beginROW + Ressource.listLevel.length + 1) + ")"); cell.setCellStyle(styles.get("cell_b_centered_locked")); for (int k = 0; k < model.getListColumn().length + 3; k++) { sheet.autoSizeColumn(k); } sheet.protectSheet("3kles2014"); }
From source file:com.krawler.esp.servlets.AdminServlet.java
public static String makeNickName(Connection conn, String name, int flag) throws ServiceException { String nickName = name.toLowerCase().trim().replaceAll("\\s+", "-").replaceAll("[^\\w|\\-]", ""); String sql = "select nickName from " + (flag == 1 ? "project" : "community") + " where nickName like ?"; DbResults rs = DbUtil.executeQuery(conn, sql, nickName + "%"); java.util.ArrayList<String> namesArray = new java.util.ArrayList<String>(); while (rs.next()) { namesArray.add(rs.getString(1)); }/*from w w w . j a v a 2 s. com*/ int i = 0; while (namesArray.indexOf(nickName) != -1) { namesArray.remove(nickName); i++; nickName = nickName + i; } return nickName; }
From source file:com.geotrackin.gpslogger.GpsMainActivity.java
private void ShowFileListDialog(final Intent settingsIntent, final IFileSender sender) { final File gpxFolder = new File(AppSettings.getGpsLoggerFolder()); if (gpxFolder != null && gpxFolder.exists()) { File[] enumeratedFiles = Utilities.GetFilesInFolder(gpxFolder, sender); //Order by last modified Arrays.sort(enumeratedFiles, new Comparator<File>() { public int compare(File f1, File f2) { if (f1 != null && f2 != null) { return -1 * Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); }/*from w ww. jav a2 s. c o m*/ return -1; } }); List<String> fileList = new ArrayList<String>(enumeratedFiles.length); for (File f : enumeratedFiles) { fileList.add(f.getName()); } final String settingsText = getString(R.string.menu_settings); //Add 'settings' to top of list fileList.add(0, settingsText); final String[] files = fileList.toArray(new String[fileList.size()]); final ArrayList selectedItems = new ArrayList(); // Where we track the selected items AlertDialog.Builder builder = new AlertDialog.Builder(this); // Set the dialog title builder.setTitle(R.string.osm_pick_file) // Specify the list array, the items to be selected by default (null for none), // and the listener through which to receive callbacks when items are selected .setMultiChoiceItems(files, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { if (which == 0) { //Unselect all others ((AlertDialog) dialog).getListView().clearChoices(); ((AlertDialog) dialog).getListView().setItemChecked(which, isChecked); selectedItems.clear(); } else { //Unselect the settings item ((AlertDialog) dialog).getListView().setItemChecked(0, false); if (selectedItems.contains(0)) { selectedItems.remove(selectedItems.indexOf(0)); } } selectedItems.add(which); } else if (selectedItems.contains(which)) { // Else, if the item is already in the array, remove it selectedItems.remove(Integer.valueOf(which)); } } }) // Set the action buttons .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (selectedItems.size() > 0 && selectedItems.get(0).equals(0)) { startActivity(settingsIntent); } else { List<File> chosenFiles = new ArrayList<File>(); for (Object item : selectedItems) { tracer.info( "Selected file to upload- " + files[Integer.valueOf(item.toString())]); chosenFiles.add(new File(gpxFolder, files[Integer.valueOf(item.toString())])); } selectedItems.clear(); if (chosenFiles.size() > 0) { Utilities.ShowProgress(GpsMainActivity.this, getString(R.string.please_wait), getString(R.string.please_wait)); sender.UploadFile(chosenFiles); } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { selectedItems.clear(); } }); builder.create(); builder.show(); } else { Utilities.MsgBox(getString(R.string.sorry), getString(R.string.no_files_found), this); } }
From source file:org.seqdoop.hadoop_bam.TestVCFOutputFormat.java
@Test public void testVariantContextReadWrite() throws IOException, InterruptedException { // This is to check whether issue https://github.com/HadoopGenomics/Hadoop-BAM/issues/1 has been // resolved/*from w w w . ja v a 2 s. com*/ VariantContextBuilder vctx_builder = new VariantContextBuilder(); ArrayList<Allele> alleles = new ArrayList<Allele>(); alleles.add(Allele.create("C", false)); alleles.add(Allele.create("G", true)); vctx_builder.alleles(alleles); ArrayList<Genotype> genotypes = new ArrayList<Genotype>(); GenotypeBuilder builder = new GenotypeBuilder(); genotypes.add(builder.alleles(alleles.subList(0, 1)).name("NA00001").GQ(48).DP(1).make()); genotypes.add(builder.alleles(alleles.subList(0, 1)).name("NA00002").GQ(42).DP(2).make()); genotypes.add(builder.alleles(alleles.subList(0, 1)).name("NA00003").GQ(39).DP(3).make()); vctx_builder.genotypes(genotypes); HashSet<String> filters = new HashSet<String>(); vctx_builder.filters(filters); HashMap<String, Object> attributes = new HashMap<String, Object>(); attributes.put("NS", new Integer(4)); vctx_builder.attributes(attributes); vctx_builder.loc("20", 2, 2); vctx_builder.log10PError(-8.0); VariantContext ctx = vctx_builder.make(); VariantContextWithHeader ctxh = new VariantContextWithHeader(ctx, readHeader()); writable.set(ctxh); DataOutputBuffer out = new DataOutputBuffer(1000); writable.write(out); byte[] data = out.getData(); ByteArrayInputStream bis = new ByteArrayInputStream(data); writable = new VariantContextWritable(); writable.readFields(new DataInputStream(bis)); VariantContext vc = writable.get(); Assert.assertArrayEquals("comparing Alleles", ctx.getAlleles().toArray(), vc.getAlleles().toArray()); Assert.assertEquals("comparing Log10PError", ctx.getLog10PError(), vc.getLog10PError(), 0.01); Assert.assertArrayEquals("comparing Filters", ctx.getFilters().toArray(), vc.getFilters().toArray()); Assert.assertEquals("comparing Attributes", ctx.getAttributes(), vc.getAttributes()); // Now check the genotypes. Note: we need to make the header accessible before decoding the genotypes. GenotypesContext gc = vc.getGenotypes(); assert (gc instanceof LazyVCFGenotypesContext); LazyVCFGenotypesContext.HeaderDataCache headerDataCache = new LazyVCFGenotypesContext.HeaderDataCache(); headerDataCache.setHeader(readHeader()); ((LazyVCFGenotypesContext) gc).getParser().setHeaderDataCache(headerDataCache); for (Genotype genotype : genotypes) { Assert.assertEquals("checking genotype name", genotype.getSampleName(), gc.get(genotypes.indexOf(genotype)).getSampleName()); Assert.assertEquals("checking genotype quality", genotype.getGQ(), gc.get(genotypes.indexOf(genotype)).getGQ()); Assert.assertEquals("checking genotype read depth", genotype.getDP(), gc.get(genotypes.indexOf(genotype)).getDP()); } }
From source file:pcgui.SetupParametersPanel.java
private void runModel() { //retrieve master configuration ArrayList<ArrayList<Object>> mod = model.getData(); //create a new list and check for dependencies ArrayList<Symbol> list = new ArrayList<Symbol>(); //independent variable list ArrayList<Symbol> ivList = new ArrayList<Symbol>(); //step variable list ArrayList<Symbol> stepList = new ArrayList<Symbol>(); //dependent list ArrayList<Symbol> depList = new ArrayList<Symbol>(); //output tracking ArrayList<Symbol> trackedSymbols = new ArrayList<Symbol>(); Symbol tempSym = null;/*from w w w .j a va 2 s . com*/ //step variable counter to be used for making combinations int stepVarCount = 0; long stepCombinations = 1; TextParser textParser = new TextParser(); compileSuccess = true; for (ArrayList<Object> rowData : mod) { tempSym = paramList.get(mod.indexOf(rowData)); if ("Manual".equals((String) rowData.get(2))) { System.out.println("Found Customized Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(3) + ": type=" + rowData.get(3).getClass()); tempSym.mode = "Manual"; String data = (String) rowData.get(3); //checking dependent variables if (data != null && !data.isEmpty()) { //dependent if (hashTable.containsKey(data)) { tempSym.setDependent(true); depList.add(tempSym); } else { //independents tempSym.setDependent(false); tempSym.set(data); ivList.add(tempSym); } } } else if ("External".equals((String) rowData.get(2))) { System.out.println("Found External Symbol : " + rowData.get(0)); System.out.println("External : " + rowData.get(3) + ": type=" + rowData.get(3).getClass()); if (!(((String) rowData.get(4)).isEmpty())) { tempSym.externalFile = (String) rowData.get(4); tempSym.set(tempSym.externalFile); tempSym.mode = "External"; if (tempSym.externalFile.endsWith(".xls") || tempSym.externalFile.endsWith(".xlsx")) { if (tempSym.excelFileRange.isEmpty()) { // TODO show an error dialog System.err.println("Error user missed excel range arguments"); JOptionPane.showMessageDialog(new JFrame(), "Error user missed excel range arguments"); return; } else { tempSym.excelFileRange = (String) rowData.get(5); //'[Daten_10$B'+(i)+':B'+(5+n)+']' //user has to add quote before the 1st + and after the last + //the data file used should be inside Models/Data folder tempSym.set("Models//Data//" + tempSym.externalFile + "::" + tempSym.excelFileRange); } } else { //for non excel files tempSym.set("Models//Data//" + tempSym.externalFile); } } else { System.err.println("Error user missed excel file"); JOptionPane.showMessageDialog(new JFrame(), "Please enter external file for variable : " + tempSym.name); return; } ivList.add(tempSym); list.add(tempSym); } else if ("Randomized".equals((String) rowData.get(2))) { System.out.println("Found Randomized Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(6)); boolean isValid = textParser.validate((String) rowData.get(6)); if (isValid) { //saving the array declaration parameters if (((String) rowData.get(1)).trim().startsWith("array")) { System.out.println("Found randomized array : " + tempSym.name); //found an array tempSym.isArray = true; List<String> arrayParams = parseArrayParam((String) rowData.get(1)); tempSym.arrayParams = arrayParams; System.out.println("Param list : "); for (Object obj : tempSym.arrayParams) { //check if any of the param is symbol if (hashTable.containsKey((String) obj)) { tempSym.isDependentDimension = true; depList.add(tempSym); break; } System.out.println((String) obj); } //add to independent variable list if none of the dimension is based on variable if (!tempSym.isDependentDimension) { ivList.add(tempSym); } } Distribution dist = textParser.getDistribution((String) rowData.get(6)); if ("Step".equalsIgnoreCase(dist.getDistribution())) { System.err.println("Error: User entered step distribution in Randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } tempSym.setDistribution(dist); tempSym.mode = "Randomized"; //check dependent variables List<String> distParamList = dist.getParamList(); for (String param : distParamList) { //TODO: if .contains work on Symbol if (hashTable.containsKey(param) && !depList.contains(tempSym)) { tempSym.setDependent(true); depList.add(tempSym); break; } } //generate apache distribution object for independent vars if (!tempSym.isDependent()) { Object apacheDist = generateDistribution(tempSym); tempSym.setApacheDist(apacheDist); if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) { stepVarCount++; StepDistribution stepDist = (StepDistribution) apacheDist; stepCombinations *= stepDist.getStepCount(); tempSym.isStepDist = true; tempSym.setStepDist(stepDist); stepList.add(tempSym); } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) { ivList.add(tempSym); } } list.add(tempSym); } else { System.err.println("Error: User entered unknown distribution for randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } } else if ("Step".equals((String) rowData.get(2))) { System.out.println("Found Step Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(6)); Distribution dist = textParser.getStepDistribution((String) rowData.get(6)); if (dist == null || !"Step".equalsIgnoreCase(dist.getDistribution())) { System.err.println("Error: User entered unknown distribution for step variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } boolean isValid = textParser.validateStepDist((String) rowData.get(6)); if (isValid) { //saving the array declaration parameters if (((String) rowData.get(1)).trim().startsWith("array")) { //TODO: if this can work for step arrays System.out.println("Found step array : " + tempSym.name); //found an array tempSym.isArray = true; List<String> arrayParams = parseArrayParam((String) rowData.get(1)); tempSym.arrayParams = arrayParams; System.out.println("Param list : "); for (Object obj : tempSym.arrayParams) { //check if any of the param is symbol if (hashTable.containsKey((String) obj)) { tempSym.isDependentDimension = true; depList.add(tempSym); break; } System.out.println((String) obj); } //add to independent variable list if none of the dimension is based on variable if (!tempSym.isDependentDimension) { ivList.add(tempSym); } } tempSym.setDistribution(dist); tempSym.mode = "Randomized"; //check dependent variables List<String> distParamList = dist.getParamList(); for (String param : distParamList) { if (hashTable.containsKey(param) && !depList.contains(tempSym)) { tempSym.setDependent(true); depList.add(tempSym); break; } } //generate apache distribution object for independent vars if (!tempSym.isDependent()) { Object apacheDist = generateDistribution(tempSym); tempSym.setApacheDist(apacheDist); //dual safe check if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) { stepVarCount++; StepDistribution stepDist = (StepDistribution) apacheDist; stepCombinations *= stepDist.getStepCount(); tempSym.isStepDist = true; tempSym.setStepDist(stepDist); stepList.add(tempSym); } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) { ivList.add(tempSym); } } list.add(tempSym); } else { System.err.println("Error: User entered unknown distribution for randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } } //add symbol to trackedSymbol list for output tracking if (tempSym != null && rowData.get(7) != null && (boolean) rowData.get(7)) { trackedSymbols.add(tempSym); } } System.out.println("Total step distribution variables =" + stepVarCount); System.out.println("Total step combinations =" + stepCombinations); System.out.println("====STEP VARIABLES===="); for (Symbol sym : stepList) { System.out.println(sym.name); } //resolve dependencies and generate random distributions object //list for an instance of execution HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < stepList.size(); i++) { map.put(stepList.get(i).name, getSteppingCount(stepList, i)); System.out.println(stepList.get(i).name + " has stepping count =" + map.get(stepList.get(i).name)); } int repeatitions = 0; try { repeatitions = Integer.parseInt(repeatCount.getText()); } catch (NumberFormatException e) { System.err.println("Invalid repeat count"); JOptionPane.showMessageDialog(new JFrame(), "Please enter integer value for repeat count"); return; } //generate instances showProgressBar(); final long totalIterations = repeatitions * stepCombinations; final long repeatitionsFinal = repeatitions; final long combinations = stepCombinations; SwingWorker<Void, Void> executionTask = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { long itNum = 1; int itCount = 1; System.out.println("Total iterations: " + totalIterations); // TODO Auto-generated method stub for (int c = 1; c <= repeatitionsFinal; c++) { for (int i = 1; i <= combinations; i++) { setProgress((int) (itNum * 100 / totalIterations)); //step variables first for (Symbol sym : stepList) { if (map.get(sym.name) == 1 || i % map.get(sym.name) - 1 == 0 || i == 1) { sym.set(sym.getStepDist().sample()); hashTable.put(sym.name, sym); } //System.out.println(sym.name+" = "+sym.get()); } //independent randomized variables for (Symbol sym : ivList) { if (sym.mode.equals("Randomized")) { Object distObj = sym.getApacheDist(); switch (sym.getApacheDist().getClass().getSimpleName()) { case "UniformIntegerDistribution": //case "GeometricDistribution" : // case "BinomialDistribution"://not implemented yet IntegerDistribution intDist = (IntegerDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateIndependentArray(sym, intDist); sym.set(val); hashTable.put(sym.name, sym); } break; case "LogisticDistribution": case "UniformRealDistribution": case "ExponentialDistribution": case "GammaDistribution": case "NormalDistribution": RealDistribution realDist = (RealDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateIndependentArray(sym, realDist); sym.set(val); hashTable.put(sym.name, sym); } break; default: System.err.println("Unknown distribution"); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : Unknown distribution"); return null; } } //System.out.println(sym.name+" = "+sym.get()); //other types of independent variable already have values } for (Symbol sym : depList) { if (sym.mode != null && "Manual".equals(sym.mode)) { //value depends on some other value String ref = (String) sym.get(); Object val = (Object) hashTable.get(ref); sym.set(val); hashTable.put(sym.name, sym); } else if (sym.mode != null && "Randomized".equals(sym.mode)) { Object distObj = null; //when a random distribution depends on another variable Distribution dist = sym.getDistribution(); StringBuilder sb = new StringBuilder(); sb.append(dist.getDistribution()); sb.append("("); for (String s : dist.getParamList()) { //replacing a dependency by actual value of that variable if (hashTable.containsKey(s)) { Symbol val = (Symbol) hashTable.get(s); sb.append((String) val.get()); } else { //this param is a number itself sb.append(s); } sb.append(","); } //check if param list length = 0 if (dist.getParamList() != null && dist.getParamList().size() >= 1) { sb.deleteCharAt(sb.length() - 1); } sb.append(")"); if (sym.typeString != null && sym.typeString.contains("integer")) { try { distObj = textParser.parseText(sb.toString(), TextParser.INTEGER); sym.setApacheDist(distObj); } catch (Exception e) { System.err.println( "Exception occured when trying to get Random distribution for variable" + sym.name + "\n" + e.getMessage()); e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); return null; } } else { try { distObj = textParser.parseText(sb.toString(), TextParser.REAL); sym.setApacheDist(distObj); } catch (Exception e) { System.err.println( "Exception occured when trying to get Random distribution for variable" + sym.name + "\n" + e.getMessage()); e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); return null; } } //generation of actual apache distribution objects switch (distObj.getClass().getSimpleName()) { case "UniformIntegerDistribution": //case "GeometricDistribution" : //case "BinomialDistribution": IntegerDistribution intDist = (IntegerDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateDependentArray(sym, intDist); sym.set(val); hashTable.put(sym.name, sym); } break; case "LogisticDistribution": case "UniformRealDistribution": case "ExponentialDistribution": case "GammaDistribution": case "NormalDistribution": RealDistribution realDist = (RealDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateDependentArray(sym, realDist); sym.set(val); hashTable.put(sym.name, sym); } break; default: System.err.println("Unknown distribution"); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : Unknown distribution"); } } //System.out.println(sym.name+" = "+sym.get()); } ArrayList<Symbol> instanceList = new ArrayList<Symbol>(); instanceList.addAll(stepList); instanceList.addAll(ivList); instanceList.addAll(depList); System.out.println("=======ITERATION " + itCount++ + "======="); System.out.println("=======instanceList.size =" + instanceList.size() + " ======="); for (Symbol sym : instanceList) { System.out.println(sym.name + " = " + sym.get()); } //runModel here try { //TODO anshul: pass output variables to be written to excel System.out.println("Tracked output symbols"); for (Symbol sym : trackedSymbols) { System.out.println(sym.name); } HashMap<String, OutputParams> l = parser.changeModel(instanceList, trackedSymbols, itNum); if (l == null) { compileSuccess = false; break; } } catch (/*XPRMCompileException | */XPRMLicenseError | IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); compileSuccess = false; break; } itNum++; } } this.notifyAll(); done(); return null; } @Override protected void done() { super.done(); //check if compilation was successful if (compileSuccess) { ModelSaver.saveModelResult(); visPanel.setTrackedVariables(trackedSymbols); mapVisPanel.setTrackedVariables(trackedSymbols); JOptionPane.showMessageDialog(new JFrame("Success"), "Model execution completed.\nOutput written to excel file : " + outputFile); } else { //Error popup should have been shown by ModelParser System.err.println("There was an error while running the model."); return; } if (progressFrame != null) { progressFrame.dispose(); } } }; executionTask.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); if (pbar != null) pbar.setValue(progress); if (taskOutput != null) taskOutput.append(String.format("Completed %d%% of task.\n", executionTask.getProgress())); } } }); executionTask.execute(); }
From source file:nl.mpcjanssen.simpletask.Simpletask.java
private void updateTags(@NotNull final List<Task> checkedTasks) { final ArrayList<String> projects = new ArrayList<String>(); Set<String> selectedProjects = new HashSet<String>(); final TaskCache taskbag = getTaskBag(); projects.addAll(Util.sortWithPrefix(taskbag.getProjects(), m_app.sortCaseSensitive(), null)); for (Task t : checkedTasks) { selectedProjects.addAll(t.getTags()); }//from ww w.j a v a2 s.com @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.tag_dialog, null, false); final ListView lv = (ListView) view.findViewById(R.id.listView); lv.setAdapter(new ArrayAdapter<String>(this, R.layout.simple_list_item_multiple_choice, projects.toArray(new String[projects.size()]))); lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); for (String context : selectedProjects) { int position = projects.indexOf(context); if (position != -1) { lv.setItemChecked(position, true); } } final EditText ed = (EditText) view.findViewById(R.id.editText); m_app.setEditTextHint(ed, R.string.new_tag_name); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ArrayList<String> items = new ArrayList<String>(); ArrayList<String> originalLines = new ArrayList<String>(); originalLines.addAll(Util.tasksToString(checkedTasks)); ArrayList<String> uncheckedItems = new ArrayList<String>(); uncheckedItems.addAll(Util.getCheckedItems(lv, false)); items.addAll(Util.getCheckedItems(lv, true)); String newText = ed.getText().toString(); if (!newText.equals("")) { items.add(ed.getText().toString()); } for (String item : items) { for (Task t : checkedTasks) { t.addTag(item); } } for (String item : uncheckedItems) { for (Task t : checkedTasks) { t.removeTag("+" + item); } } finishActionmode(); m_app.getTaskCache(null).modify(originalLines, checkedTasks, null, null); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Create the AlertDialog AlertDialog dialog = builder.create(); dialog.setTitle(R.string.update_tags); dialog.show(); }