List of usage examples for java.util ArrayList set
public E set(int index, E element)
From source file:net.sf.jclal.experiment.ExperimentBuilder.java
/** * Expands the experiments for the configuration file * * @param experimentFileName The name of the experiment file. * @return The experiments for the configuration file. *///ww w . j a v a2 s. c o m public ArrayList<String> buildExperiment(String experimentFileName) { ArrayList<String> configurations = expandElements(experimentFileName); ArrayList<String> allCreatedExperiments = new ArrayList<String>(); int numberExperiments = 1; allCreatedExperiments.addAll(configurations); /** * Expand multi-valued elements */ do { numberExperiments = configurations.size(); ArrayList<String> createdExperiments = new ArrayList<String>(); for (String experiment : configurations) { createdExperiments.addAll(expandElements(experiment)); } allCreatedExperiments.addAll(createdExperiments); configurations = createdExperiments; } while (configurations.size() != numberExperiments); /** * Expand multi-valued attributes */ do { numberExperiments = configurations.size(); ArrayList<String> createdExperiments = new ArrayList<String>(); for (String experiment : configurations) { createdExperiments.addAll(expandAttributes(experiment)); } allCreatedExperiments.addAll(createdExperiments); configurations = createdExperiments; } while (configurations.size() != numberExperiments); allCreatedExperiments.removeAll(configurations); /** * Remove temp files */ for (String temp : allCreatedExperiments) { if (!temp.equals(experimentFileName)) { new File(temp).delete(); } } /** * Move the expanded configuration files to the experiments folder */ if (configurations.size() > 1) { File dir = new File("experiments"); /** * If the directory exists, delete all files */ if (dir.exists()) { File[] experimentFiles = dir.listFiles(); for (File f : experimentFiles) { f.delete(); } } /** * Else, create the directory */ else { dir.mkdir(); } for (int i = 0; i < configurations.size(); i++) { File file = new File(configurations.get(i)); file.renameTo(new File(dir, file.getName())); String[] files = configurations.get(i).split("/"); String fileName = files[files.length - 1]; configurations.set(i, dir.getPath() + "/" + fileName); } } /** * Return the configuration filenames */ return configurations; }
From source file:dashboard.VersionCheck.java
public int importVersionCheckLog(int n, String apiuser, String apipass, String IPfile, String ERRfile, String versionCheckURL, String versionCheckPass, String API_KEY, String TOKEN, String startTime) throws Exception { int lines = 0; String ip = ""; String registrant = ""; Mixpanel mix = new Mixpanel(); String build = ""; String eventTime = "5/22/13 0:01 AM"; int x = 0;//from www . jav a2s. c o m int mixpanelStatus = 0; int errors = 0; String prevIP = ""; int index = 0; Registrant r; ArrayList<Registrant> rList = new ArrayList<Registrant>(); ArrayList<Registrant> eList = new ArrayList<Registrant>(); IPList ipl = new IPList(); IPList errl = new IPList(); Whois w = new Whois(apiuser, apipass); SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yy h:mm a"); long event = 0; long from = sdf.parse(startTime).getTime(); int nn = 1; System.out.println(">>> Version Check log - " + versionCheckURL); URL logURL = new URL(versionCheckURL); String base64EncodedString = Base64.encodeBase64String(StringUtils.getBytesUtf8(versionCheckPass)); URLConnection conn = logURL.openConnection(); conn.setRequestProperty("Authorization", "Basic " + base64EncodedString); InputStream in = conn.getInputStream(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(in)); String inputLine = br.readLine(); // Skip first line (headers) if (inputLine != null) inputLine = br.readLine(); // Load list of IP - REGISTRANT ipl.loadList(rList, IPfile); ipl.printList(rList, 5); // Loop - limited to n cycles (parameter defined by user) while (inputLine != null & lines < n) { String[] dataArray = inputLine.split(","); x = 0; for (String ttt : dataArray) x++; if (x == 3) { ip = dataArray[0]; build = dataArray[1]; eventTime = dataArray[2]; } else if (x == 4) { // Line format is corrupted (2 ip's) errors++; ip = dataArray[1]; build = dataArray[2]; eventTime = dataArray[3]; } event = sdf.parse(eventTime).getTime(); if (event < from) { nn++; //System.out.print(nn + ", "); inputLine = br.readLine(); // Read next line of data. continue; } if (lines == 0) { System.out.println("------ Skipped " + nn + " events --------"); System.out.println(); } if (ip != prevIP) { prevIP = ip; index = ipl.ipInList(ip, rList); if (index >= 0) { r = rList.get(index); registrant = r.name; // Update counter for this IP r.counter = r.counter + 1; rList.set(index, r); } else { // WHOIS - Check registrant of this IP address registrant = w.whoisIP(ip); // if there was an error, try again if (registrant.equals("ERROR")) registrant = w.whoisIP(ip); // if there was a second error, add it to errors list if (registrant.equals("ERROR")) { eList.add(new Registrant(ip, registrant, 1)); } else { // If name includes a comma, exclude the comma registrant = registrant.replace(",", ""); rList.add(new Registrant(ip, registrant, 1)); } } } inputLine = br.readLine(); // Read next line of data. lines++; System.out.println(">> " + lines + " - " + eventTime + " " + ip + " - " + registrant); // Track the event in Mixpanel (using the POST import) - event time is in the PAST mix.postVersionCheckToMixpanel(API_KEY, TOKEN, ip, registrant, "Version Check", eventTime, build); } // while } catch (IOException e) { e.printStackTrace(); } finally { // Close the file once all data has been read. if (br != null) br.close(); ipl.printList(rList, 5); ipl.saveList(rList, IPfile); if (!eList.isEmpty()) { sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm"); String fName = ERRfile + sdf.format(new Date()) + ".txt"; System.out.println("\n>>> " + eList.size() + " DomainTools errors:"); errl.saveList(eList, fName); } else System.out.println("\n>>> No DomainTools errors"); return lines; } }
From source file:de.unijena.bioinf.FragmentationTreeConstruction.computation.FragmentationPatternAnalysis.java
/** * Step 7: Peak Scoring//from w w w . j a v a 2 s.co m * Scores each peak. Expects a decomposition list */ public ProcessedInput performPeakScoring(ProcessedInput input) { final List<ProcessedPeak> processedPeaks = input.getMergedPeaks(); final ProcessedPeak parentPeak = input.getParentPeak(); final int n = processedPeaks.size(); input.getOrCreateAnnotation(Scoring.class).initializeScoring(n); // score peak pairs final double[][] peakPairScores = input.getAnnotationOrThrow(Scoring.class).getPeakPairScores(); for (PeakPairScorer scorer : peakPairScorers) { scorer.score(processedPeaks, input, peakPairScores); } // score fragment peaks final double[] peakScores = input.getAnnotationOrThrow(Scoring.class).getPeakScores(); for (PeakScorer scorer : fragmentPeakScorers) { scorer.score(processedPeaks, input, peakScores); } final PeakAnnotation<DecompositionList> decomp = input.getPeakAnnotationOrThrow(DecompositionList.class); // dont score parent peak peakScores[peakScores.length - 1] = 0d; // score peaks { final ArrayList<Object> preparations = new ArrayList<Object>(decompositionScorers.size()); for (DecompositionScorer<?> scorer : decompositionScorers) preparations.add(scorer.prepare(input)); for (int i = 0; i < processedPeaks.size() - 1; ++i) { final DecompositionList decomps = decomp.get(processedPeaks.get(i)); final ArrayList<ScoredMolecularFormula> scored = new ArrayList<ScoredMolecularFormula>( decomps.getDecompositions().size()); for (MolecularFormula f : decomps.getFormulas()) { double score = 0d; int k = 0; for (DecompositionScorer<?> scorer : decompositionScorers) { score += ((DecompositionScorer<Object>) scorer).score(f, processedPeaks.get(i), input, preparations.get(k++)); } scored.add(new ScoredMolecularFormula(f, score)); } decomp.set(processedPeaks.get(i), new DecompositionList(scored)); } } // same with root { final ArrayList<Object> preparations = new ArrayList<Object>(rootScorers.size()); for (DecompositionScorer<?> scorer : rootScorers) preparations.add(scorer.prepare(input)); final ArrayList<ScoredMolecularFormula> scored = new ArrayList<ScoredMolecularFormula>( decomp.get(parentPeak).getDecompositions()); for (int j = 0; j < scored.size(); ++j) { double score = 0d; int k = 0; final MolecularFormula f = scored.get(j).getFormula(); for (DecompositionScorer<?> scorer : rootScorers) { score += ((DecompositionScorer<Object>) scorer).score(f, input.getParentPeak(), input, preparations.get(k++)); } scored.set(j, new ScoredMolecularFormula(f, score)); } Collections.sort(scored, Collections.reverseOrder()); decomp.set(parentPeak, new DecompositionList(scored)); input.addAnnotation(DecompositionList.class, decomp.get(parentPeak)); } // set peak indizes for (int i = 0; i < processedPeaks.size(); ++i) processedPeaks.get(i).setIndex(i); return input; }
From source file:org.sakaiproject.evaluation.tool.reporting.PDFReportExporter.java
private ArrayList<Double> getWeightedMeansBlocks(List<DataTemplateItem> dtis) { //20140226 - daniel.merino@unavarra.es - https://jira.sakaiproject.org/browse/EVALSYS-1100 ArrayList<Double> alTemporal = new ArrayList<>(); //List of means of each block. //Number of answers for the block we are working in //If is not the same for every block element, mean is invalidated. ArrayList<Integer> collectedValues = new ArrayList<>(); DataTemplateItem dti;//from w ww .j a v a 2 s . c o m EvalTemplateItem templateItem; EvalItem item; boolean processingBlock = false; int numberOfChildren = 0; List<String> optionLabels = null; //Answers of each item. for (int i = 0; i < dtis.size(); i++) { dti = dtis.get(i); templateItem = dti.templateItem; item = templateItem.getItem(); List<EvalAnswer> itemAnswers = dti.getAnswers(); String templateItemType = TemplateItemUtils.getTemplateItemType(templateItem); if ((processingBlock) && (numberOfChildren == 0)) { //A block is being processed and there are no more children, time to do the block weighted mean. double blockWeightedMean = calculateBlockWeightedMean(collectedValues, optionLabels); alTemporal.add(blockWeightedMean); //Reset. processingBlock = false; collectedValues = new ArrayList<>(); } if (EvalConstants.ITEM_TYPE_BLOCK_PARENT.equals(templateItemType)) { processingBlock = true; numberOfChildren = templateItem.childTemplateItems.size(); } else if (EvalConstants.ITEM_TYPE_HEADER.equals(templateItemType)) { } else if (EvalConstants.ITEM_TYPE_TEXT.equals(templateItemType)) { } else if (EvalConstants.ITEM_TYPE_MULTIPLEANSWER.equals(templateItemType) || EvalConstants.ITEM_TYPE_MULTIPLECHOICE.equals(templateItemType) || EvalConstants.ITEM_TYPE_SCALED.equals(templateItemType) || EvalConstants.ITEM_TYPE_BLOCK_CHILD.equals(templateItemType)) { if (processingBlock) { if (numberOfChildren > 0) numberOfChildren--; int[] responseArray = TemplateItemDataList.getAnswerChoicesCounts(templateItemType, item.getScale().getOptions().size(), itemAnswers); int temporal; optionLabels = item.getScale().getOptions(); try { for (int n = 0; n < optionLabels.size(); n++) { if (n >= collectedValues.size()) { collectedValues.add(responseArray[n]); } else { temporal = (collectedValues.get(n)); collectedValues.set(n, temporal + responseArray[n]); } } } catch (Exception e) { //This exception is raised if there is a non numerical answer among the available choices. //So mean is not valid for answers but for answer numbers. } } } else { LOG.warn("Trying to add unknown type to PDF: " + templateItemType); } } //Just in case the last element is a block. if ((processingBlock) && (numberOfChildren == 0)) { double blockWeightedMean = calculateBlockWeightedMean(collectedValues, optionLabels); alTemporal.add(blockWeightedMean); } return alTemporal; }
From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java
private StringBuffer readConfiguration() throws ConfigurationException { String wizardParam = null, templatesParam = null; Integer generationIndex = null, wizardIndex = null, templatesIndex = null; // Will change wizardParam value instead of appending it wizardParam = userConfig.getProperty(PARAM_WIZARD_DONE); // Will change templatesParam value instead of appending it templatesParam = userConfig.getProperty(PARAM_TEMPLATES_NAME); ArrayList<String> newLines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(nuxeoConf))) { String line;/* w w w .j a va 2s .c o m*/ MessageDigest digest = DigestUtils.getMd5Digest(); boolean onConfiguratorContent = false; while ((line = reader.readLine()) != null) { digest.update(line.getBytes()); if (!onConfiguratorContent) { if (!line.startsWith(BOUNDARY_BEGIN)) { if (line.startsWith(PARAM_FORCE_GENERATION)) { if (setOnceToFalse && onceGeneration) { line = PARAM_FORCE_GENERATION + "=false"; } if (setFalseToOnce && !forceGeneration) { line = PARAM_FORCE_GENERATION + "=once"; } if (generationIndex == null) { newLines.add(line); generationIndex = newLines.size() - 1; } else { newLines.set(generationIndex, line); } } else if (line.startsWith(PARAM_WIZARD_DONE)) { if (wizardParam != null) { line = PARAM_WIZARD_DONE + "=" + wizardParam; } if (wizardIndex == null) { newLines.add(line); wizardIndex = newLines.size() - 1; } else { newLines.set(wizardIndex, line); } } else if (line.startsWith(PARAM_TEMPLATES_NAME)) { if (templatesParam != null) { line = PARAM_TEMPLATES_NAME + "=" + templatesParam; } if (templatesIndex == null) { newLines.add(line); templatesIndex = newLines.size() - 1; } else { newLines.set(templatesIndex, line); } } else { int equalIdx = line.indexOf("="); if (equalIdx < 1 || line.trim().startsWith("#")) { newLines.add(line); } else { String key = line.substring(0, equalIdx).trim(); if (userConfig.getProperty(key) != null) { newLines.add(line); } else { newLines.add("#" + line); } } } } else { // What must be written just before the BOUNDARY_BEGIN if (templatesIndex == null && templatesParam != null) { newLines.add(PARAM_TEMPLATES_NAME + "=" + templatesParam); templatesIndex = newLines.size() - 1; } if (wizardIndex == null && wizardParam != null) { newLines.add(PARAM_WIZARD_DONE + "=" + wizardParam); wizardIndex = newLines.size() - 1; } onConfiguratorContent = true; } } else { if (!line.startsWith(BOUNDARY_END)) { int equalIdx = line.indexOf("="); if (line.startsWith("#" + PARAM_TEMPLATES_NAME) || line.startsWith(PARAM_TEMPLATES_NAME)) { // Backward compliance, it must be ignored continue; } if (equalIdx < 1) { // Ignore non-readable lines continue; } if (line.trim().startsWith("#")) { String key = line.substring(1, equalIdx).trim(); String value = line.substring(equalIdx + 1).trim(); getStoredConfig().setProperty(key, value); } else { String key = line.substring(0, equalIdx).trim(); String value = line.substring(equalIdx + 1).trim(); if (!value.equals(userConfig.getRawProperty(key))) { getStoredConfig().setProperty(key, value); } } } else { onConfiguratorContent = false; } } } reader.close(); currentConfigurationDigest = Hex.encodeHexString(digest.digest()); } catch (IOException e) { throw new ConfigurationException("Error reading " + nuxeoConf, e); } StringBuffer newContent = new StringBuffer(); for (int i = 0; i < newLines.size(); i++) { newContent.append(newLines.get(i).trim() + System.getProperty("line.separator")); } return newContent; }
From source file:org.eclipse.ice.item.utilities.moose.MOOSEFileHandler.java
/** * This operations loads a MOOSE GetPot file at the specified path and * returns a fully-configured set of ICE TreeComposites. * //w w w . j a v a2 s . c o m * @param filePath * The file path from which the MOOSE blocks written in GetPot * should be read. If the path is null or empty, the operation * returns without doing any work. * @return The MOOSE input file specification as read from the GetPot input * and stored in TreeComposites. Each TreeComposite contains both * parameters and exemplar children. Any parameters in a * TreeComposite are contained in a DataComponent. The id of the * data component is 1. */ public ArrayList<TreeComposite> loadFromGetPot(String filePath) { // Local Declarations ArrayList<TreeComposite> trees = new ArrayList<TreeComposite>(); byte[] fileByteArray = null; String mooseFileString = null, potLine = null; // Quit if the path is boned if (filePath == null || filePath.isEmpty()) { return null; } // Post some debug info if (debugFlag) { logger.info("MOOSEFileHandler Message: " + "Attempting to loading GetPot file " + filePath); } // Load the GetPot file try { RandomAccessFile mooseFile = new RandomAccessFile(filePath, "r"); // Put it into a byte array fileByteArray = new byte[(int) mooseFile.length()]; mooseFile.read(fileByteArray); // And then a string mooseFileString = new String(fileByteArray); // Close the file mooseFile.close(); // Post some more debug info if (debugFlag) { logger.info("MOOSEFileHandler Message: File loaded."); } } catch (IOException e) { // Complain if the file is not found System.err.println("MOOSEFileHandler Message: " + "Unable to load GetPot file!"); logger.error(getClass().getName() + " Exception!", e); } // Check the string before proceeding if (mooseFileString != null && !mooseFileString.isEmpty()) { // Create an array list from the string ArrayList<String> potLines = new ArrayList<String>(Arrays.asList(mooseFileString.split("\n"))); // Remove (non-parameter) commented lines and white space String trimmedPotLine = ""; for (int i = 0; i < potLines.size(); i++) { trimmedPotLine = potLines.get(i).trim(); if (trimmedPotLine.startsWith("#") && !trimmedPotLine.contains("=") && !trimmedPotLine.contains("[") && !trimmedPotLine.contains("]")) { // Lines that start with "#" but have no "=" are comments // that aren't parameters and should be removed potLines.remove(i); // Update "i" so that we read correctly --i; } else if (potLines.get(i).isEmpty()) { // Remove empty lines potLines.remove(i); // Update "i" so that we read correctly --i; } else { // This is a rare scenario to check for, but it's possible // (and has happened at least once) where a line is just a // comment (starts with "#") AND includes a "=" in the text // of the comment if (trimmedPotLine.startsWith("#") && trimmedPotLine.contains("=")) { String[] splitTrimmedPotLine = trimmedPotLine.split("\\s+"); if (splitTrimmedPotLine.length > 4) { // Skip this line, it's a comment that's been // mistaken as a parameter potLines.remove(i); --i; continue; } } // Otherwise, the normal behavior is that the line should be // trimmed and be considered a real parameter potLines.set(i, potLines.get(i).trim()); } } // Read all of the lines again, create blocks and load them. int counter = 0, endCounter = 1; while (counter < potLines.size()) { // Get the line and shift the counters potLine = potLines.get(counter); ++counter; // The start of a full block is a line with the name in brackets // and without the "./" sequence. if (potLine.contains("[") && potLine.contains("]")) { // Go to the next line potLine = potLines.get(endCounter); // Loop over the block and find the end while (!potLine.contains("[]")) { // Update the line and the counter potLine = potLines.get(endCounter); ++endCounter; } // Create a new block Block block = new Block(); ArrayList<String> blockLines = null; if (endCounter >= counter - 1) { blockLines = new ArrayList<String>(potLines.subList(counter - 1, endCounter)); } if (blockLines != null && !blockLines.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(blockLines.get(0)); blockLines.set(0, stringBuilder.toString()); block.fromGetPot(blockLines); // Add the block to the list trees.add(block.toTreeComposite()); // Update the counter to point to the last read line counter = endCounter; } // Print some debug information if (debugFlag) { logger.info("\nMOOSEFileHandler Message: " + "Block output read from GetPot file " + filePath + " follows."); // Dump each line of the newly created block for (String line : blockLines) { logger.info(line); } } } } } else if (debugFlag) { System.err.println( "MOOSEFileHandler Message: " + "String loaded from " + filePath + " is null or empty."); } return trees; }
From source file:es.pode.catalogadorWeb.presentacion.categoriasAvanzado.ciclodevida.CiclodevidaControllerImpl.java
private void cambioFormulario(HttpServletRequest request, int longitudDescripciones, int longitudVersiones, int longitudContribuciones, int[] longitudTextosDesc, int[] longitudEntidadesContrib) { //descripciones descripciones = new DescripcionVO[longitudDescripciones]; versiones = new VersionVO[1]; contribuciones = new Contribucion[longitudContribuciones]; ArrayList[] textoDescripciones = new ArrayList[longitudDescripciones]; ArrayList[] idiomaDescripciones = new ArrayList[longitudDescripciones]; ArrayList[] nombresEntidades = new ArrayList[longitudContribuciones]; ArrayList[] orgsEntidades = new ArrayList[longitudContribuciones]; ArrayList[] correoEntidades = new ArrayList[longitudContribuciones]; String[] idiomaVersion = new String[longitudVersiones]; String[] textoVersion = new String[longitudVersiones]; String[] fechaCorta = new String[longitudContribuciones]; String[] horas = new String[longitudContribuciones]; String[] minutos = new String[longitudContribuciones]; String[] segundos1 = new String[longitudContribuciones]; String[] segundos2 = new String[longitudContribuciones]; String[] zhHoras = new String[longitudContribuciones]; String[] zhMinutos = new String[longitudContribuciones]; String[] roles = new String[longitudContribuciones]; String[] zonaH = new String[longitudContribuciones]; String[] meridianosCero = new String[longitudContribuciones]; for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) { String name = String.valueOf(names.nextElement()); if (name.startsWith("Cont")) {//descripciones String[] namePartido = name.split("_"); int i = Integer.parseInt(namePartido[0].substring(4, namePartido[0].length())); //Descripciones fechas if (namePartido[1].startsWith("DesFecTex")) { int j = Integer.parseInt(namePartido[1].substring(9, namePartido[1].length())); ArrayList lDesc = textoDescripciones[i]; if (lDesc == null) { lDesc = new ArrayList(); for (int k = 0; k < longitudTextosDesc[i]; k++) lDesc.add(""); }/* www . j a v a 2 s.c om*/ lDesc.set(j, request.getParameter(name)); textoDescripciones[i] = lDesc; } else if (namePartido[1].startsWith("DesFecIdio")) {//Idio int j = Integer.parseInt(namePartido[1].substring(10, namePartido[1].length())); ArrayList lDesc = idiomaDescripciones[i]; if (lDesc == null) { lDesc = new ArrayList(); for (int k = 0; k < longitudTextosDesc[i]; k++) lDesc.add(""); } lDesc.set(j, request.getParameter(name)); idiomaDescripciones[i] = lDesc; } // partes de la fecha else if (namePartido[1].startsWith("FechaCorta")) fechaCorta[i] = request.getParameter(name); else if (namePartido[1].startsWith("FechaHora")) horas[i] = request.getParameter(name); else if (namePartido[1].startsWith("FechaMin")) minutos[i] = request.getParameter(name); else if (namePartido[1].startsWith("FechaSeg1")) segundos1[i] = request.getParameter(name); else if (namePartido[1].startsWith("FechaSeg2")) segundos2[i] = request.getParameter(name); else if (namePartido[1].startsWith("FechaZHHora")) zhHoras[i] = request.getParameter(name); else if (namePartido[1].startsWith("FechaZHMinutos")) zhMinutos[i] = request.getParameter(name); else if (namePartido[1].startsWith("FechaZonaH")) zonaH[i] = request.getParameter(name); else if (namePartido[1].startsWith("Rol")) roles[i] = request.getParameter(name); //entidades else if (namePartido[1].startsWith("Ent")) { int j = Integer.parseInt(namePartido[1].substring(3, namePartido[1].length())); if (namePartido[2].startsWith("Nom")) { ArrayList lNom = nombresEntidades[i]; if (lNom == null) { lNom = new ArrayList(); for (int k = 0; k < longitudEntidadesContrib[i]; k++) lNom.add(""); } lNom.set(j, request.getParameter(name)); nombresEntidades[i] = lNom; } if (namePartido[2].startsWith("Org")) { ArrayList lOrg = orgsEntidades[i]; if (lOrg == null) { lOrg = new ArrayList(); for (int k = 0; k < longitudEntidadesContrib[i]; k++) lOrg.add(""); } lOrg.set(j, request.getParameter(name)); orgsEntidades[i] = lOrg; } if (namePartido[2].startsWith("Cor")) { ArrayList lCor = correoEntidades[i]; if (lCor == null) { lCor = new ArrayList(); for (int k = 0; k < longitudEntidadesContrib[i]; k++) lCor.add(""); } lCor.set(j, request.getParameter(name)); correoEntidades[i] = lCor; } } else if (namePartido[1].startsWith("meridianoCero")) { meridianosCero[i] = request.getParameter(name); } } if (name.startsWith("Ver")) { if (name.startsWith("VerTex")) { int i = Integer.parseInt(name.substring(6, name.length())); textoVersion[i] = request.getParameter(name); } if (name.startsWith("VerIdio")) { int i = Integer.parseInt(name.substring(7, name.length())); idiomaVersion[i] = request.getParameter(name); } } } //Versiones VersionVO VerVO = new VersionVO(); LangStringVO[] aLangVersion = new LangStringVO[textoVersion.length]; for (int i = 0; i < textoVersion.length; i++) { LangStringVO langVersion = new LangStringVO(); langVersion.setTexto(textoVersion[i]); langVersion.setIdioma(idiomaVersion[i]); aLangVersion[i] = langVersion; } VerVO.setTextos(aLangVersion); versiones[0] = VerVO; //descripciones for (int i = 0; i < textoDescripciones.length; i++) { DescripcionVO descVO = new DescripcionVO(); if (textoDescripciones[i] != null) { LangStringVO[] aLangDesc = new LangStringVO[textoDescripciones[i].size()]; for (int j = 0; j < textoDescripciones[i].size(); j++) { LangStringVO langDesc = new LangStringVO(); langDesc.setTexto(textoDescripciones[i].get(j).toString()); langDesc.setIdioma(idiomaDescripciones[i].get(j).toString()); aLangDesc[j] = langDesc; } descVO.setTextos(aLangDesc); } else { LangStringVO[] aLangString = new LangStringVO[1]; LangStringVO langString = new LangStringVO(); langString.setIdioma(""); langString.setTexto(""); aLangString[0] = langString; descVO.setTextos(aLangString); } descripciones[i] = descVO; } //contribuciones for (int i = 0; i < longitudContribuciones; i++) { Contribucion contribucionAux = new Contribucion(); //rol SourceValueVO rolAux = new SourceValueVO(); rolAux.setValor(roles[i]); //entidad Entidad[] entidadesAux = new Entidad[longitudEntidadesContrib[i]]; for (int j = 0; j < entidadesAux.length; j++) { Entidad entidad = new Entidad(); String correoEntIJ = ""; if ((correoEntidades[i] != null) && (correoEntidades[i].get(j)) != null) { correoEntIJ = correoEntidades[i].get(j).toString(); } entidad.setCorreo(correoEntIJ); String nombresEntIJ = ""; if ((nombresEntidades[i] != null) && (nombresEntidades[i].get(j) != null)) { nombresEntIJ = nombresEntidades[i].get(j).toString(); } entidad.setNombre(nombresEntIJ); String orgsEntIJ = ""; if ((orgsEntidades[i] != null) && (orgsEntidades[i].get(j) != null)) { orgsEntIJ = orgsEntidades[i].get(j).toString(); } entidad.setOrganizacion(orgsEntIJ); entidadesAux[j] = entidad; } //fecha Fecha fechaAux = new Fecha(); fechaAux.setIdioma(this.getCatalogadorAvSession(request).getIdioma()); fechaAux.setFechaCorta(fechaCorta[i]); fechaAux.setHora(horas[i]); fechaAux.setMinutos(minutos[i]); fechaAux.setSegundoP1(segundos1[i]); fechaAux.setSegundoP2(segundos2[i]); fechaAux.setZhHora(zhHoras[i] == null ? "" : zhHoras[i]); fechaAux.setZhMinutos(zhMinutos[i] == null ? "" : zhMinutos[i]); fechaAux.setMasOmenos(zonaH[i] == null ? "" : zonaH[i]); fechaAux.setMeridianoCero(meridianosCero[i]); //contribucion contribucionAux.setRol(rolAux); contribucionAux.setEntidades(entidadesAux); contribucionAux.setFecha(fechaAux); contribuciones[i] = contribucionAux; } }
From source file:com.buaa.cfs.conf.Configuration.java
private void loadResources(Properties properties, ArrayList<Resource> resources, boolean quiet) { if (loadDefaults) { for (String resource : defaultResources) { loadResource(properties, new Resource(resource), quiet); }/*from w w w . java2 s.c om*/ //support the hadoop-site.xml as a deprecated case if (getResource("hadoop-site.xml") != null) { loadResource(properties, new Resource("hadoop-site.xml"), quiet); } } for (int i = 0; i < resources.size(); i++) { Resource ret = loadResource(properties, resources.get(i), quiet); if (ret != null) { resources.set(i, ret); } } }
From source file:com.androguide.honamicontrol.kernel.voltagecontrol.VoltageActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.ic_tools_voltage_control)); setContentView(R.layout.cardsui);/*w w w . j av a 2 s . c o m*/ final SharedPreferences bootPrefs = getSharedPreferences("BOOT_PREFS", 0); CardUI cardsUI = (CardUI) findViewById(R.id.cardsui); cardsUI.addStack(new CardStack("")); cardsUI.addStack(new CardStack(getString(R.string.voltage_control).toUpperCase())); if (Helpers.doesFileExist(UV_MV_TABLE)) { cardsUI.addCard( new CardTextStripe(getString(R.string.warning), getString(R.string.voltage_warning_text), getString(R.string.play_orange), getString(R.string.play_orange), false)); final ArrayList<Integer> applicableVoltages = new ArrayList<Integer>(); for (int i = 500; i < 1100; i += 5) { applicableVoltages.add(i); } String rawUvTable = CPUHelper.readFileViaShell(UV_MV_TABLE, false); String[] splitTable = rawUvTable.split("\n"); final ArrayList<Integer> currentApplicableTable = new ArrayList<Integer>(); // Counters to avoid applying voltage when launching the activity final int[] spinnerCounters = new int[splitTable.length]; for (int i = 0; i < splitTable.length; i++) spinnerCounters[i] = 0; Boolean areDefaultsSaved = false; String[] defaultTable = new String[splitTable.length]; if (!bootPrefs.getString("DEFAULT_VOLTAGE_TABLE", "null").equals("null")) { areDefaultsSaved = true; defaultTable = bootPrefs.getString("DEFAULT_VOLTAGE_TABLE", "null").split(" "); Log.e("Default Table", "Def Table Size: " + defaultTable.length + " // Default Table: " + bootPrefs.getString("DEFAULT_VOLTAGE_TABLE", "null")); } // for each frequency scaling step we add a card for (int i = 0; i < splitTable.length; i++) { // format each line into a frequency in MHz & a voltage in mV String[] separateFreqFromVolts = splitTable[i].split(":"); String freqLabel = separateFreqFromVolts[0].replace("mhz", " MHz:"); String intVoltage = separateFreqFromVolts[1].replaceAll("mV", ""); intVoltage = intVoltage.replaceAll(" ", ""); int currStepVoltage = Integer.valueOf(intVoltage); currentApplicableTable.add(currStepVoltage); ArrayList<String> possibleVoltages = new ArrayList<String>(); if (areDefaultsSaved) { for (int k = 500; k < 1100; k += 5) { if (k == Integer.valueOf(defaultTable[i])) possibleVoltages.add(k + " mV (default)"); else possibleVoltages.add(k + " mV"); } } else { for (int k = 500; k < 1100; k += 5) { if (k == currStepVoltage) possibleVoltages.add(k + " mV (default)"); else possibleVoltages.add(k + " mV"); } } int currIndex = possibleVoltages.indexOf(currStepVoltage + " mV (default)"); if (currIndex == -1) currIndex = possibleVoltages.indexOf(currStepVoltage + " mV"); final int currStep = i; cardsUI.addCard(new CardSpinnerVoltage("", freqLabel, "#1abc9c", "", currIndex, possibleVoltages, this, new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) { if (spinnerCounters[currStep] > 0) { String toApply = "busybox echo \""; String defaultTable = ""; currentApplicableTable.set(currStep, applicableVoltages.get(pos)); for (int j = 0; j < currentApplicableTable.size(); j++) { if (j == 0) { toApply += currentApplicableTable.get(j); defaultTable += currentApplicableTable.get(j); } else { toApply += " " + currentApplicableTable.get(j); defaultTable += " " + currentApplicableTable.get(j); } } toApply += "\" > " + UV_MV_TABLE; CMDProcessor.runSuCommand(toApply); bootPrefs.edit().putString("CURRENT_VOLTAGE_TABLE", defaultTable).commit(); Log.e("toApply", toApply); } else spinnerCounters[currStep]++; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } })); } if (bootPrefs.getString("DEFAULT_VOLTAGE_TABLE", "null").equals("null")) { String table = ""; for (int j = 0; j < currentApplicableTable.size(); j++) { if (j == 0) table += currentApplicableTable.get(j); else table += " " + currentApplicableTable.get(j); } bootPrefs.edit().putString("DEFAULT_VOLTAGE_TABLE", table).commit(); } } cardsUI.refresh(); }
From source file:edu.cuny.cat.market.matching.LazyMaxVolumeShoutEngine.java
/** * <p>//from w w w . jav a2 s. c om * Return a list of matched bids and asks. The list is of the form * </p> * <br> * ( b0, a0, b1, a1 .. bn, an )<br> * * <p> * where bi is the ith bid and a0 is the ith ask. A typical auctioneer would * clear by matching bi with ai for all i at some price. * </p> */ @Override public List<Shout> getMatchedShouts() { final ArrayList<Shout> result = new ArrayList<Shout>(sIn.size() + bIn.size()); // prettyPrint("sIn: ", sIn); // prettyPrint("bIn: ", bIn); // // prettyPrint("asks", asks); // prettyPrint("bid", bids); Shout sInTop = null; Shout bInTop = null; final ListIterator<Shout> sItor = sIn.listIterator(); final ListIterator<Shout> bItor = bIn.listIterator(); while (true) { if (sInTop == null) { if (sItor.hasNext()) { sInTop = sItor.next(); if (!asks.remove(sInTop)) { LazyMaxVolumeShoutEngine.logger.fatal("Failed to remove the matched ask !"); LazyMaxVolumeShoutEngine.logger.fatal(sInTop); } // logger.info(sInTop); } else { break; } } if (bInTop == null) { if (bItor.hasNext()) { bInTop = bItor.next(); if (!bids.remove(bInTop)) { LazyMaxVolumeShoutEngine.logger.fatal("Failed to remove the matched bid !"); LazyMaxVolumeShoutEngine.logger.fatal(bInTop); } // logger.info(bInTop); } else { LazyMaxVolumeShoutEngine.logger.fatal("Unempty bInTop expected !"); } } result.add(bInTop); result.add(sInTop); if (bInTop.getPrice() < sInTop.getPrice()) { LazyMaxVolumeShoutEngine.logger.fatal("Wrong match between ask and bid !"); LazyMaxVolumeShoutEngine.logger.fatal(bInTop); LazyMaxVolumeShoutEngine.logger.fatal(sInTop); } final int nS = sInTop.getQuantity(); final int nB = bInTop.getQuantity(); if (nS < nB) { // split the bid bInTop = bInTop.split(nB - nS); sInTop = null; } else if (nB < nS) { // split the ask sInTop = sInTop.split(nS - nB); bInTop = null; } else { bInTop = null; sInTop = null; } } if (bItor.hasNext()) { LazyMaxVolumeShoutEngine.logger .fatal("Inconsistent state of bIn in " + this + ". Empty bItor expected !"); } sIn.clear(); bIn.clear(); // randomize the matching pairs Shout bid, ask; int index; for (int i = result.size() / 2 - 1; i > 0; i--) { // pick a pair to be at the i(th) // TODO: check whether this can lead to mutual access or not. index = uniform.nextIntFromTo(0, i); bid = result.get(i * 2); ask = result.get(i * 2 + 1); result.set(i * 2, result.get(index * 2)); result.set(i * 2 + 1, result.get(index * 2 + 1)); result.set(index * 2, bid); result.set(index * 2 + 1, ask); } return result; }