List of usage examples for org.apache.commons.lang3.tuple Pair getKey
@Override public final L getKey()
Gets the key from this pair.
This method implements the Map.Entry interface returning the left element as the key.
From source file:io.pravega.service.server.host.stat.AutoScaleProcessor.java
private void triggerScaleUp(String streamSegmentName, int numOfSplits) { if (initialized.get()) { Pair<Long, Long> pair = cache.getIfPresent(streamSegmentName); long lastRequestTs = 0; if (pair != null && pair.getKey() != null) { lastRequestTs = pair.getKey(); }// ww w. ja v a 2 s.c om long timestamp = System.currentTimeMillis(); if (timestamp - lastRequestTs > configuration.getMuteDuration().toMillis()) { log.debug("sending request for scale up for {}", streamSegmentName); Segment segment = Segment.fromScopedName(streamSegmentName); ScaleEvent event = new ScaleEvent(segment.getScope(), segment.getStreamName(), segment.getSegmentNumber(), ScaleEvent.UP, timestamp, numOfSplits, false); // Mute scale for timestamp for both scale up and down writeRequest(event) .thenAccept(x -> cache.put(streamSegmentName, new ImmutablePair<>(timestamp, timestamp))); } } }
From source file:com.github.jknack.handlebars.cache.ConcurrentMapTemplateCache.java
/** * Get/Parse a template source./*w w w .ja v a 2s . c o m*/ * * @param source The template source. * @param parser The parser. * @return A Handlebars template. * @throws IOException If we can't read input. */ private Template cacheGet(final TemplateSource source, final Parser parser) throws IOException { Pair<TemplateSource, Template> entry = cache.get(source); if (entry == null) { logger.debug("Loading: {}", source); entry = Pair.of(source, parser.parse(source)); cache.put(source, entry); } else if (source.lastModified() != entry.getKey().lastModified()) { // remove current entry. evict(source); logger.debug("Reloading: {}", source); entry = Pair.of(source, parser.parse(source)); cache.put(source, entry); } else { logger.debug("Found in cache: {}", source); } return entry.getValue(); }
From source file:com.jaspersoft.jasperserver.jrsh.completion.completer.RepositoryNameCompleter.java
@Override public int complete(String buffer, int cursor, List<CharSequence> candidates) { if (buffer != null && cursor < buffer.length()) { candidates.add(""); return buffer.length(); }/* w ww. j av a 2 s.co m*/ if (uniqueId == 0) { uniqueId = hashCode(); } if (buffer == null) { candidates.add("/"); return 0; } else { if (uniqueId == hashCode()) { if (buffer.isEmpty()) { return 0; } List<Pair<String, Boolean>> resources; List<String> filteredResources; try { if (isResourceExist(buffer)) { resources = download(buffer); if (!resources.isEmpty() && !buffer.equals("/")) { return buffer.length() + 1; } fillResources(candidates, resources); } else { String root = getPreviousPath(buffer); if (isResourceExist(root)) { resources = download(root); List<Pair<String, Boolean>> temp = new ArrayList<>(); for (Pair<String, Boolean> pair : resources) { String resource = pair.getKey(); Boolean isFolder = pair.getRight(); if (startsWith(resource, buffer)) { ImmutablePair<String, Boolean> newPair = new ImmutablePair<>(resource, isFolder); temp.add(newPair); } } fillResources(candidates, temp); } else { String lastInput = getLastInput(buffer); if ("".equals(lastInput)) { List<Pair<String, Boolean>> temp = new ArrayList<>(); ImmutablePair<String, Boolean> newPair = new ImmutablePair<>("", false); temp.add(newPair); fillResources(candidates, temp); return buffer.length(); } } } } catch (AuthenticationFailedException e3) { SessionUtil.reopenSession(); complete(buffer, cursor, candidates); } if (candidates.size() == 1) { return buffer.lastIndexOf("/") + 1; } if (candidates.size() > 1) { String lastInput = getLastInput(buffer); if (compareCandidatesWithLastInput(lastInput, candidates)) { return buffer.length() - lastInput.length(); } } return buffer.length(); } else { candidates.addAll(bufCandidates); if (candidates.size() > 0) { String lastInput = getLastInput(buffer); if (compareCandidatesWithLastInput(lastInput, candidates)) { return buffer.length() - lastInput.length(); } } return buffer.length(); } } }
From source file:com.nttec.everychan.chans.sich.SichModule.java
@Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = CHAN_NAME;// w ww. ja va 2 s. c o m urlModel.boardName = model.boardName; if (model.threadNumber == null) { urlModel.type = UrlPageModel.TYPE_BOARDPAGE; urlModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE; } else { urlModel.type = UrlPageModel.TYPE_THREADPAGE; urlModel.threadNumber = model.threadNumber; } String referer = buildUrl(urlModel); List<Pair<String, String>> fields = VichanAntiBot.getFormValues(referer, task, httpClient); if (task != null && task.isCancelled()) throw new Exception("interrupted"); ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create() .setCharset(Charset.forName("UTF-8")).setDelegates(listener, task); for (Pair<String, String> pair : fields) { if (pair.getKey().equals("spoiler")) continue; String val; switch (pair.getKey()) { case "subject": val = model.subject; break; case "body": val = model.comment; break; case "password": val = model.password; break; default: val = pair.getValue(); } int i = 1; String fileNo; switch (pair.getKey()) { case "file": case "file2": case "file3": case "file4": fileNo = pair.getKey().replaceAll("[\\D]", ""); if (fileNo != "") { i = Integer.parseInt(fileNo); } if (model.attachments == null || model.attachments.length < i) { postEntityBuilder.addPart(pair.getKey(), new ByteArrayBody(new byte[0], "")); } else { postEntityBuilder.addFile(pair.getKey(), model.attachments[i - 1], model.randomHash); } break; default: postEntityBuilder.addString(pair.getKey(), val); } } String url = getUsingUrl() + "post.php"; Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, referer) }; HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()) .setCustomHeaders(customHeaders).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, listener, task); if (response.statusCode == 200 || response.statusCode == 400) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); Matcher errorMatcher = ERROR_PATTERN.matcher(htmlResponse); if (errorMatcher.find()) throw new Exception(errorMatcher.group(1)); } else if (response.statusCode == 303) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { return fixRelativeUrl(header.getValue()); } } } throw new Exception(response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } }
From source file:com.act.lcms.db.model.LCMSWell.java
public List<LCMSWell> insertFromPlateComposition(DB db, PlateCompositionParser parser, Plate p) throws SQLException, IOException { Map<Pair<String, String>, String> msids = parser.getCompositionTables().get("msid"); List<Pair<String, String>> sortedCoordinates = new ArrayList<>(msids.keySet()); Collections.sort(sortedCoordinates, new Comparator<Pair<String, String>>() { // TODO: parse the values of these pairs as we read them so we don't need this silly comparator. @Override/*from www. ja va 2s.c om*/ public int compare(Pair<String, String> o1, Pair<String, String> o2) { if (o1.getKey().equals(o2.getKey())) { return Integer.valueOf(Integer.parseInt(o1.getValue())) .compareTo(Integer.parseInt(o2.getValue())); } return o1.getKey().compareTo(o2.getKey()); } }); List<LCMSWell> results = new ArrayList<>(); for (Pair<String, String> coords : sortedCoordinates) { String msid = msids.get(coords); if (msid == null || msid.isEmpty()) { continue; } String composition = parser.getCompositionTables().get("composition").get(coords); String chemical = parser.getCompositionTables().get("chemical").get(coords); String note = null; if (parser.getCompositionTables().get("note") != null) { note = parser.getCompositionTables().get("note").get(coords); } Pair<Integer, Integer> index = parser.getCoordinatesToIndices().get(coords); LCMSWell s = INSTANCE.insert(db, p.getId(), index.getLeft(), index.getRight(), msid, composition, chemical, note); results.add(s); } return results; }
From source file:alfio.manager.WaitingQueueManager.java
private List<Integer> selectTicketsForPreReservation(int eventId, Pair<Integer, TicketCategoryStatisticView> p) { TicketCategoryStatisticView category = p.getValue(); Integer amount = p.getKey(); if (category.isBounded()) { return ticketRepository.selectFreeTicketsForPreReservation(eventId, amount, category.getId()); }//w w w .j ava2 s . c o m return ticketRepository.selectNotAllocatedFreeTicketsForPreReservation(eventId, amount); }
From source file:forge.limited.BoosterDraftAI.java
/** * <p>/*from w ww .j a va2 s.c o m*/ * Choose a CardPrinted from the list given. * </p> * * @param chooseFrom * List of CardPrinted * @param player * a int. * @return a {@link forge.item.PaperCard} object. */ public PaperCard choose(final List<PaperCard> chooseFrom, final int player) { if (ForgePreferences.DEV_MODE) { System.out.println("Player[" + player + "] pack: " + chooseFrom.toString()); } final DeckColors deckCols = this.playerColors.get(player); final ColorSet currentChoice = deckCols.getChosenColors(); final boolean canAddMoreColors = deckCols.canChoseMoreColors(); final List<Pair<PaperCard, Double>> rankedCards = rankCards(chooseFrom); for (final Pair<PaperCard, Double> p : rankedCards) { double valueBoost = 0; // If a card is not ai playable, somewhat decrease its rating if (p.getKey().getRules().getAiHints().getRemAIDecks()) { valueBoost = TAKE_BEST_THRESHOLD; } // if I cannot choose more colors, and the card cannot be played with chosen colors, decrease its rating. if (!canAddMoreColors && !p.getKey().getRules().getManaCost().canBePaidWithAvaliable(currentChoice.getColor())) { valueBoost = TAKE_BEST_THRESHOLD * 3; } if (valueBoost > 0) { p.setValue(p.getValue() + valueBoost); //System.out.println(p.getKey() + " is now " + p.getValue()); } } double bestRanking = Double.MAX_VALUE; PaperCard bestPick = null; final List<PaperCard> possiblePick = new ArrayList<PaperCard>(); for (final Pair<PaperCard, Double> p : rankedCards) { final double rating = p.getValue(); if (rating <= bestRanking + .01) { if (rating < bestRanking) { // found a better card start a new list possiblePick.clear(); bestRanking = rating; } possiblePick.add(p.getKey()); } } bestPick = Aggregates.random(possiblePick); if (canAddMoreColors) { deckCols.addColorsOf(bestPick); } System.out.println("Player[" + player + "] picked: " + bestPick + " ranking of " + bestRanking); this.deck.get(player).add(bestPick); return bestPick; }
From source file:candr.yoclip.DefaultParserHelpFactory.java
@Override public List<Pair<String, String>> getOptionPropertyDescriptions(ParserOption<T> parserOption) { if (null == parserOption) { throw new IllegalArgumentException("ParserOption cannot be null."); }//w w w. ja v a 2s. c om List<Pair<String, String>> propertyDescriptions = parserOption.getPropertyDescriptions(); if (propertyDescriptions.isEmpty()) { return Collections.emptyList(); } List<Pair<String, String>> optionPropertiesHelp = new LinkedList<Pair<String, String>>(); for (final Pair<String, String> propertyDescription : propertyDescriptions) { String synopsis = propertyDescription.getKey(); if (StringUtils.isEmpty(synopsis)) { synopsis = "key"; } String details = propertyDescription.getValue(); if (StringUtils.isEmpty(details)) { details = String.format("An option property value for %s.", parserOption); } optionPropertiesHelp.add(ImmutablePair.of(synopsis, details)); } return optionPropertiesHelp; }
From source file:edu.sjsu.pokemonclassifier.classification.UserPreferenceInfo.java
public Map<String, Integer> getRecommendPokemon() { // API for downard module // Put all strongerCandidates to GMM model List<Pair<Integer, Double>> weightPairList = new ArrayList<>(); GaussianMixtureModel model = gmmTrainer.getModel(); for (int j = 0; j < model.getK(); j++) { weightPairList.add(Pair.of(j, model.weights()[j])); }/*from w ww .jav a 2 s . c o m*/ Collections.sort(weightPairList, new Comparator<Pair<Integer, Double>>() { @Override public int compare(Pair<Integer, Double> o1, Pair<Integer, Double> o2) { if (o1.getValue() < o2.getKey()) return -1; else if (o1.getValue().equals(o2.getValue())) return 0; else return 1; } }); // Get top-5 // 5 is temp number // <String, Interger> -> <PokemonName, Rank#> HashMap<String, Integer> rankedPokemon = new HashMap<String, Integer>(); HashMap<Integer, String> strongerCandidatesMap = new HashMap<Integer, String>(); for (String strongerCandidate : strongerCandidates) { strongerCandidatesMap.put(strongerCandidates.indexOf(strongerCandidate), strongerCandidate); } // for (int i = 0; i < strongerCandidates.size(); i++) { // // strongerCandidatesMap.put(i, strongerCandidates.get(i).toLowerCase()); // } // modified by sidmishraw for getting top 10 pokemons rather than 5 int totalClusters = Math.min(model.getK(), 10); int rank = 1; for (int i = totalClusters - 1; i >= 0; i--) { int modelIdx = weightPairList.get(i).getKey(); double[] meanVector = model.gaussians()[modelIdx].mean().toArray(); double att = meanVector[0]; double def = meanVector[1]; double hp = meanVector[2]; double minDist = Double.MAX_VALUE; int minIdx = 0; String bestFitName = null; for (int j = 0; j < strongerCandidatesMap.size(); j++) { String name = strongerCandidatesMap.get(j); if (name == null) { continue; } //name = name.toLowerCase(); System.out.println("HARMLESS:::: name = " + name); System.out.println("HARMLESS:::: att2 = " + PokemonDict.getInstance().getAttack(name)); System.out.println("HARMLESS:::: def2 = " + PokemonDict.getInstance().getDefense(name)); System.out.println("HARMLESS:::: hp2 = " + PokemonDict.getInstance().getHP(name)); int att2 = PokemonDict.getInstance().getAttack(name); int def2 = PokemonDict.getInstance().getDefense(name); int hp2 = PokemonDict.getInstance().getHP(name); double dist = Math .sqrt((att - att2) * (att - att2) + (def - def2) * (def - def2) + (hp - hp2) * (hp - hp2)); if (dist < minDist) { minDist = dist; minIdx = j; bestFitName = name; } } strongerCandidatesMap.remove(minIdx); rankedPokemon.put(bestFitName, rank); rank++; } return rankedPokemon; }
From source file:com.netflix.genie.agent.execution.services.impl.FetchingCacheServiceImpl.java
/** * {@inheritDoc}/*w w w . jav a2 s . c o m*/ */ @Override public void get(final Set<Pair<URI, File>> sourceDestinationPairs) throws DownloadException, IOException { for (final Pair<URI, File> sourceDestinationPair : sourceDestinationPairs) { get(sourceDestinationPair.getKey(), sourceDestinationPair.getValue()); } }