List of usage examples for java.util List set
E set(int index, E element);
From source file:com.flipkart.zjsonpatch.JsonDiff.java
/** * This method merge 2 diffs ( remove then add, or vice versa ) with same value into one Move operation, * all the core logic resides here only// w w w. ja v a 2 s. com */ private static void compactDiffs(List<Diff> diffs) { for (int i = 0; i < diffs.size(); i++) { Diff diff1 = diffs.get(i); // if not remove OR add, move to next diff if (!(Operation.REMOVE.equals(diff1.getOperation()) || Operation.ADD.equals(diff1.getOperation()))) { continue; } for (int j = i + 1; j < diffs.size(); j++) { Diff diff2 = diffs.get(j); if (!diff1.getValue().equals(diff2.getValue())) { continue; } Diff moveDiff = null; if (Operation.REMOVE.equals(diff1.getOperation()) && Operation.ADD.equals(diff2.getOperation())) { computeRelativePath(diff2.getPath(), i + 1, j - 1, diffs); moveDiff = new Diff(Operation.MOVE, diff1.getPath(), diff2.getValue(), diff2.getPath()); } else if (Operation.ADD.equals(diff1.getOperation()) && Operation.REMOVE.equals(diff2.getOperation())) { computeRelativePath(diff2.getPath(), i, j - 1, diffs); // diff1's add should also be considered moveDiff = new Diff(Operation.MOVE, diff2.getPath(), diff1.getValue(), diff1.getPath()); } if (moveDiff != null) { diffs.remove(j); diffs.set(i, moveDiff); break; } } } }
From source file:com.datatorrent.stram.client.AppPackage.java
private void processAppDirectory(File dir) { Configuration config = new Configuration(); List<String> absClassPath = new ArrayList<String>(classPath); for (int i = 0; i < absClassPath.size(); i++) { String path = absClassPath.get(i); if (!path.startsWith("/")) { absClassPath.set(i, directory + "/" + path); }//from w w w. j a va 2 s. c o m } config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, StringUtils.join(absClassPath, ',')); File[] files = dir.listFiles(); for (File entry : files) { if (entry.getName().endsWith(".jar")) { appJars.add(entry.getName()); try { StramAppLauncher stramAppLauncher = new StramAppLauncher(entry, config); stramAppLauncher.loadDependencies(); List<AppFactory> appFactories = stramAppLauncher.getBundledTopologies(); for (AppFactory appFactory : appFactories) { String appName = stramAppLauncher.getLogicalPlanConfiguration() .getAppAlias(appFactory.getName()); if (appName == null) { appName = appFactory.getName(); } AppInfo appInfo = new AppInfo(appName, entry.getName(), "class"); appInfo.displayName = appFactory.getDisplayName(); try { appInfo.dag = appFactory.createApp(stramAppLauncher.getLogicalPlanConfiguration()); appInfo.dag.validate(); } catch (Throwable ex) { appInfo.error = ex.getMessage(); appInfo.errorStackTrace = ExceptionUtils.getStackTrace(ex); } applications.add(appInfo); } } catch (Exception ex) { LOG.error("Caught exception trying to process {}", entry.getName(), ex); } } } // this is for the properties and json files to be able to depend on the app jars, // since it's possible for users to implement the operators as part of the app package for (String appJar : appJars) { absClassPath.add(new File(dir, appJar).getAbsolutePath()); } config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, StringUtils.join(absClassPath, ',')); files = dir.listFiles(); for (File entry : files) { if (entry.getName().endsWith(".json")) { appJsonFiles.add(entry.getName()); try { AppFactory appFactory = new StramAppLauncher.JsonFileAppFactory(entry); StramAppLauncher stramAppLauncher = new StramAppLauncher(entry.getName(), config); stramAppLauncher.loadDependencies(); AppInfo appInfo = new AppInfo(appFactory.getName(), entry.getName(), "json"); appInfo.displayName = appFactory.getDisplayName(); try { appInfo.dag = appFactory.createApp(stramAppLauncher.getLogicalPlanConfiguration()); appInfo.dag.validate(); } catch (Exception ex) { appInfo.error = ex.getMessage(); appInfo.errorStackTrace = ExceptionUtils.getStackTrace(ex); } applications.add(appInfo); } catch (Exception ex) { LOG.error("Caught exceptions trying to process {}", entry.getName(), ex); } } else if (entry.getName().endsWith(".properties")) { appPropertiesFiles.add(entry.getName()); try { AppFactory appFactory = new StramAppLauncher.PropertyFileAppFactory(entry); StramAppLauncher stramAppLauncher = new StramAppLauncher(entry.getName(), config); stramAppLauncher.loadDependencies(); AppInfo appInfo = new AppInfo(appFactory.getName(), entry.getName(), "properties"); appInfo.displayName = appFactory.getDisplayName(); try { appInfo.dag = appFactory.createApp(stramAppLauncher.getLogicalPlanConfiguration()); appInfo.dag.validate(); } catch (Throwable t) { appInfo.error = t.getMessage(); appInfo.errorStackTrace = ExceptionUtils.getStackTrace(t); } applications.add(appInfo); } catch (Exception ex) { LOG.error("Caught exceptions trying to process {}", entry.getName(), ex); } } else if (!entry.getName().endsWith(".jar")) { LOG.warn("Ignoring file {} with unknown extension in app directory", entry.getName()); } } }
From source file:com.extrahardmode.module.MsgModule.java
/** * Send a short message using SbPopupAPI * * @param player player to send the message to * @param category type defines the length color for consistency * @param message text already seperated into lines * @param stripColors if colors should be removed from the message *//*from ww w . j a va 2 s . c om*/ public void sendPopup(Player player, MsgCategory category, List<String> message, boolean stripColors) { if (popupsAreEnabled(category)) { int length; ChatColor titleColor; ChatColor textColor; String titleText = messages.getString(MessageNode.SB_MSG_TITLE); if (stripColors) for (int i = 0; i < message.size(); i++) message.set(i, ChatColor.stripColor(message.get(i))); switch (category) { case BROADCAST: length = messages.getInt(MessageNode.SB_MSG_BROADCAST_LEN); titleColor = null; textColor = messages.getColor(MessageNode.SB_MSG_BROADCAST_TEXT_CLR); break; case ONE_TIME: case NOTIFICATION: length = messages.getInt(MessageNode.SB_MSG_NOTIFICATION_LEN); titleColor = null; textColor = messages.getColor(MessageNode.SB_MSG_NOTIFICATION_TEXT_CLR); break; case TUTORIAL: length = messages.getInt(MessageNode.SB_MSG_TUTORIAL_LEN); titleColor = null; textColor = messages.getColor(MessageNode.SB_MSG_TUTORIAL_TEXT_CLR); break; case DISABLED: default: length = 0; titleColor = null; textColor = null; } manager.showPopup(player.getName(), category.getUniqueIdentifier(), length, titleColor, textColor, titleText, message); } }
From source file:com.techcavern.wavetact.ircCommands.chanhalfop.Topic.java
@Override public void onCommand(String command, User user, PircBotX network, String prefix, Channel channel, boolean isPrivate, int userPermLevel, String... args) throws Exception { Record topicseparator = DatabaseUtils.getChannelProperty(IRCUtils.getNetworkNameByNetwork(network), channel.getName(), "topicseparator"); boolean isTopicCommand = args[0].equalsIgnoreCase("ad") || args[0].equalsIgnoreCase("add") || args[0].startsWith("+") || args[0].startsWith("-") || args[0].equalsIgnoreCase("sw") || args[0].equalsIgnoreCase("swap") || args[0].equalsIgnoreCase("switch") || args[0].equalsIgnoreCase("rev") || args[0].equalsIgnoreCase("revert"); if (!isTopicCommand) { IRCUtils.setTopic(network, channel, GeneralUtils.buildMessage(0, args.length, args)); saveTopic(channel, network);/* ww w. jav a 2s .c om*/ return; } else if (topicseparator == null) { IRCUtils.sendError(user, network, channel, "Please set the topic separator before using this command", prefix); return; } StringUtils.split(channel.getTopic(), topicseparator.getValue(CHANNELPROPERTY.VALUE)); List<String> topic = new LinkedList(Arrays .asList(StringUtils.split(channel.getTopic(), topicseparator.getValue(CHANNELPROPERTY.VALUE)))); List<String> newtopic = new LinkedList(Arrays .asList(StringUtils.split(channel.getTopic(), topicseparator.getValue(CHANNELPROPERTY.VALUE)))); if (args[0].equalsIgnoreCase("ad") || args[0].equalsIgnoreCase("add")) { IRCUtils.setTopic(network, channel, channel.getTopic() + " " + topicseparator.getValue(CHANNELPROPERTY.VALUE) + " " + GeneralUtils.buildMessage(1, args.length, args)); saveTopic(channel, network); } else if (args[0].startsWith("+")) { newtopic.set(Integer.parseInt(args[0].replaceFirst("\\+", "")) - 1, " " + GeneralUtils.buildMessage(1, args.length, args) + " "); IRCUtils.setTopic(network, channel, StringUtils.join(newtopic, topicseparator.getValue(CHANNELPROPERTY.VALUE))); saveTopic(channel, network); } else if (args[0].startsWith("-")) { newtopic.remove(Integer.parseInt(args[0].replaceFirst("\\-", "")) - 1); IRCUtils.setTopic(network, channel, StringUtils.join(newtopic, topicseparator.getValue(CHANNELPROPERTY.VALUE))); saveTopic(channel, network); } else if (args[0].equalsIgnoreCase("sw") || args[0].equalsIgnoreCase("swap") || args[0].equalsIgnoreCase("switch")) { newtopic.set((Integer.parseInt(args[1]) - 1), topic.get(Integer.parseInt(args[2]) - 1)); newtopic.set((Integer.parseInt(args[2]) - 1), topic.get(Integer.parseInt(args[1]) - 1)); channel.send().setTopic(StringUtils.join(newtopic, topicseparator.getValue(CHANNELPROPERTY.VALUE))); saveTopic(channel, network); } else if (args[0].equalsIgnoreCase("rev") || args[0].equalsIgnoreCase("revert")) { Record oldTopic = DatabaseUtils.getChannelProperty(IRCUtils.getNetworkNameByNetwork(network), channel.getName(), "topic"); if (oldTopic != null) { IRCUtils.setTopic(network, channel, oldTopic.getValue(CHANNELPROPERTY.VALUE)); } else { IRCUtils.sendError(user, network, channel, "Error: no reversal possible", prefix); } } else { IRCUtils.setTopic(network, channel, GeneralUtils.buildMessage(0, args.length, args)); saveTopic(channel, network); } }
From source file:ca.mcgill.cs.creco.logic.ConcreteServiceFacade.java
/*** * //from w ww . ja v a 2s . co m * @param pUserFeatures list of scored attributes selected by the user. * @return list of sorted scored attributes according to attribute correlation. */ public List<ScoredAttribute> sortFeatures(List<ScoredAttribute> pUserFeatures) { ScoredAttribute tmp = null; for (int i = 0; i < pUserFeatures.size(); i++) { for (int j = pUserFeatures.size() - 1; j >= i + 1; j--) { if (pUserFeatures.get(j).getCorrelation() > pUserFeatures.get(j - 1).getCorrelation()) { tmp = pUserFeatures.get(j); pUserFeatures.set(j, pUserFeatures.get(j - 1)); pUserFeatures.set(j - 1, tmp); } } } return pUserFeatures; }
From source file:es.bsc.autonomic.powermodeller.DataSet.java
public DataSet replaceCol(String colName, String newColName, List<Double> newValues) { if (size != newValues.size()) { throw new DataSetException( "Can not swap columns between DataSet and array of different number of samples."); }/*from w w w .j a v a 2s . c o m*/ if (!header.contains(colName)) { throw new DataSetException("Specified column '" + colName + "' does not exist in the DataSet."); } //Read current contents of file CSVReader reader = null; List<String[]> contents = null; try { reader = new CSVReader(new FileReader(filePath), CoreConfiguration.CSV_DELIMITER, CSVReader.DEFAULT_ESCAPE_CHARACTER, 1); contents = reader.readAll(); } catch (IOException e) { logger.error("Error while reading CSV file.", e); throw new DataSetException("Error while reading CSV file."); } finally { try { reader.close(); } catch (IOException e) { logger.error("Error while closing CSV file.", e); throw new DataSetException("Error while closing CSV file."); } } //Modify array with new column name int colIndex = header.indexOf(colName); //Write new contents to file while modifying specified column CSVWriter writer = null; String filePath = null; try { filePath = CoreConfiguration.getNewCSVFileName(); writer = new CSVWriter(new FileWriter(filePath), CoreConfiguration.CSV_DELIMITER, CSVWriter.NO_QUOTE_CHARACTER); List<String> newHeader = new ArrayList<String>(header); newHeader.set(colIndex, newColName); //Write new header writer.writeNext(newHeader.toArray(new String[0])); //Write new contents for (int i = 0; i < size; i++) { List<String> modifiedRecord = new ArrayList<String>(Arrays.asList(contents.get(i))); modifiedRecord.set(colIndex, newValues.get(i).toString()); writer.writeNext(modifiedRecord.toArray(new String[0])); } } catch (IOException e) { logger.error("Error while reading CSV file.", e); throw new DataSetException("Error while reading CSV file."); } finally { try { writer.close(); } catch (IOException e) { logger.error("Error while closing CSV file.", e); throw new DataSetException("Error while closing CSV file."); } } DataSet ret = new DataSet(filePath); if (colName.equalsIgnoreCase(this.getIndependent())) { ret.setIndependent(newColName); logger.debug("Changing independent variable column from " + colName + " to " + newColName); } return ret; }
From source file:net.nifheim.beelzebu.coins.common.utils.FileManager.java
private void updateMessages() { try {/*from w ww .j av a 2 s . c o m*/ List<String> lines = FileUtils.readLines(messagesFiles.get("default"), Charsets.UTF_8); int index; if (core.getMessages("").getInt("version") == 6) { index = lines.indexOf("version: 6"); lines.set(index, "version: 7"); index = lines.indexOf("Multipliers:"); lines.remove(index); index = lines.indexOf(" Menu:"); lines.add(index, "Multipliers:"); core.log("Updated messages.yml file to v7"); } if (core.getMessages("").getInt("version") == 7) { index = lines.indexOf("version: 7"); lines.set(index, "version: 8"); index = lines.indexOf(" Menu:") + 2; lines.addAll(index, Arrays.asList(" Confirm:", " Title: '&8Are you sure?'", " Accept: '&aYES!'", " Decline: '&cNope'", " Multipliers:", " Name: '&6Multiplier &cx%amount%'", " Lore:", " - ''", " - '&7Amount: &c%amount%'", " - '&7Server: &c%server%'", " - '&7Minutes: &c%minutes%'", " - ''", " - '&7ID: &c#%id%'", " No Multipliers:", " Name: '&cYou don''t have any multiplier :('", " Lore:", " - ''", " - '&7You can buy multipliers in our store'", " - '&6&nstore.servername.net'")); core.log("Updated messages.yml file to v8"); } if (core.getMessages("").getInt("version") == 8) { index = lines.indexOf("version: 8"); lines.set(index, "version: 9"); lines.removeAll(Arrays.asList("# Coins messages file.", "# If you need support or find a bug open a issuse in", "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "", "# The version of this file, don't edit!")); lines.addAll(0, Arrays.asList("# Coins messages file.", "# If you need support or find a bug open a issuse in", "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "", "# The version of this file, is used to auto update this file, don't change it", "# unless you know what you do.")); core.log("Updated messages.yml file to v9"); } if (core.getMessages("").getInt("version") == 9) { index = lines.indexOf("version: 9"); lines.set(index, "version: 10"); index = lines.indexOf( " Multiplier Create: '" + core.getMessages("").getString("Help.Multiplier Create") + "'") + 1; lines.add(index, " Multiplier Set: '%prefix% &cPlease use &f/coins multiplier set <amount> <enabler> <minutes> (server)'"); lines.addAll(Arrays.asList(" Set:", " - '%prefix% A multiplier with the following data was set for %server%'", " - ' &7Enabler: &c%enabler%'", " - ' &7Amount: &c%amount%'", " - ' &7Minutes: &c%minutes%'")); core.log("Updated messages.yml file to v10"); } FileUtils.writeLines(messagesFiles.get("default"), lines); } catch (IOException ex) { core.log("An unexpected error occurred while updating the messages.yml file."); core.debug(ex.getMessage()); } try { List<String> lines = FileUtils.readLines(messagesFiles.get("es"), Charsets.UTF_8); int index; if (core.getMessages("es").getInt("version") == 6) { index = lines.indexOf("version: 6"); lines.set(index, "version: 7"); index = lines.indexOf("Multipliers:"); lines.remove(index); index = lines.indexOf(" Menu:"); lines.add(index, "Multipliers:"); core.log("Updated messages_es.yml file to v7"); } if (core.getMessages("es").getInt("version") == 7) { index = lines.indexOf("version: 7"); lines.set(index, "version: 8"); index = lines.indexOf(" Menu:") + 2; lines.addAll(index, Arrays.asList(" Confirm:", " Title: '&8Ests seguro?'", " Accept: '&aSI!'", " Decline: '&cNo'", " Multipliers:", " Name: '&6Multiplicador &cx%amount%'", " Lore:", " - ''", " - '&7Cantidad: &c%amount%'", " - '&7Servidor: &c%server%'", " - '&7Minutos: &c%minutes%'", " - ''", " - '&7ID: &c#%id%'", " No Multipliers:", " Name: '&cNo tienes ningn multiplicador :('", " Lore:", " - ''", " - '&7Puedes comprar multiplicadores en nuestra tienda'", " - '&6&nstore.servername.net'")); core.log("Updated messages_es.yml file to v8"); } index = lines.indexOf(" - '&6&nstore.servername.net'\""); if (index != -1) { lines.set(index, " - '&6&nstore.servername.net'"); } if (core.getMessages("es").getInt("version") == 8) { index = lines.indexOf("version: 8"); lines.set(index, "version: 9"); lines.removeAll(Arrays.asList("# Coins messages file.", "# If you need support or find a bug open a issuse in", "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "", "# The version of this file, don't edit!")); lines.addAll(0, Arrays.asList("# Coins messages file.", "# Si necesitas soporte o encuentras un error por favor abre un ticket en el", "# repositorio oficial de github https://github.com/Beelzebu/Coins/issuses/", "", "# La versin de este archivo, es usado para actualizarlo automticamente, no lo cambies", "# a menos que sepas lo que haces.")); core.log("Updated messages_es.yml file to v9"); } if (core.getMessages("es").getInt("version") == 9) { index = lines.indexOf("version: 9"); lines.set(index, "version: 10"); index = lines.indexOf( " Multiplier Create: '" + core.getMessages("es").getString("Help.Multiplier Create") + "'") + 1; lines.add(index, " Multiplier Set: '%prefix% &cPor favor usa &f/coins multiplier set <cantidad> <activador> <minutos> (server)'"); lines.addAll(Arrays.asList(" Set:", " - '%prefix% Un multiplicador con la siguiente informacin fue establecido en %server%'", " - ' &7Activador: &c%enabler%'", " - ' &7Cantidad: &c%amount%'", " - ' &7Minutos: &c%minutes%'")); core.log("Updated messages_es.yml file to v10"); } if (lines.get(0).startsWith(" Multiplier Set:")) { lines.remove(0); index = lines.indexOf( " Multiplier Create: '" + core.getMessages("es").getString("Help.Multiplier Create") + "'") + 1; lines.add(index, " Multiplier Set: '%prefix% &cPor favor usa &f/coins multiplier set <cantidad> <activador> <minutos> (server)'"); } FileUtils.writeLines(messagesFiles.get("es"), lines); } catch (IOException ex) { core.log("An unexpected error occurred while updating the messages_es.yml file."); core.debug(ex.getMessage()); } }
From source file:com.shopify.buy.dataprovider.BuyClientError.java
/** * Returns the ordered list of line items errors for specific property. Index of errors corresponds to the index * of line item in the checkout. Could contain null items that represents no errors for the particular line item. * * @param property filter for line item errors (e.g. "quantity") * @return ordered list of line items errors */// ww w . j a v a 2s . com public List<Map<String, String>> getLineItemErrors(final String property) { if (errorsRootJsonObject == null) { return null; } if (TextUtils.isEmpty(property)) { return null; } final Iterator<String> pathIterator = Arrays.asList("checkout", "line_items").iterator(); JSONObject rootJsonObject = errorsRootJsonObject; try { JSONArray lineItemJsonErrors = null; while (pathIterator.hasNext()) { final String pathElement = pathIterator.next(); if (rootJsonObject.has(pathElement)) { if (pathIterator.hasNext()) { rootJsonObject = rootJsonObject.getJSONObject(pathElement); } else { lineItemJsonErrors = rootJsonObject.getJSONArray(pathElement); } } else { return null; } } if (lineItemJsonErrors == null) { return null; } final List<Map<String, String>> lineItemErrors = new ArrayList<>(); for (int i = 0; i < lineItemJsonErrors.length(); i++) { lineItemErrors.add(null); if (!lineItemJsonErrors.isNull(i)) { final JSONObject lineItemError = lineItemJsonErrors.getJSONObject(i); if (lineItemError.has(property)) { try { lineItemErrors.set(i, parseErrorMessages(lineItemError.getJSONArray(property))); } catch (Exception e) { // ignore } } } } return lineItemErrors; } catch (Exception e) { return null; } }
From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.JourneyPhaseSummaryLibrary.java
public List<JourneyPhaseSummary> extendSummaries(VehicleState parentState, BlockState blockState, JourneyState journeyState, Observation observation) { List<JourneyPhaseSummary> parentSummaries = Collections.emptyList(); if (parentState != null) parentSummaries = parentState.getJourneySummaries(); List<JourneyPhaseSummary> summaries = new ArrayList<JourneyPhaseSummary>(parentSummaries); if (summaries.isEmpty()) { JourneyPhaseSummary summary = createJourneySummary(blockState, journeyState, observation); summaries.add(summary);// ww w . j a v a 2 s .c om } else { JourneyPhaseSummary previous = summaries.get(summaries.size() - 1); JourneyPhaseSummary merged = createMergedJourneySummary(blockState, journeyState, observation, previous); if (merged != null) { summaries.set(summaries.size() - 1, merged); } else { JourneyPhaseSummary summary = createJourneySummary(blockState, journeyState, observation); summaries.add(summary); } } return summaries; }
From source file:com.google.gerrit.server.project.SectionSortCache.java
void sort(String ref, List<AccessSection> sections) { final int cnt = sections.size(); if (cnt <= 1) { return;/* w ww .j a v a 2s .c om*/ } EntryKey key = new EntryKey(ref, sections); EntryVal val = cache.get(key); if (val != null) { int[] srcIdx = val.order; if (srcIdx != null) { AccessSection[] srcList = copy(sections); for (int i = 0; i < cnt; i++) { sections.set(i, srcList[srcIdx[i]]); } } else { // Identity transform. No sorting is required. } } else { IdentityHashMap<AccessSection, Integer> srcMap = new IdentityHashMap<AccessSection, Integer>(); for (int i = 0; i < cnt; i++) { srcMap.put(sections.get(i), i); } Collections.sort(sections, new MostSpecificComparator(ref)); int srcIdx[]; if (isIdentityTransform(sections, srcMap)) { srcIdx = null; } else { srcIdx = new int[cnt]; for (int i = 0; i < cnt; i++) { srcIdx[i] = srcMap.get(sections.get(i)); } } cache.put(key, new EntryVal(srcIdx)); } }