Java Examples for org.apache.commons.lang3.tuple.Pair
The following java examples will help you to understand the usage of org.apache.commons.lang3.tuple.Pair. These source code samples are taken from different open source projects.
Example 1
Project: geowave-master File: FilterToCQLToolTest.java View source code |
public void testFilter(Filter gtFilter) { final SimpleFeature newFeature = FeatureDataUtils.buildFeature(type, new Pair[] { Pair.of("geom", new GeometryFactory().createPoint(new Coordinate(-122.76570055844142, 0.4979))), Pair.of("pop", Long.valueOf(100)) }); assertTrue(gtFilter.evaluate(newFeature)); final SimpleFeature newFeatureToFail = FeatureDataUtils.buildFeature(type, new Pair[] { Pair.of("geom", new GeometryFactory().createPoint(new Coordinate(-122.7690, 0.4980))), Pair.of("pop", Long.valueOf(100)) }); assertFalse(gtFilter.evaluate(newFeatureToFail)); }
Example 2
Project: CoAnSys-master File: LocalSequenceFileUtils.java View source code |
//------------------------ LOGIC -------------------------- /** * Reads sequence file from local filesystem. * Passed file object can be single file or a directory * that contains sequence file splitted into parts (part-* files). * Sequence file must contain keys and values of types * specified as method parameters. */ public static <K extends Writable, V extends Writable> List<Pair<K, V>> readSequenceFile(File sequenceFile, Class<K> keyClass, Class<V> valueClass) throws IOException { if (sequenceFile.isFile()) { Path path = getAbsolutePath(sequenceFile); return readSequenceFile(path, keyClass, valueClass); } List<Pair<K, V>> records = Lists.newArrayList(); for (File f : FileUtils.listFiles(sequenceFile, null, true)) { if (f.isFile() && f.getName().startsWith("part-")) { Path path = getAbsolutePath(f); List<Pair<K, V>> singleFileRecords = readSequenceFile(path, keyClass, valueClass); records.addAll(singleFileRecords); } } return records; }
Example 3
Project: MorozParser-master File: XmlLexicon.java View source code |
public List<List<TypeString>> types(List<Pair<String, String>> sentence) { List<List<TypeString>> res = new ArrayList<List<TypeString>>(); for (Pair<String, String> word : sentence) { List<TypeString> l = mFromForm.get(word.getLeft()); if (l == null) { List<TypeString> l2 = mFromTag.get(word.getRight()); if (l2 == null) res.add(new ArrayList<TypeString>()); else res.add(l2); } else res.add(l); } return res; }
Example 4
Project: andFHEM-master File: OtherWidgetsAdapter.java View source code |
@Override @SuppressWarnings("unchecked") public View getView(int position, View view, ViewGroup parent) { Pair<WidgetType, String> item = (Pair<WidgetType, String>) getItem(position); if (view == null) { view = inflater.inflate(resource, null); } TextView textView = (TextView) view.findViewById(R.id.text); textView.setText(item.getValue()); view.setTag(item.getKey()); return view; }
Example 5
Project: aorra-master File: ManagementPracticeBuilder.java View source code |
@Override protected ADCDataset createDataset(Context ctx) { SpreadsheetDataSource ds = ctx.datasource(); Region region = ctx.region(); try { Region current = null; List<Pair<String, Double[]>> values = Lists.newArrayList(); for (int row = 1; !eof(row, ds); row++) { String r0 = ds.select(row, 0).asString(); if (StringUtils.isBlank(r0)) { if (values.isEmpty()) { continue; } else { break; } } if (Region.lookup(r0) != null) { current = Region.lookup(r0); continue; } if (current == region) { String year = r0; values.add(Pair.of(year, readRow(ds, row))); } } if (values.size() >= 2) { ADCDataset dataset = new ADCDataset(); for (Pair<String, Double[]> p : ImmutableList.of(values.get(0), values.get(values.size() - 1))) { addData(dataset, p.getLeft(), p.getRight()); } return dataset; } else { return null; } } catch (MissingDataException e) { throw new RuntimeException(e); } }
Example 6
Project: bhave.network-master File: NetworkModelUtils.java View source code |
/** * Considering all the possible links of an undirected network, we could * represent the links as an adjacency matrix (ignoring loops) such as: * * M = [ 01 02 03 04 ] [ 00 12 13 14 ] [ 00 00 23 24 ] [ 00 00 00 34 ] * * for a network with 5 nodes. * * This procedure transforms a linear index from a vector of possible edges: * * [ 01, 02, 03, 04, 12, 13, 14, 23, 24, 34 ] * * into the node IDS of the respective edge. * * For Instance, the index i=4 corresponds to the edge (1,2). The procedure * returns (1,2) without constructing a vector with all the links in the * network. * * @param index * the index of the link we want to retrieve 0 <= i < * Binomial(n,2) * @param numNodes * the number of nodes in the network * * @return a pair of IDS for the nodes in the link we want to retrieve. */ public static Pair<Integer, Integer> getLink(int index, int numNodes) { long maxI = numNodes - 1; long ii = (maxI * (maxI + 1) / 2) - 1 - index; double t = FastMath.sqrt(8 * ii + 1); long k = (long) FastMath.floor((t - 1) / 2); long row = maxI - 1 - k; double column = ((index + (row * (row + 1) / 2)) % maxI); int node1 = (int) row; int node2 = (int) (column + 1); return Pair.of(node1, node2); }
Example 7
Project: cas-master File: RadiusTokenAuthenticationHandler.java View source code |
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
try {
final RadiusTokenCredential radiusCredential = (RadiusTokenCredential) credential;
final String password = radiusCredential.getToken();
final RequestContext context = RequestContextHolder.getRequestContext();
final String username = WebUtils.getAuthentication(context).getPrincipal().getId();
final Pair<Boolean, Optional<Map<String, Object>>> result = RadiusUtils.authenticate(username, password, this.servers, this.failoverOnAuthenticationFailure, this.failoverOnException);
if (result.getKey()) {
return createHandlerResult(credential, this.principalFactory.createPrincipal(username, result.getValue().get()), new ArrayList<>());
}
throw new FailedLoginException("Radius authentication failed for user " + username);
} catch (final Exception e) {
throw new FailedLoginException("Radius authentication failed " + e.getMessage());
}
}
Example 8
Project: cattle-master File: AllocationCandidate.java View source code |
@SuppressWarnings("unchecked")
public <T> T loadResource(Class<T> clz, Long id) {
if (id == null) {
return null;
}
Pair<Class<?>, Long> key = new ImmutablePair<Class<?>, Long>(clz, id);
Object resource = resources.get(key);
if (resource == null) {
resource = objectManager.loadResource(clz, id);
resources.put(key, resource);
}
return (T) resource;
}
Example 9
Project: glados-wiki-master File: RecentsController.java View source code |
@ResponseBody
@RequestMapping(value = "/listRecents", produces = MediaType.APPLICATION_JSON_VALUE)
public PageContentVersionsResponse listRecents(@RequestParam(value = "offset", defaultValue = "0", required = false) final int offset, @RequestParam(value = "limit", defaultValue = "10", required = false) final int limit) {
//
Pair<Long, List<PageContent>> p = pageContentService.listRecents(offset, limit);
Long tot = p.getLeft();
Pagination pagination = new Pagination(tot, offset, limit);
TeeConsumeFunction<PageContent, PageContentResponse> f = new TeeConsumeFunction<PageContent, PageContentResponse>(new PageContentReadablePredicate(pageAclService), new PageContentToPageContentResponseFunction(), new EmptyPageContentFunction());
List<PageContentResponse> l2 = Lists.transform(p.getRight(), f);
//
return new PageContentVersionsResponse(pagination, l2);
}
Example 10
Project: olca-app-master File: Comparators.java View source code |
/** * Returns a new comparator for flow descriptors which sorts the flow * descriptors first by name and than by category. */ public static Comparator<FlowDescriptor> forFlowDescriptors(EntityCache cache) { return ( flow1, flow2) -> { int c = Strings.compare(flow1.getName(), flow2.getName()); if (c != 0) return c; Pair<String, String> cat1 = Labels.getCategory(flow1, cache); Pair<String, String> cat2 = Labels.getCategory(flow2, cache); c = Strings.compare(cat1.getLeft(), cat2.getLeft()); if (c != 0) return c; return Strings.compare(cat1.getRight(), cat2.getRight()); }; }
Example 11
Project: purepos-master File: GeneralizedLemmaTransformationTest.java View source code |
@Test @Ignore public void substringTest() { Assert.assertEquals(Pair.of(0, 2), GeneralizedLemmaTransformation.longestSubstring("alma", "alom")); Assert.assertEquals(Pair.of(0, 7), GeneralizedLemmaTransformation.longestSubstring("kÅ‘szÃvűbb", "kÅ‘szÃvű")); Assert.assertEquals(Pair.of(3, 1), GeneralizedLemmaTransformation.longestSubstring("legjobb", "jó")); Assert.assertEquals(Pair.of(3, 4), GeneralizedLemmaTransformation.longestSubstring("legokosabb", "okos")); Assert.assertEquals(Pair.of(1, 1), GeneralizedLemmaTransformation.longestSubstring("megesz", "enni")); }
Example 12
Project: RFTools-master File: OreTypeItemSorter.java View source code |
public static int compareOreType(Pair<ItemStack, Integer> o1, Pair<ItemStack, Integer> o2) { String oreName1 = getOreType(o1); String oreName2 = getOreType(o2); if (oreName1 == null) { if (oreName2 == null) { return NameItemSorter.compareNames(o1, o2); } else { return -1; } } if (oreName2 == null) { return 1; } if (oreName1.equals(oreName2)) { return NameItemSorter.compareNames(o1, o2); } return oreName1.compareTo(oreName2); }
Example 13
Project: Web-Karma-master File: PyTransformConsolidator.java View source code |
@Override
public Pair<ICommand, Object> consolidateCommand(List<ICommand> commands, ICommand newCommand, Workspace workspace) {
if (newCommand instanceof SubmitEditPythonTransformationCommand) {
Iterator<ICommand> itr = commands.iterator();
String model = newCommand.getModel();
while (itr.hasNext()) {
ICommand tmp = itr.next();
if (((Command) tmp).getOutputColumns().equals(((Command) newCommand).getOutputColumns()) && tmp instanceof SubmitPythonTransformationCommand && !(tmp instanceof SubmitEditPythonTransformationCommand) && model.equals(tmp.getModel())) {
SubmitPythonTransformationCommand py = (SubmitPythonTransformationCommand) tmp;
SubmitPythonTransformationCommand edit = (SubmitPythonTransformationCommand) newCommand;
JSONArray inputJSON = new JSONArray(py.getInputParameterJson());
JSONArray oldInputJSON = new JSONArray(py.getInputParameterJson());
HistoryJsonUtil.setArgumentValue("transformationCode", edit.getTransformationCode(), inputJSON);
py.setInputParameterJson(inputJSON.toString());
py.setTransformationCode(edit.getTransformationCode());
return new ImmutablePair<>(tmp, (Object) oldInputJSON);
}
}
}
return null;
}
Example 14
Project: apps-android-wikipedia-master File: ImageTagParser.java View source code |
@NonNull
private Map<PixelDensityDescriptor, String> parseSrcSet(@NonNull PixelDensityDescriptorParser descriptorParser, @Nullable String srcSet) {
if (StringUtils.isBlank(srcSet)) {
return Collections.emptyMap();
}
Map<PixelDensityDescriptor, String> srcs = new HashMap<>();
for (String src : srcSet.split(",")) {
try {
Pair<String, String> urlDescriptor = parseSrc(src.trim());
PixelDensityDescriptor descriptor = descriptorParser.parse(urlDescriptor.getRight());
srcs.put(descriptor, urlDescriptor.getLeft());
} catch (ParseException ignore) {
}
}
return Collections.unmodifiableMap(srcs);
}
Example 15
Project: Baragon-master File: BootstrapFileChecker.java View source code |
@Override public Optional<Pair<ServiceContext, Collection<BaragonConfigFile>>> call() { try { ServiceContext context = new ServiceContext(serviceState.getService(), serviceState.getUpstreams(), now, true); Optional<Collection<BaragonConfigFile>> maybeConfigsToApply = configHelper.configsToApply(context); if (maybeConfigsToApply.isPresent()) { Pair<ServiceContext, Collection<BaragonConfigFile>> configMap = new ImmutablePair<>(context, maybeConfigsToApply.get()); return Optional.of(configMap); } } catch (Exception e) { LOG.error(String.format("Caught exception while finding config for %s", serviceState.getService()), e); } LOG.info(String.format("Don't need to apply %s", serviceState.getService().getServiceId())); return Optional.absent(); }
Example 16
Project: bigtop-master File: RouletteWheelSampler.java View source code |
private ImmutableList<Pair<T, Double>> normalize(Map<T, Double> domainWeights) { double weightSum = 0.0; for (Map.Entry<T, Double> entry : domainWeights.entrySet()) { weightSum += entry.getValue(); } double cumProb = 0.0; ImmutableList.Builder<Pair<T, Double>> builder = ImmutableList.builder(); for (Map.Entry<T, Double> entry : domainWeights.entrySet()) { double prob = entry.getValue() / weightSum; cumProb += prob; builder.add(Pair.of(entry.getKey(), cumProb)); } return builder.build(); }
Example 17
Project: Botania-master File: LexiconModel.java View source code |
@Override public Pair<? extends IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) { IBakedModel original = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getModelManager().getModel(path); if ((cameraTransformType == ItemCameraTransforms.TransformType.FIRST_PERSON_RIGHT_HAND || cameraTransformType == ItemCameraTransforms.TransformType.FIRST_PERSON_LEFT_HAND) && ConfigHandler.lexicon3dModel) return Pair.of(this, null); return ((IPerspectiveAwareModel) original).handlePerspective(cameraTransformType); }
Example 18
Project: CardinalPGM-master File: CraftingModuleBuilder.java View source code |
private AbstractRecipe getShapedRecipe(Element element) {
ItemStack result = Parser.getItem(element.getChild("result"));
List<String> rows = new ArrayList<>();
for (Element row : element.getChild("shape").getChildren("row")) {
rows.add(row.getText());
}
Set<Pair<Character, MaterialData>> ingredients = new HashSet<>();
for (Element ingredient : getIngredientChilds(element)) {
ingredients.add(new ImmutablePair<>(ingredient.getAttributeValue("symbol").charAt(0), Parser.parseMaterialData(ingredient.getText())));
}
return new ShapedRecipe(result, rows.toArray(new String[rows.size()]), ingredients);
}
Example 19
Project: cloud-slang-master File: AbstractBinding.java View source code |
protected Value getEvalResultForMap(Value evalResult, LoopStatement loopStatement, String collectionExpression) {
if (loopStatement instanceof MapLoopStatement) {
if (evalResult != null && evalResult.get() instanceof Map) {
List<Value> entriesAsValues = new ArrayList<>();
@SuppressWarnings("unchecked") Set<Map.Entry<Serializable, Serializable>> entrySet = ((Map) evalResult.get()).entrySet();
for (Map.Entry<Serializable, Serializable> entry : entrySet) {
entriesAsValues.add(ValueFactory.create(Pair.of(ValueFactory.create(entry.getKey(), evalResult.isSensitive()), ValueFactory.create(entry.getValue(), evalResult.isSensitive()))));
}
evalResult = ValueFactory.create((Serializable) entriesAsValues);
} else {
throw new RuntimeException(LoopsBinding.INVALID_MAP_EXPRESSION_MESSAGE + ": " + collectionExpression);
}
}
return evalResult;
}
Example 20
Project: distributedlog-master File: TestDLMTestUtil.java View source code |
@Test(timeout = 60000) public void testRunZookeeperOnAnyPort() throws Exception { Pair<ZooKeeperServerShim, Integer> serverAndPort1 = null; Pair<ZooKeeperServerShim, Integer> serverAndPort2 = null; Pair<ZooKeeperServerShim, Integer> serverAndPort3 = null; try { File zkTmpDir1 = IOUtils.createTempDir("zookeeper1", "distrlog"); serverAndPort1 = LocalDLMEmulator.runZookeeperOnAnyPort(7000, zkTmpDir1); File zkTmpDir2 = IOUtils.createTempDir("zookeeper2", "distrlog"); serverAndPort2 = LocalDLMEmulator.runZookeeperOnAnyPort(7000, zkTmpDir2); File zkTmpDir3 = IOUtils.createTempDir("zookeeper3", "distrlog"); serverAndPort3 = LocalDLMEmulator.runZookeeperOnAnyPort(7000, zkTmpDir3); } catch (Exception ex) { if (null != serverAndPort1) { serverAndPort1.getLeft().stop(); } if (null != serverAndPort2) { serverAndPort2.getLeft().stop(); } if (null != serverAndPort3) { serverAndPort3.getLeft().stop(); } } }
Example 21
Project: elasticsearch-http-master File: Suggestions.java View source code |
/* parses something like (e.g. for sub aggs) "song-suggest": { "text": "n", "completion": { "field": "suggest" } } */ protected static Pair<String, XContentBuilder> parseInnerSuggestion(XContentParser parser, String aggregationName) { try { assert parser.currentToken() == START_OBJECT : "expected a START_OBJECT token but was " + parser.currentToken(); XContentBuilder docBuilder = XContentFactory.contentBuilder(XContentType.JSON); docBuilder.copyCurrentStructure(parser); docBuilder.close(); return Pair.of(aggregationName, docBuilder); } catch (IOException e) { throw new RuntimeException(e); } }
Example 22
Project: ethereumj-master File: PeerSource.java View source code |
@Override
public byte[] serialize(Pair<Node, Integer> value) {
byte[] nodeRlp = value.getLeft().getRLP();
byte[] nodeIsDiscovery = RLP.encodeByte(value.getLeft().isDiscoveryNode() ? (byte) 1 : 0);
byte[] savedReputation = RLP.encodeBigInteger(BigInteger.valueOf(value.getRight()));
return RLP.encodeList(nodeRlp, nodeIsDiscovery, savedReputation);
}
Example 23
Project: fitnesse-selenium-slim-master File: SeleniumLocatorParser.java View source code |
private By parseBy(String locator) {
if (StringUtils.isBlank(locator)) {
return new ByFocus();
}
Pair<String, String> prefixAndSelector = this.fitnesseMarkup.cleanAndParseKeyValue(locator, FitnesseMarkup.KEY_VALUE_SEPARATOR);
String prefix = prefixAndSelector.getKey();
String selector = prefixAndSelector.getValue();
LocatorType selectorType = EnumUtils.getEnum(LocatorType.class, prefix);
if (selectorType == null) {
selector = locator;
selectorType = LocatorType.xpath;
}
try {
return selectorType.byClass.getConstructor(String.class).newInstance(selector);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Unexpected failure instantiating selector: " + prefix, e);
}
}
Example 24
Project: Flaxbeards-Steam-Power-master File: ItemCalamityInjectorUpgrade.java View source code |
@Override
public boolean onBlockBreakWithTool(BlockEvent.BreakEvent event, @Nonnull ItemStack toolStack, @Nonnull ItemStack thisUpgradeStack) {
EntityPlayer player = event.getPlayer();
BlockPos pos = event.getPos();
SteamChargable drill = (SteamChargable) toolStack.getItem();
World world = player.worldObj;
Random rand = world.rand;
drill.addSteam(toolStack, -(2 * drill.steamPerDurability()), player);
if (world.getDifficulty() == EnumDifficulty.HARD && rand.nextInt(100) < 15) {
return true;
}
int max = 0;
int min = 0;
int constant = 0;
boolean useConstant = false;
switch(player.worldObj.getDifficulty()) {
case HARD:
{
max = HARD_CHARGE_CAP;
min = HARD_CHARGE_MIN;
break;
}
case NORMAL:
{
max = NORMAL_CHARGE_CAP;
min = NORMAL_CHARGE_MIN;
break;
}
case EASY:
{
max = EASY_CHARGE_CAP;
min = EASY_CHARGE_MIN;
break;
}
case PEACEFUL:
{
constant = PEACEFUL_CHARGE;
useConstant = true;
break;
}
default:
{
}
}
charges.put(Pair.of(player, pos), useConstant ? constant : rand.nextInt((max - min) + 1) + min);
return true;
}
Example 25
Project: galen-master File: SpecComponentProcessor.java View source code |
@Override
public Spec process(StringCharReader reader, String contextPath) {
SpecComponent spec = new SpecComponent();
int initialPosition = reader.currentCursorPosition();
if (reader.readWord().equals("frame")) {
spec.setFrame(true);
} else {
reader.moveCursorTo(initialPosition);
}
String filePath = reader.readSafeUntilSymbol(',').trim();
List<Pair<String, String>> unprocessedArguments = Expectations.commaSeparatedRepeatedKeyValues().read(reader);
spec.setArguments(processArguments(unprocessedArguments));
if (contextPath != null && !contextPath.equals(".")) {
filePath = contextPath + File.separator + filePath;
}
spec.setSpecPath(filePath);
return spec;
}
Example 26
Project: Harvest-Festival-master File: FishingHelper.java View source code |
private static Pair<Season, WaterType> getLocation(World world, BlockPos pos) { Season season = HFApi.calendar.getDate(world).getSeason(); TownData data = TownHelper.getClosestTownToBlockPos(world, pos, false); BlockPos position = data.getCoordinatesFor(BuildingLocations.FISHING_POND_CENTRE); WaterType type; if (position != null && position.getDistance(pos.getX(), pos.getY(), pos.getZ()) <= 5) { type = WaterType.POND; } else { Biome biome = world.getBiome(pos); if (BiomeDictionary.isBiomeOfType(biome, Type.OCEAN)) type = WaterType.OCEAN; else if (BiomeDictionary.isBiomeOfType(biome, Type.RIVER)) type = WaterType.RIVER; else type = WaterType.LAKE; } return Pair.of(season, type); }
Example 27
Project: hyracks-master File: RegisterPartitionRequestWork.java View source code |
@Override
public void run() {
PartitionId pid = partitionRequest.getPartitionId();
JobRun run = ccs.getActiveRunMap().get(pid.getJobId());
if (run == null) {
return;
}
PartitionMatchMaker pmm = run.getPartitionMatchMaker();
Pair<PartitionDescriptor, PartitionRequest> match = pmm.matchPartitionRequest(partitionRequest);
if (match != null) {
try {
PartitionUtils.reportPartitionMatch(ccs, pid, match);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example 28
Project: hystrix-monitor-master File: HystrixMonitor.java View source code |
@PostConstruct public void subscribeToHystrixStream() { ObservableHttp.createGet("http://localhost:6543/hystrix.stream", httpAsyncClient).toObservable().flatMap( response -> response.getContent().map(String::new)).filter( hystrixEvent -> hystrixEvent.startsWith("data:")).filter( data -> data.contains("isCircuitBreakerOpen")).map( data -> data.substring("data:".length())).map( data -> JsonPath.from(data).getBoolean("isCircuitBreakerOpen")).map( isCircuitBreakerCurrentlyOpened -> Pair.of(isCircuitBreakerCurrentlyOpened, monitoringSystem.isCircuitBreakerOpened())).filter( pair -> pair.getLeft() != pair.getRight()).map(Pair::getLeft).doOnNext( isCircuitBreakerOpened -> { if (isCircuitBreakerOpened) { monitoringSystem.reportCircuitBreakerOpened(); } else { monitoringSystem.reportCircuitBreakerClosed(); } }).doOnError( throwable -> log.error("Error", throwable)).subscribe(); }
Example 29
Project: incubator-asterixdb-hyracks-master File: RegisterPartitionRequestWork.java View source code |
@Override
public void run() {
PartitionId pid = partitionRequest.getPartitionId();
JobRun run = ccs.getActiveRunMap().get(pid.getJobId());
if (run == null) {
return;
}
PartitionMatchMaker pmm = run.getPartitionMatchMaker();
Pair<PartitionDescriptor, PartitionRequest> match = pmm.matchPartitionRequest(partitionRequest);
if (match != null) {
try {
PartitionUtils.reportPartitionMatch(ccs, pid, match);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example 30
Project: incubator-asterixdb-master File: RegisterPartitionRequestWork.java View source code |
@Override
public void run() {
PartitionId pid = partitionRequest.getPartitionId();
JobRun run = ccs.getActiveRunMap().get(pid.getJobId());
if (run == null) {
return;
}
PartitionMatchMaker pmm = run.getPartitionMatchMaker();
Pair<PartitionDescriptor, PartitionRequest> match = pmm.matchPartitionRequest(partitionRequest);
if (match != null) {
try {
PartitionUtils.reportPartitionMatch(ccs, pid, match);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example 31
Project: jpa-utils-master File: MemoryCache.java View source code |
@Override
public V get(K key) {
Pair<V, Long> pair = cache.get(key);
if (pair == null) {
return null;
}
if (pair.getRight() < 0) {
return pair.getLeft();
}
Date date = new Date(pair.getRight());
if (date.before(new Date())) {
return null;
} else {
return pair.getLeft();
}
}
Example 32
Project: libmythtv-java-master File: Command71QueryRemoteEncoderIsBusy.java View source code |
@Override protected Pair<Boolean, TunedInputInfo> parseResponse(String response) throws ProtocolException, CommandException { List<String> args = getParser().splitArguments(response); if (args.size() != 8) { throw new ProtocolException(response, Direction.RECEIVE); } boolean busy; if ("0".equals(args.get(0))) { busy = false; } else if ("1".equals(args.get(0))) { busy = true; } else { throw new ProtocolException(response, Direction.RECEIVE); } try { int i = 1; TunedInputInfo inputInfo = new TunedInputInfo(args.get(i++), Integer.parseInt(args.get(i++)), Integer.parseInt(args.get(i++)), Integer.parseInt(args.get(i++)), Integer.parseInt(args.get(i++)), Integer.parseInt(args.get(i++)), Integer.parseInt(args.get(i++))); return Pair.of(busy, inputInfo); } catch (NumberFormatException e) { throw new ProtocolException(response, Direction.RECEIVE, e); } }
Example 33
Project: liferay-cli-master File: PairListTest.java View source code |
@SuppressWarnings("unchecked")
@Test
public void testConstructFromVarargArrayOfPairs() {
// Invoke
final PairList<Integer, String> pairs = new PairList<Integer, String>(PAIR_1, PAIR_2);
// Check
assertEquals(2, pairs.size());
assertEquals(Arrays.asList(KEY_1, KEY_2), pairs.getKeys());
assertEquals(Arrays.asList(VALUE_1, VALUE_2), pairs.getValues());
final Pair<Integer, String>[] array = pairs.toArray();
assertEquals(pairs.size(), array.length);
assertEquals(pairs, Arrays.asList(array));
}
Example 34
Project: MissingBot-master File: AirpediaPropertyMapping.java View source code |
public String buildPropertyMapping() {
String property_txt = "";
for (Pair<String, String> prop : properties) {
String template_property = prop.getLeft();
String ontology_property = prop.getRight();
// check if property (template_property) exists
if (!this.getText().contains(template_property)) {
property_txt += String.format(property_template, template_property, ontology_property);
}
}
return property_txt;
}
Example 35
Project: OC-Minecarts-master File: ComputerCartT4Template.java View source code |
public static Iterable<Pair<String, Integer>> getComponentSlots() { ArrayList<Pair<String, Integer>> list = new ArrayList<Pair<String, Integer>>(); list.add(Pair.of(Slot.Card, 2)); list.add(Pair.of(Slot.Card, 2)); list.add(Pair.of(Slot.Card, 2)); list.add(Pair.of(Slot.CPU, 2)); list.add(Pair.of(Slot.Memory, 2)); list.add(Pair.of(Slot.Memory, 2)); list.add(Pair.of("eeprom", Tier.Any())); list.add(Pair.of(Slot.HDD, 2)); return list; }
Example 36
Project: OpenModsLib-master File: TypedValueParser.java View source code |
public static TypedValue mergeNumberParts(TypeDomain domain, Pair<BigInteger, Double> result) {
final BigInteger intPart = result.getLeft();
final Double fractionPart = result.getRight();
if (fractionPart == null)
return domain.create(BigInteger.class, intPart);
final double total = intPart.doubleValue() + fractionPart;
return domain.create(Double.class, total);
}
Example 37
Project: ORCID-Source-master File: PasswordResetToken.java View source code |
/** * * @return The params encoded as a single string, as if in a URL query. The string is not url encoded because will * be encrypted by a manager first. email=?&gNames=?&fName=?&sponsor=?&identifier=?&institution=? */ public String toParamsString() { List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>(); pairs.add(new ImmutablePair<String, String>(EMAIL_PARAM_KEY, email)); pairs.add(new ImmutablePair<String, String>(ISSUE_DATE_PARAM_KEY, String.valueOf(issueDate))); List<String> items = new ArrayList<String>(pairs.size()); for (Pair<String, String> pair : pairs) { items.add(pair.getLeft() + EQUALS + NullUtils.blankIfNull(pair.getRight())); } return StringUtils.join(items, SEPARATOR); }
Example 38
Project: PUMA-master File: SingleReadIndexManager.java View source code |
@Override public V find(K indexKey) throws IOException { checkStop(); byte[] data; Pair<K, V> oldPair = null; try { while (true) { data = readBucket.next(); if (data != null) { Pair<K, V> pair = decode(data); if (!greater(indexKey, pair.getLeft())) { if (oldPair == null) { throw new IOException("failed to find."); } else { return oldPair.getRight(); } } else { oldPair = pair; } } } } catch (EOFException eof) { if (oldPair == null) { throw new IOException("failed to find."); } else { return oldPair.getRight(); } } }
Example 39
Project: spring-roo-custom-master File: PairListTest.java View source code |
@SuppressWarnings("unchecked")
@Test
public void testConstructFromVarargArrayOfPairs() {
// Invoke
final PairList<Integer, String> pairs = new PairList<Integer, String>(PAIR_1, PAIR_2);
// Check
assertEquals(2, pairs.size());
assertEquals(Arrays.asList(KEY_1, KEY_2), pairs.getKeys());
assertEquals(Arrays.asList(VALUE_1, VALUE_2), pairs.getValues());
final Pair<Integer, String>[] array = pairs.toArray();
assertEquals(pairs.size(), array.length);
assertEquals(pairs, Arrays.asList(array));
}
Example 40
Project: spring-roo-master File: PairListTest.java View source code |
@SuppressWarnings("unchecked")
@Test
public void testConstructFromVarargArrayOfPairs() {
// Invoke
final PairList<Integer, String> pairs = new PairList<Integer, String>(PAIR_1, PAIR_2);
// Check
assertEquals(2, pairs.size());
assertEquals(Arrays.asList(KEY_1, KEY_2), pairs.getKeys());
assertEquals(Arrays.asList(VALUE_1, VALUE_2), pairs.getValues());
final Pair<Integer, String>[] array = pairs.toArray();
assertEquals(pairs.size(), array.length);
assertEquals(pairs, Arrays.asList(array));
}
Example 41
Project: StorageDrawers-master File: ItemTrim.java View source code |
@Override public List<Pair<ItemStack, ModelResourceLocation>> getMeshMappings() { List<Pair<ItemStack, ModelResourceLocation>> mappings = new ArrayList<Pair<ItemStack, ModelResourceLocation>>(); for (BlockPlanks.EnumType woodType : BlockPlanks.EnumType.values()) { IBlockState state = block.getDefaultState().withProperty(BlockTrim.VARIANT, woodType); ModelResourceLocation location = new ModelResourceLocation(ModBlocks.trim.getRegistryName().toString() + '_' + woodType.getName(), "inventory"); mappings.add(Pair.of(new ItemStack(this, 1, block.getMetaFromState(state)), location)); } return mappings; }
Example 42
Project: syncope-master File: SuspendProducer.java View source code |
@SuppressWarnings("unchecked") @Override public void process(final Exchange exchange) throws Exception { if (getAnyTypeKind() == AnyTypeKind.USER) { Pair<WorkflowResult<String>, Boolean> updated = (Pair<WorkflowResult<String>, Boolean>) exchange.getIn().getBody(); // propagate suspension if and only if it is required by policy if (updated != null && updated.getValue()) { UserPatch userPatch = new UserPatch(); userPatch.setKey(updated.getKey().getResult()); List<PropagationTask> tasks = getPropagationManager().getUserUpdateTasks(new WorkflowResult<Pair<UserPatch, Boolean>>(new ImmutablePair<>(userPatch, Boolean.FALSE), updated.getKey().getPropByRes(), updated.getKey().getPerformedTasks())); getPropagationTaskExecutor().execute(tasks); } } }
Example 43
Project: uncc2014watsonsim-master File: ApproxStringIntMapTest.java View source code |
@Test public void testIterator() { asim.put("moo", 1); asim.put("far", 2); Iterator<Pair<String, Integer>> pairs = asim.iterator(); assertTrue(pairs.hasNext()); assertEquals(Pair.of("moo", 1), pairs.next()); assertTrue(pairs.hasNext()); assertEquals(Pair.of("far", 2), pairs.next()); assertFalse(pairs.hasNext()); }
Example 44
Project: wikibrain-master File: TestObjectDb.java View source code |
@Test
public void testIterate() throws ConfigurationException, IOException, DatabaseException, ClassNotFoundException {
ObjectDb<Integer> db = getObjectDb();
db.put("foo", 324);
db.put("bar", 11);
db.put("foo", 24);
db.put("asdfasdf", 24);
db.put("zab", 26);
db.remove("asdfasdf");
Map<String, Integer> iteratedMap = new HashMap<String, Integer>();
for (Pair<String, Integer> pair : db) {
iteratedMap.put(pair.getKey(), pair.getValue());
}
Map<String, Integer> expectedMap = new HashMap<String, Integer>();
expectedMap.put("bar", 11);
expectedMap.put("foo", 24);
expectedMap.put("zab", 26);
assertEquals(iteratedMap, expectedMap);
}
Example 45
Project: AcademyCraft-master File: TutorialRegistry.java View source code |
/** * Get two list of tutorials, one is the set of learned, another the set of unlearned. */ public static Pair<List<ACTutorial>, List<ACTutorial>> groupByLearned(EntityPlayer player) { List<ACTutorial> learned = new ArrayList<>(); List<ACTutorial> unlearned = new ArrayList<>(); for (ACTutorial tut : tutorials.values()) { if (tut.isActivated(player)) { learned.add(tut); } else { unlearned.add(tut); } } return Pair.of(learned, unlearned); }
Example 46
Project: act-master File: MassCalculator2Test.java View source code |
@Test
public void testMC2MatchesMC1WithinMeaningfulTolerance() throws Exception {
List<Map<String, String>> rows;
try (InputStream is = MassCalculator2Test.class.getResourceAsStream(TEST_CASE_RESOURCE)) {
TSVParser parser = new TSVParser();
parser.parse(is);
rows = parser.getResults();
}
int testCase = 1;
for (Map<String, String> row : rows) {
String inchi = row.get("InChI");
Double expectedMass = Double.valueOf(row.get("Mass"));
Integer expectedCharge = Integer.valueOf(row.get("Charge"));
Pair<Double, Integer> actualMassAndCharge = MassCalculator2.calculateMassAndCharge(inchi);
Double threshold = ACCEPTABLE_MASS_DELTA_THRESHOLD;
if (actualMassAndCharge.getRight() < 0) {
// Widen the window for added electrons' masses included in Chemaxon's calculations for negative ions.
threshold += ACCEPTABLE_MASS_DELTA_THRESHOLD * -1.0 * actualMassAndCharge.getRight().doubleValue();
} else if (actualMassAndCharge.getRight() > 0) {
// Positively charged molecules have the missing electrons' masses subtracted
threshold += ACCEPTABLE_MASS_DELTA_THRESHOLD * actualMassAndCharge.getRight().doubleValue();
}
assertEquals(String.format("Case %d: mass for %s is within delta threshold: %.6f vs. %.6f", testCase, inchi, expectedMass, actualMassAndCharge.getLeft()), expectedMass, actualMassAndCharge.getLeft(), threshold);
assertEquals(String.format("Case %d: charge %s matches expected", testCase, inchi), expectedCharge, actualMassAndCharge.getRight());
testCase++;
}
}
Example 47
Project: alf.io-master File: DefaultLocationManager.java View source code |
@Override @Cacheable public Pair<String, String> geocode(String address) { return Optional.ofNullable(GeocodingApi.geocode(getApiContext(), address).awaitIgnoreError()).filter( r -> r.length > 0).map( r -> r[0].geometry.location).map( l -> Pair.of(Double.toString(l.lat), Double.toString(l.lng))).orElseThrow(() -> new LocationNotFound("No location found for address " + address)); }
Example 48
Project: alluxio-master File: WebInterfaceConfigurationServlet.java View source code |
private SortedSet<Pair<String, String>> getSortedProperties() { TreeSet<Pair<String, String>> rtn = new TreeSet<>(); for (Map.Entry<String, String> entry : Configuration.toMap().entrySet()) { String key = entry.getKey(); if (key.startsWith(ALLUXIO_CONF_PREFIX) && !ALLUXIO_CONF_EXCLUDES.contains(key)) { rtn.add(new ImmutablePair<>(key, Configuration.get(PropertyKey.fromString(key)))); } } return rtn; }
Example 49
Project: Applied-Energistics-2-master File: ItemRenderable.java View source code |
@Override
public void renderTileEntityAt(T te, double x, double y, double z, float partialTicks, int destroyStage) {
Pair<ItemStack, Matrix4f> pair = f.apply(te);
if (pair != null && pair.getLeft() != null) {
GlStateManager.pushMatrix();
if (pair.getRight() != null) {
FloatBuffer matrix = BufferUtils.createFloatBuffer(16);
pair.getRight().store(matrix);
matrix.flip();
GlStateManager.multMatrix(matrix);
}
Minecraft.getMinecraft().getRenderItem().renderItem(pair.getLeft(), TransformType.GROUND);
GlStateManager.popMatrix();
}
}
Example 50
Project: asta4d-master File: FieldRenderBuilder.java View source code |
public Renderer toRenderer(boolean forEdit) {
Renderer renderer = Renderer.create();
for (FormFieldPrepareRenderer prepare : prepareList) {
String fieldName = ((SimpleFormFieldPrepareRenderer) prepare).getGivenFieldName();
renderer.add(prepare.preRender(editSelector(fieldName), displaySelector(fieldName)));
}
FormFieldValueRenderer valueRenderer;
try {
valueRenderer = valueRenderCls.newInstance();
for (Pair<String, Object> value : valueList) {
String edit = editSelector(value.getKey());
String display = displaySelector(value.getKey());
renderer.add(forEdit ? valueRenderer.renderForEdit(edit, value.getValue()) : valueRenderer.renderForDisplay(edit, display, value.getValue()));
}
} catch (InstantiationExceptionIllegalAccessException | e) {
throw new RuntimeException(e);
}
for (FormFieldPrepareRenderer prepare : prepareList) {
String fieldName = ((SimpleFormFieldPrepareRenderer) prepare).getGivenFieldName();
renderer.add(prepare.postRender(editSelector(fieldName), displaySelector(fieldName)));
}
return renderer;
}
Example 51
Project: avenir-master File: FeaturePosterior.java View source code |
/** * @param featureValues * @return */ public double getFeaturePostProb(List<Pair<Integer, Object>> featureValues) { double prob = 1.0; for (Pair<Integer, Object> feature : featureValues) { FeatureCount feaCount = getFeatureCount(feature.getLeft()); if (feature.getRight() instanceof String) { //categorical or binned numerical prob *= feaCount.getProb((String) feature.getRight()); } else { //continuous numerical prob *= feaCount.getProb((Integer) feature.getRight()); } } return prob; }
Example 52
Project: awe-core-master File: RenderHandler.java View source code |
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
final ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
if (selection instanceof IStructuredSelection) {
final Pair<IRenderableModel, Iterable<IDataElement>> mapSelection = RenderMenuUtils.getLocationElements((IStructuredSelection) selection);
if (mapSelection != null) {
if (mapSelection.getRight() == null) {
showModelOnMap(mapSelection.getLeft());
} else {
showElementsOnMap(mapSelection.getLeft(), mapSelection.getRight());
}
}
}
return null;
}
Example 53
Project: blogix-master File: ExporterAccTest.java View source code |
@Test
public void shouldLoadTestRequestSamples() throws IOException, URISyntaxException {
List<Pair<String, String>> checks = RequestSampleParser.loadRequestChecksFromFile(new File(getClass().getResource("/exported-samples.txt").toURI()));
assertThat(checks.size(), is(9));
assertThat(checks.get(0).getLeft(), is("/index.html"));
assertThat(checks.get(1).getLeft(), is("/help/index.html"));
assertThat(checks.get(2).getLeft(), is("/article/123/2012-01-12/index.html"));
assertThat(checks.get(3).getLeft(), is("/article/1/2012-01-13/index.html"));
assertThat(checks.get(4).getLeft(), is("/file/someFile.txt"));
assertThat(checks.get(5).getLeft(), is("/no-tile/index.html"));
assertThat(checks.get(6).getLeft(), is("/file/customView.txt"));
assertThat(checks.get(7).getLeft(), is("/file/customFile.txt"));
assertThat(checks.get(8).getLeft(), is("/someFile.txt"));
}
Example 54
Project: cassandra-hadoop-2-master File: TestMultiRowIterator.java View source code |
@Test public void testGroupByOneColumn() { ConfigHelper.setInputCqlQuery(mConf, CqlQuerySpec.builder().withKeyspace(KEYSPACE).withTable(TABLE_LOGOS).build()); ResultSet resultSet = mSession.execute(String.format("SELECT * from %s.%s", KEYSPACE, TABLE_LOGOS)); List<ResultSet> resultSets = Lists.newArrayList(); resultSets.add(resultSet); List<Pair<String, DataType>> columns = Lists.newArrayList(); columns.add(Pair.of(COL_STATE, DataType.text())); MultiRowIterator multiRowIterator = new MultiRowIterator(resultSets, columns); assertTrue(multiRowIterator.hasNext()); // We are grouping by state, so we should get one set of rows for CA, DC, IL, TX. List<List<Row>> rowsByState = Lists.newArrayList(multiRowIterator); assertEquals(4, rowsByState.size()); for (List<Row> rowsForOneState : rowsByState) { String state = rowsForOneState.get(0).getString(COL_STATE); if (state.equals("CA") || state.equals("TX")) { assertEquals(3, rowsForOneState.size()); } else if (state.equals("DC") || state.equals("IL")) { assertEquals(1, rowsForOneState.size()); } else { assertFalse(true); } } }
Example 55
Project: cgeo-master File: HtmlUtils.java View source code |
/** * Extract the text from a HTML based string. This is similar to what HTML.fromHtml(...) does, but this method also * removes the embedded images instead of replacing them by a small rectangular representation character. * */ @NonNull public static String extractText(final CharSequence html) { if (StringUtils.isBlank(html)) { return StringUtils.EMPTY; } String result = html.toString(); // recognize images in textview HTML contents if (html instanceof Spanned) { final Spanned text = (Spanned) html; final Object[] styles = text.getSpans(0, text.length(), Object.class); final List<Pair<Integer, Integer>> removals = new ArrayList<>(); for (final Object style : styles) { if (style instanceof ImageSpan) { final int start = text.getSpanStart(style); final int end = text.getSpanEnd(style); removals.add(Pair.of(start, end)); } } // sort reversed and delete image spans Collections.sort(removals, new Comparator<Pair<Integer, Integer>>() { @Override public int compare(final Pair<Integer, Integer> lhs, final Pair<Integer, Integer> rhs) { return rhs.getRight().compareTo(lhs.getRight()); } }); result = text.toString(); for (final Pair<Integer, Integer> removal : removals) { result = result.substring(0, removal.getLeft()) + result.substring(removal.getRight()); } } // now that images are gone, do a normal html to text conversion return Html.fromHtml(result).toString().trim(); }
Example 56
Project: clouck-master File: AbstractEc2Comparator.java View source code |
protected void compareTags(Collection<Event> result, List<Tag> oldTags, List<Tag> newTags, R oldResource, R newResource) {
CompareResult<Tag> compareResult = resourceUtil.compareTags(oldTags, newTags);
for (Tag tag : compareResult.getAdd()) {
result.add(createEvent(oldResource, newResource, EventType.Tag_Add, tag.getKey(), tag.getValue()));
}
for (Pair<Tag, Tag> pair : compareResult.getUpdate()) {
result.add(createEvent(oldResource, newResource, EventType.Tag_Update, pair.getLeft().getKey(), pair.getLeft().getValue(), pair.getRight().getValue()));
}
for (Tag tag : compareResult.getDelete()) {
result.add(createEvent(oldResource, newResource, EventType.Tag_Delete, tag.getKey(), tag.getValue()));
}
}
Example 57
Project: components-ness-jackson-master File: CommonsLang3SerializerTest.java View source code |
@Test public void testEntryCrossover() throws IOException { Entry<String, Boolean> pair = Maps.immutableEntry("foo", true); Pair<String, Boolean> newPair = mapper.readValue(mapper.writeValueAsBytes(pair), new TypeReference<Pair<String, Boolean>>() { }); assertEquals(pair.getKey(), newPair.getKey()); assertEquals(pair.getValue(), newPair.getValue()); pair = mapper.readValue(mapper.writeValueAsBytes(newPair), new TypeReference<Entry<String, Boolean>>() { }); assertEquals(newPair.getKey(), pair.getKey()); assertEquals(newPair.getValue(), pair.getValue()); }
Example 58
Project: ddf-master File: TestQueryUpdateSubscriberList.java View source code |
@Test
public void testNotify() {
QueryUpdateSubscriber childSubscriber = mock(QueryUpdateSubscriber.class);
QueryUpdateSubscriberList queryUpdateSubscriberList = new QueryUpdateSubscriberList(Collections.singletonList(childSubscriber));
Map<String, Pair<WorkspaceMetacardImpl, Long>> workspaceMetacardMap = Collections.emptyMap();
queryUpdateSubscriberList.notify(workspaceMetacardMap);
verify(childSubscriber).notify(workspaceMetacardMap);
}
Example 59
Project: DeepResonance-master File: WorldTickHandler.java View source code |
@SubscribeEvent public void tickEnd(TickEvent.WorldTickEvent event) { if (event.side != Side.SERVER) { return; } World world = event.world; int dim = WorldHelper.getDimID(world); if (event.phase == TickEvent.Phase.END) { ArrayDeque<RetroChunkCoord> chunks = chunksToGen.get(dim); if (chunks != null && !chunks.isEmpty()) { RetroChunkCoord r = chunks.pollFirst(); Pair<Integer, Integer> c = r.coord; // Logging.log("Retrogen " + c.toString() + "."); long worldSeed = world.getSeed(); Random rand = new Random(worldSeed); long xSeed = rand.nextLong() >> 2 + 1L; long zSeed = rand.nextLong() >> 2 + 1L; rand.setSeed(xSeed * c.getLeft() + zSeed * c.getRight() ^ worldSeed); DeepWorldGenerator.instance.generateWorld(rand, r.coord.getLeft(), r.coord.getRight(), world, false); chunksToGen.put(dim, chunks); } else if (chunks != null) { chunksToGen.remove(dim); } } else { Deque<Pair<Integer, Integer>> chunks = chunksToPreGen.get(dim); if (chunks != null && !chunks.isEmpty()) { Pair<Integer, Integer> c = chunks.pollFirst(); // Logging.log("Pregen " + c.toString() + "."); world.getChunkFromChunkCoords(c.getLeft(), c.getRight()); } else if (chunks != null) { chunksToPreGen.remove(dim); } } }
Example 60
Project: disunity-master File: BundleInfo.java View source code |
private Table<Integer, Integer, Object> buildHeaderTable(BundleHeader header) { TableBuilder table = new TableBuilder(); table.row("Field", "Value"); table.row("signature", header.signature()); table.row("streamVersion", header.streamVersion()); table.row("unityVersion", header.unityVersion()); table.row("unityRevision", header.unityRevision()); table.row("minimumStreamedBytes", header.minimumStreamedBytes()); table.row("headerSize", header.headerSize()); table.row("numberOfLevelsToDownload", header.numberOfLevelsToDownload()); table.row("numberOfLevels", header.numberOfLevels()); List<Pair<Long, Long>> levelByteEnds = header.levelByteEnd(); for (int i = 0; i < levelByteEnds.size(); i++) { Pair<Long, Long> levelByteEnd = levelByteEnds.get(i); table.row("levelByteEnd[" + i + "][0]", levelByteEnd.getLeft()); table.row("levelByteEnd[" + i + "][1]", levelByteEnd.getRight()); } if (header.streamVersion() >= 2) { table.row("completeFileSize", header.completeFileSize()); } if (header.streamVersion() >= 3) { table.row("dataHeaderSize", header.dataHeaderSize()); } return table.get(); }
Example 61
Project: drill-master File: Checker.java View source code |
public static Checker getChecker(int min, int max) { final Pair<Integer, Integer> range = Pair.of(min, max); if (checkerMap.containsKey(range)) { return checkerMap.get(range); } final Checker newChecker; if (min == max) { newChecker = new Checker(min); } else { newChecker = new Checker(min, max); } checkerMap.put(range, newChecker); return newChecker; }
Example 62
Project: eav-model-pattern-master File: ValueMatchAttributeSpecification.java View source code |
@Override
public boolean isSafisfiedBy(final Pair<? extends AbstractValue<?>, Attribute> arg) {
final Boolean[] bag = new Boolean[1];
arg.getLeft().accept(new ValueVisitor() {
private boolean checkDataType(Type type) {
return arg.getRight().getDataType().getType() == type;
}
private boolean checkDictionary(Dictionary left, Dictionary right) {
return left.getIdentifier().equals(right.getIdentifier());
}
@Override
public void visit(DateValue value) {
bag[0] = checkDataType(Type.DATE);
}
@Override
public void visit(DictionaryEntryValue value) {
bag[0] = checkDataType(Type.DICTIONARY);
bag[0] &= checkDictionary(value.getValue().getDictionary(), arg.getRight().getDataType().getDictionary());
}
@Override
public void visit(DoubleValue value) {
bag[0] = checkDataType(Type.DOUBLE);
}
@Override
public void visit(IntegerValue value) {
bag[0] = checkDataType(Type.INTEGER);
}
@Override
public void visit(BooleanValue value) {
bag[0] = checkDataType(Type.BOOLEAN);
}
@Override
public void visit(StringValue value) {
bag[0] = checkDataType(Type.TEXT);
}
});
return bag[0] == null ? false : bag[0];
}
Example 63
Project: grapht-master File: UnresolvableDependencyException.java View source code |
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder("Unable to satisfy desire ").append(format(desires.getCurrentDesire().getInjectionPoint()));
List<Pair<Satisfaction, InjectionPoint>> path = context;
if (!path.isEmpty()) {
sb.append(" of ").append(path.get(0).getLeft());
}
sb.append('\n').append(format(context, desires));
return sb.toString();
}
Example 64
Project: jMetal-master File: SetCoverage.java View source code |
@Override public Pair<Double, Double> evaluate(Pair<List<? extends Solution<?>>, List<? extends Solution<?>>> pairOfSolutionLists) { List<? extends Solution<?>> front1 = pairOfSolutionLists.getLeft(); List<? extends Solution<?>> front2 = pairOfSolutionLists.getRight(); if (front1 == null) { throw new JMetalException("The first front is null"); } else if (front2 == null) { throw new JMetalException("The second front is null"); } return new ImmutablePair<>(evaluate(front1, front2), evaluate(front2, front1)); }
Example 65
Project: Mariculture-master File: ASMHelper.java View source code |
public static Pair<MethodNode, ObfType> getMethodAndObfType(ClassNode node, String... methodAndDescription) { for (int i = 0; i < methodAndDescription.length; i += 2) { String name = methodAndDescription[i]; String desc = methodAndDescription[i + 1]; for (MethodNode method : node.methods) { if (method.name.equals(name) && method.desc.equals(desc)) { if (i == 0) return Pair.of(method, ObfType.NAMED); else if (i == 2) return Pair.of(method, ObfType.FUNC); else if (i == 4) return Pair.of(method, ObfType.NOTCH); } } } return null; }
Example 66
Project: Mekanism-master File: CTMRegistry.java View source code |
@SubscribeEvent
public void onModelBake(ModelBakeEvent event) throws Exception {
IModel model = ModelLoaderRegistry.getModel(baseResource);
baseModel = model.bake(new TRSRTransformation(ModelRotation.X0_Y0), Attributes.DEFAULT_BAKED_FORMAT, r -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(r.toString()));
for (Pair<String, String> pair : ctmTypes) {
ModelCTM chiselModel = new ModelCTM(baseModel, pair.getRight());
chiselModel.load();
event.getModelRegistry().putObject(new ModelResourceLocation(pair.getLeft() + ":" + pair.getRight()), new CTMModelFactory(chiselModel));
}
}
Example 67
Project: NewCommands-master File: TypeNBTArg.java View source code |
@Override public ArgWrapper<NBTTagCompound> iParse(final Parser parser, final Context context) throws SyntaxErrorException { final ArgWrapper<NBTTagCompound> ret = context.generalParse(parser, TypeIDs.NBTCompound); if (ret != null) return ret; final Matcher m = parser.getMatcher(ParserNBTTag.specialMatcher); if (!parser.findInc(m) || !"{".equals(m.group(1))) throw parser.SEE("Expected '{' "); ParsingUtilities.terminateCompletion(parser); final CompoundData data = new CompoundData(); this.baseDescriptor.getCompoundParser().parseItems(parser, data); if (data.data.isEmpty()) return TypeIDs.NBTCompound.wrap(new NBTTagCompound(data.primitiveData)); final ArrayList<Pair<String, CommandArg<NBTBase>>> dynamicData = data.data; dynamicData.trimToSize(); return TypeIDs.NBTCompound.wrap(new CommandArg<NBTTagCompound>() { final NBTTagCompound compound = new NBTTagCompound(data.primitiveData); @Override public NBTTagCompound eval(final ICommandSender sender) throws CommandException { for (final Pair<String, CommandArg<NBTBase>> tag : dynamicData) this.compound.setTag(tag.getKey(), tag.getValue().eval(sender)); return this.compound; } }); }
Example 68
Project: onos-master File: Tl1DeviceConfig.java View source code |
private Pair<String, Integer> extractIpPort() { String info = subject.toString(); if (info.startsWith(Tl1DeviceProvider.TL1)) { //+1 is due to length of colon separator String ip = info.substring(info.indexOf(":") + 1, info.lastIndexOf(":")); int port = Integer.parseInt(info.substring(info.lastIndexOf(":") + 1)); return Pair.of(ip, port); } return null; }
Example 69
Project: OpenIDM-master File: CertificateResourceProvider.java View source code |
@Override
public void createDefaultEntry(String alias) throws Exception {
Pair<X509Certificate, PrivateKey> pair = generateCertificate("local.openidm.forgerock.org", "OpenIDM Self-Signed Certificate", "None", "None", "None", "None", DEFAULT_ALGORITHM, DEFAULT_KEY_SIZE, DEFAULT_SIGNATURE_ALGORITHM, null, null);
Certificate cert = pair.getKey();
store.getStore().setCertificateEntry(alias, cert);
store.store();
}
Example 70
Project: optaplanner-master File: PlanningIdLookUpStrategy.java View source code |
protected Object extractPlanningId(Object externalObject) {
Object planningId = planningIdMemberAccessor.executeGetter(externalObject);
if (planningId == null) {
throw new IllegalArgumentException("The planningId (" + planningId + ") of the member (" + planningIdMemberAccessor + ") of the class (" + externalObject.getClass() + ") on externalObject (" + externalObject + ") must not be null.\n" + "Maybe initialize the planningId of the original object before solving" + " or remove the " + PlanningId.class.getSimpleName() + " annotation" + " or change the " + PlanningSolution.class.getSimpleName() + " annotation's " + LookUpStrategyType.class.getSimpleName() + ".");
}
return Pair.of(externalObject.getClass(), planningId);
}
Example 71
Project: pinot-master File: MmapDebugResource.java View source code |
@GET @Path("memory/offheap") @ApiOperation(value = "View current off-heap allocations", notes = "Lists all off-heap allocations and their associated sizes") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success") }) @Produces(MediaType.APPLICATION_JSON) public Map<String, List<AllocationInfo>> getOffHeapSizes() throws ResourceException { List<AllocationInfo> allocations = new ArrayList<>(); List<Pair<MmapUtils.AllocationContext, Integer>> allocationsMap = MmapUtils.getAllocationsAndSizes(); for (Pair<MmapUtils.AllocationContext, Integer> allocation : allocationsMap) { AllocationInfo info = new AllocationInfo(); info.context = allocation.getKey().getContext(); info.type = allocation.getKey().getContext(); info.size = allocation.getValue(); allocations.add(info); } Map<String, List<AllocationInfo>> allocationMap = new HashMap<>(); allocationMap.put("allocations", allocations); return allocationMap; }
Example 72
Project: PneumaticCraft-master File: RenderDroneAI.java View source code |
public void update() { entityItem.age += 4; ChunkPosition lastPos = pos; pos = drone.getTargetedBlock(); if (pos != null) { if (lastPos == null) { oldPos = pos; } else if (!pos.equals(lastPos)) { progress = 0; oldPos = lastPos; } } else { oldPos = null; } progress = Math.min((float) Math.PI, progress + 0.1F); Iterator<Pair<RenderCoordWireframe, Integer>> iterator = blackListWireframes.iterator(); while (iterator.hasNext()) { Pair<RenderCoordWireframe, Integer> wireframe = iterator.next(); wireframe.getKey().ticksExisted++; wireframe.setValue(wireframe.getValue() - 1); if (wireframe.getValue() <= 0) { iterator.remove(); } } }
Example 73
Project: poi-tl-master File: TemplateParserTest.java View source code |
@Test public void TestRule() { Pattern compile = Pattern.compile(TemplateResolver.RULER_REGEX); // System.out.println(compile.matcher("{{123}}").matches()); // System.out.println(compile.matcher("{{@ada_123}}").matches()); // System.out.println(compile.matcher("{{#ada_123}}").matches()); // System.out.println(compile.matcher("{{#ada_@23}}").matches()); // System.out.println(compile.matcher("{{ad a}}").matches()); // System.out.println(compile.matcher("{123}").matches()); // System.out.println(compile.matcher("{ada}}").matches()); // System.out.println(compile.matcher("{ada}}ad").matches()); // Matcher matcher = compile.matcher("{{ada_123}}"); // System.out.println(matcher); // // Matcher matcher2 = compile.matcher("{{ada}}ad{{sayi}}"); // while(matcher2.find()) // System.out.println(matcher2.group()); // // //String str = "{{ada}}ad"; // //System.out.println(str.matches(TemplateParser.RULER_REGEX)); // // // String regEx="(\\{\\{)|(\\}\\})"; // Pattern p = Pattern.compile(regEx); // Matcher m = p.matcher("{{@ada_123}}ada{{sayi}}"); // System.out.println( m.replaceAll("").trim()); String str = "ada{{sayi}}dsfsad{dfds{{@ada}}dsfsad{{qishi}}{{youdou}}"; toConsole(str.split(TemplateResolver.RULER_REGEX)); //toConsole(compile.split(str)); Matcher matcher = compile.matcher(str); matcher.matches(); while (matcher.find()) { String group = matcher.group(); System.out.println(group); } List<Pair<Integer, Integer>> pairs = new ArrayList<Pair<Integer, Integer>>(); String text = str; int start = 0; int end = 0; matcher = compile.matcher(text); while (matcher.find()) { String group = matcher.group(); start = text.indexOf(group, end); end = start + group.length(); pairs.add(new ImmutablePair<Integer, Integer>(start, end)); } for (Pair<Integer, Integer> p : pairs) { System.out.println(p.getLeft() + ":" + p.getValue()); System.out.println(text.substring(p.getLeft(), p.getRight())); } }
Example 74
Project: portalsammler-master File: MapReader.java View source code |
public Pair<String, Map<String, String>> readNext() throws IOException { final String id = this.reader.readLine(); if (id == null) { return null; } final Map<String, String> map = new LinkedHashMap<String, String>(); while (true) { final String firstLine = this.reader.readLine(); if (firstLine.equals(".")) { break; } final String secondLine = this.reader.readLine(); map.put(lineToValue(firstLine), lineToValue(secondLine)); } return Pair.of(id, map); }
Example 75
Project: pregelix-master File: ConnectorPolicyAssignmentPolicy.java View source code |
@Override public IConnectorPolicy getConnectorPolicyAssignment(IConnectorDescriptor c, int nProducers, int nConsumers, int[] fanouts) { if (c.getClass().getName().contains("MToNPartitioningMergingConnectorDescriptor")) { return senderSideMatPipPolicy; } else { Pair<Pair<IOperatorDescriptor, Integer>, Pair<IOperatorDescriptor, Integer>> endPoints = spec.getConnectorOperatorMap().get(c.getConnectorId()); IOperatorDescriptor consumer = endPoints.getRight().getLeft(); if (consumer instanceof TreeIndexInsertUpdateDeleteOperatorDescriptor) { return senderSidePipeliningReceiverSideMatBlkPolicy; } else { return pipeliningPolicy; } } }
Example 76
Project: SIF-master File: TextFieldTokenNormalizer.java View source code |
/**
* @param item
* @param textSimStrategy
* @param index
* @return
* @throws IOException
*/
private Pair<String, Double> fuzzymatch(String item, DynamicAttrSimilarityStrategy textSimStrategy, int index) throws IOException {
double dist = 1.0;
String token = null;
for (String[] normalizer : normalizers) {
double thisDist = textSimStrategy.findDistance(item, normalizer[index]);
if (thisDist < dist) {
dist = thisDist;
token = normalizer[0];
}
}
ImmutablePair<String, Double> match = new ImmutablePair<String, Double>(token, dist);
return match;
}
Example 77
Project: sifarish-master File: TextFieldTokenNormalizer.java View source code |
/**
* @param item
* @param textSimStrategy
* @param index
* @return
* @throws IOException
*/
private Pair<String, Double> fuzzymatch(String item, DynamicAttrSimilarityStrategy textSimStrategy, int index) throws IOException {
double dist = 1.0;
String token = null;
for (String[] normalizer : normalizers) {
double thisDist = textSimStrategy.findDistance(item, normalizer[index]);
if (thisDist < dist) {
dist = thisDist;
token = normalizer[0];
}
}
ImmutablePair<String, Double> match = new ImmutablePair<String, Double>(token, dist);
return match;
}
Example 78
Project: spring-open-master File: SingleSrcTreeFlowIntentTest.java View source code |
@Override protected SingleSrcTreeFlowIntent createOne() { Set<Pair<Dpid, OutputAction>> actions = new HashSet<>(Arrays.asList(Pair.of(dpid2, action2), Pair.of(dpid3, action3))); SingleSrcTreeFlow tree = new SingleSrcTreeFlow(flowId1, match, new SwitchPort(dpid1, port3), createTree(), actions); return new SingleSrcTreeFlowIntent(intentId1, tree); }
Example 79
Project: swagger-core-master File: ModelWithTuple2.java View source code |
@Override
public Model resolve(Type type, ModelConverterContext context, Iterator<ModelConverter> chain) {
final JavaType javaType = _mapper.constructType(type);
if (Pair.class.isAssignableFrom(javaType.getRawClass())) {
final JavaType left = javaType.containedType(0);
final String name = "MapOf" + WordUtils.capitalize(_typeName(left));
return new ModelImpl().name(name).additionalProperties(context.resolveProperty(left, new Annotation[] {}));
}
return super.resolve(type, context, chain);
}
Example 80
Project: tachyon-master File: WebInterfaceConfigurationServlet.java View source code |
private SortedSet<Pair<String, String>> getSortedProperties() { TreeSet<Pair<String, String>> rtn = new TreeSet<>(); for (Map.Entry<String, String> entry : Configuration.toMap().entrySet()) { String key = entry.getKey(); if (key.startsWith(ALLUXIO_CONF_PREFIX) && !ALLUXIO_CONF_EXCLUDES.contains(key)) { rtn.add(new ImmutablePair<>(key, Configuration.get(PropertyKey.fromString(key)))); } } return rtn; }
Example 81
Project: telekom-workflow-engine-master File: WorkflowInstanceStateModel.java View source code |
public List<Pair<String, String>> getAttributeList() { if (getAttributes() == null) { return Collections.emptyList(); } JsonParser parser = new JsonParser(); JsonElement attributesObject = parser.parse(getAttributes()); List<Pair<String, String>> result = new ArrayList<>(); for (Entry<String, JsonElement> attribute : attributesObject.getAsJsonObject().entrySet()) { result.add(Pair.of(attribute.getKey(), gson.toJson(attribute.getValue()))); } return result; }
Example 82
Project: tempto-master File: ConfigurationVariableResolver.java View source code |
private Pair<String, Object> resolveConfigurationEntry(Configuration configuration, String prefix, StrSubstitutor strSubstitutor) { Optional<Object> optionalValue = configuration.get(prefix); if (optionalValue.isPresent()) { Object value = optionalValue.get(); if (value instanceof String) { return Pair.of(prefix, strSubstitutor.replace(value)); } else if (value instanceof List) { List<String> resolvedList = new ArrayList<String>(); for (String entry : (List<String>) value) { resolvedList.add(strSubstitutor.replace(entry)); } return Pair.of(prefix, resolvedList); } else { return Pair.of(prefix, value); } } else { return Pair.of(prefix, resolveVariables(configuration.getSubconfiguration(prefix), strSubstitutor)); } }
Example 83
Project: vertexium-master File: SimpleSubstitutionUtils.java View source code |
public static List<Pair<String, String>> getSubstitutionList(Map configuration) { Map<String, MutablePair<String, String>> substitutionMap = Maps.newHashMap(); //parse the config arguments for (Object objKey : configuration.keySet()) { String key = objKey.toString(); if (key.startsWith(SUBSTITUTION_MAP_PREFIX + ".")) { List<String> parts = Lists.newArrayList(IterableUtils.toList(Splitter.on('.').split(key))); String pairKey = parts.get(parts.size() - 2); String valueType = parts.get(parts.size() - 1); if (!substitutionMap.containsKey(pairKey)) { substitutionMap.put(pairKey, new MutablePair<String, String>()); } MutablePair<String, String> pair = substitutionMap.get(pairKey); if (KEY_IDENTIFIER.equals(valueType)) { pair.setLeft(configuration.get(key).toString()); } else if (VALUE_IDENTIFIER.equals(valueType)) { pair.setValue(configuration.get(key).toString()); } } } //order is important, so create order by the pairKey that was in the config. eg: substitution.0.key is before substitution.1.key so it is evaluated in that order List<String> keys = Lists.newArrayList(substitutionMap.keySet()); Collections.sort(keys); List<Pair<String, String>> finalMap = Lists.newArrayList(); for (String key : keys) { Pair<String, String> pair = substitutionMap.get(key); finalMap.add(pair); LOGGER.info("Using substitution %s -> %s", pair.getKey(), pair.getValue()); } return finalMap; }
Example 84
Project: ws-proxy-master File: ForwardingClientConfigurationSupport.java View source code |
public Map<QName, Pair<String, Integer>> parseForwardProxyUrl(String httpForwardProxy) { Map<QName, Pair<String, Integer>> result = new HashMap<>(); for (Entry<QName, String> entry : splitQnameConfig(httpForwardProxy, "httpForwardProxy").entrySet()) { String[] splitted = StringUtils.split(entry.getValue(), ":"); if (splitted.length > 2) { throw new RuntimeException("Forward proxy format should be host:port or host (port 80 assumed in that case)"); } result.put(entry.getKey(), Pair.of(splitted[0], Integer.parseInt(splitted.length == 2 ? splitted[1] : "80"))); } return result; }
Example 85
Project: Aero-master File: FunctionUtil.java View source code |
// CyclicCoordinateDescent
public static float[] optimize(double tolerance, int iterations, float[] initial, float[] initialStep, Pair<Float, Float> bounds, float[] data) {
float[] best = initial;
float bestF = evaluatePolynomial(best, data, false);
int maxDim = initial.length;
for (int i = 0; i < iterations; ++i) {
for (int dim = 0; dim < maxDim; ++dim) {
float step = initialStep[dim];
while (step > tolerance) {
float[] left = best.clone();
left[dim] = Math.max(bounds.getLeft(), best[dim] - step);
float leftF = evaluatePolynomial(left, data, false);
float[] right = best.clone();
right[dim] = Math.min(bounds.getRight(), best[dim] + step);
float rightF = evaluatePolynomial(right, data, false);
if (leftF < bestF) {
best = left;
bestF = leftF;
}
if (rightF < bestF) {
best = right;
bestF = rightF;
}
step *= 0.5;
}
}
}
return best;
}
Example 86
Project: aerosolve-master File: FunctionUtil.java View source code |
// CyclicCoordinateDescent
public static float[] optimize(double tolerance, int iterations, float[] initial, float[] initialStep, Pair<Float, Float> bounds, float[] data) {
float[] best = initial;
float bestF = evaluatePolynomial(best, data, false);
int maxDim = initial.length;
for (int i = 0; i < iterations; ++i) {
for (int dim = 0; dim < maxDim; ++dim) {
float step = initialStep[dim];
while (step > tolerance) {
float[] left = best.clone();
left[dim] = Math.max(bounds.getLeft(), best[dim] - step);
float leftF = evaluatePolynomial(left, data, false);
float[] right = best.clone();
right[dim] = Math.min(bounds.getRight(), best[dim] + step);
float rightF = evaluatePolynomial(right, data, false);
if (leftF < bestF) {
best = left;
bestF = leftF;
}
if (rightF < bestF) {
best = right;
bestF = rightF;
}
step *= 0.5;
}
}
}
return best;
}
Example 87
Project: camunda-bpm-mockito-master File: ParseDelegateExpressions.java View source code |
@Override public List<Pair<ExpressionType, String>> apply(final URL bpmnResource) { final Element root = new ReadXmlDocumentFromResource().apply(bpmnResource).getDocumentElement(); return new ArrayList<Pair<ExpressionType, String>>() { { for (ExpressionType type : ExpressionType.values()) { final NodeList nodes = root.getElementsByTagNameNS("*", type.element); for (int i = 0; i < nodes.getLength(); i++) { final NamedNodeMap attributes = nodes.item(i).getAttributes(); // TODO: this is not nice, but I cannot get getNamedItemNS("*", ...) to work properly Node delegateExpression = Optional.ofNullable(attributes.getNamedItem(CAMUNDA_ATTRIBUTE_DELEGATE_EXPRESSION)).orElse(attributes.getNamedItem("camunda:" + CAMUNDA_ATTRIBUTE_DELEGATE_EXPRESSION)); if (delegateExpression != null) { add(Pair.of(type, extractDelegateExpressionName(delegateExpression.getTextContent()))); } } } } }; }
Example 88
Project: com.nimbits-master File: UsersWithSameNameEntityTest.java View source code |
@Test public void testScenario() { int count = 2; String commonPointName = UUID.randomUUID().toString(); String commonHost = "http://test.com"; for (int i = 0; i < count; i++) { emails.add(Pair.of(String.format("%s@nimbits.com", UUID.randomUUID().toString()), UUID.randomUUID().toString())); } for (Pair<String, String> pair : emails) { users.add(adminClient.addUser(new UserModel.Builder().email(pair.getLeft()).password(pair.getRight()).create())); } assertEquals(count, users.size()); for (Pair<String, String> pair : emails) { Nimbits userClient = new Nimbits.Builder().email(pair.getLeft()).instance(host).token(pair.getRight()).create(); User user = userClient.getMe(); assertEquals(pair.getLeft(), user.getEmail().getValue()); Point sameNamePoint = userClient.addPoint(user, new PointModel.Builder().name(commonPointName).create()); Point uniquePoint = userClient.addPoint(user, new PointModel.Builder().name(String.valueOf(user.getEmail().hashCode())).create()); WebHook webHook = userClient.addWebHook(user, new WebHookModel.Builder().pathChannel(DataChannel.number).method(HttpMethod.GET).enabled(true).name(commonPointName).url(String.format("%s/%s", commonHost, user.getId())).create()); log(String.format("Added %s %s", sameNamePoint.getName(), uniquePoint.getName())); log(String.format("Added Hook: %s %s", webHook.getUrl(), user.getId())); clients.add(Pair.of(user, userClient)); } for (Pair<User, Nimbits> clientPair : clients) { Nimbits client = clientPair.getRight(); User user = clientPair.getKey(); Optional<Point> optional = client.findPointByName(commonPointName); assertTrue(optional.isPresent()); Point foo = optional.get(); assertEquals(user.getId(), foo.getParent()); assertEquals(commonPointName, foo.getName().getValue()); Optional<WebHook> webHook = client.findWebHook(commonPointName); assertTrue(webHook.isPresent()); assertEquals(webHook.get().getUrl().getUrl(), String.format("%s/%s", commonHost, user.getId())); } }
Example 89
Project: crawljax-master File: PreCrawlConfiguration.java View source code |
PreCrawlConfiguration build(CrawlActionsBuilder crawlActionsBuilder) {
Pair<ImmutableList<CrawlElement>, ImmutableList<CrawlElement>> elements = crawlActionsBuilder.build();
preCrawlConfiguration.includedElements = elements.getLeft();
preCrawlConfiguration.excludedElements = elements.getRight();
preCrawlConfiguration.waitConditions = waitConditions.build();
preCrawlConfiguration.crawlConditions = crawlConditions.build();
preCrawlConfiguration.filterAttributeNames = filterAttributeNames.build();
if (preCrawlConfiguration.filterAttributeNames.isEmpty()) {
preCrawlConfiguration.filterAttributeNames = ImmutableSortedSet.of("closure_hashcode_(\\w)*", "jquery[0-9]+");
}
return preCrawlConfiguration;
}
Example 90
Project: datacollector-master File: JdbcTableReadContextLoader.java View source code |
@Override public TableReadContext load(TableContext tableContext) throws Exception { Pair<String, List<Pair<Integer, String>>> queryAndParamValToSet = OffsetQueryUtil.buildAndReturnQueryAndParamValToSet(tableContext, offsets.get(tableContext.getQualifiedName()), quoteChar, tableJdbcELEvalContext); TableReadContext tableReadContext = new TableReadContext(connectionManager.getConnection(), queryAndParamValToSet.getLeft(), queryAndParamValToSet.getRight(), fetchSize); //Clear the initial offset after the query is build so we will not use the initial offset from the next //time the table is used. tableContext.clearStartOffset(); return tableReadContext; }
Example 91
Project: Dawn47-master File: CubicSplineCurve.java View source code |
@Override
public double valueAt(double x) {
// Find last point whose value <= x
int index = 0;
for (; index < pts.size() && pts.get(index).getLeft() < x; ++index) ;
if (index > 0)
--index;
if (index >= pts.size() - 1)
index = pts.size() - 2;
// Generate 4 refpoints' vals
Pair<Double, Double> pt1 = pts.get(index), pt2 = pts.get(index + 1), pt0 = index == 0 ? pt1 : pts.get(index - 1);
double dist = pt2.getLeft() - pt1.getLeft(), ldist = pt0 == pt1 ? dist : pt1.getRight() - pt0.getLeft();
double p0 = pt1.getRight(), p1 = pt2.getRight(), m0 = kval(index) * ldist, m1 = kval(index + 1) * dist;
double u = (x - pt1.getLeft()) / dist, u2 = u * u, u3 = u2 * u;
// Apply calculation
return (2 * u3 - 3 * u2 + 1) * p0 + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * p1 + (u3 - u2) * m1;
}
Example 92
Project: dynunit-master File: ClassReflectionTest.java View source code |
@Test
public void testGetElementForAnnotationAny() throws Exception {
final Pair<? extends AnnotatedElement, Any> annotatedElement = reflection.getAnnotatedElement(Any.class);
assertNotNull(annotatedElement);
assertThat("The first (and only) element annotated @Any should be the class itself.", annotatedElement.getLeft(), is(instanceOf(Class.class)));
}
Example 93
Project: earthsci-master File: LayersProperty.java View source code |
/** * Add additional layer state to this property. * * @param id * The id of the layer * @param opacity * The opacity of the layer */ public void addLayer(String id, Double opacity, String name) { // layerState.put(id, opacity); // layerName.put(id, name); List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>(); pairs.add(new ImmutablePair<String, String>("opacity", opacity.toString())); pairs.add(new ImmutablePair<String, String>("name", name)); addLayer(id, pairs.toArray(new Pair[0])); }
Example 94
Project: fim-master File: HashProgress.java View source code |
public String hashLegend() {
StringBuilder sb = new StringBuilder();
for (int progressIndex = progressChars.size() - 1; progressIndex >= 0; progressIndex--) {
Pair<Character, Integer> progressPair = progressChars.get(progressIndex);
char marker = progressPair.getLeft();
sb.append(marker);
int fileLength = progressPair.getRight();
if (fileLength == 0) {
sb.append(" otherwise");
} else {
sb.append(" > ").append(byteCountToDisplaySize(fileLength));
}
sb.append(", ");
}
String legend = sb.toString();
legend = legend.substring(0, legend.length() - 2);
return legend;
}
Example 95
Project: flink-graph-master File: ProjectEmbeddingsNodeTest.java View source code |
@Test public void testMetaDataInitialization() throws Exception { EmbeddingMetaData inputMetaData = new EmbeddingMetaData(); inputMetaData.setEntryColumn("a", EntryType.VERTEX, 0); inputMetaData.setEntryColumn("b", EntryType.VERTEX, 1); inputMetaData.setPropertyColumn("a", "age", 0); inputMetaData.setPropertyColumn("b", "name", 1); PlanNode mockNode = new MockPlanNode(null, inputMetaData); List<Pair<String, String>> projectedKeys = new ArrayList<>(); projectedKeys.add(Pair.of("a", "age")); ProjectEmbeddingsNode node = new ProjectEmbeddingsNode(mockNode, projectedKeys); EmbeddingMetaData outputMetaData = node.getEmbeddingMetaData(); assertThat(outputMetaData.getEntryCount(), is(2)); assertThat(outputMetaData.getEntryColumn("a"), is(0)); assertThat(outputMetaData.getEntryColumn("b"), is(1)); assertThat(outputMetaData.getPropertyCount(), is(1)); assertThat(outputMetaData.getPropertyColumn("a", "age"), is(0)); }
Example 96
Project: Freshet-master File: HourlyTopKBackingMap.java View source code |
@Override
public void multiPut(List<List<Object>> keys, List<OpaqueValue> vals) {
List<String> singleKeys = toSingleKeys(keys);
for (Pair<String, OpaqueValue> pair : zip(singleKeys, vals)) {
byte[] prev = CountMinSketch.serialize((CountMinSketch) pair.getValue().getPrev());
byte[] cur = CountMinSketch.serialize((CountMinSketch) pair.getValue().getCurr());
long currTxid = pair.getValue().getCurrTxid();
Map<byte[], byte[]> fields = new HashMap<byte[], byte[]>();
fields.put("txid".getBytes(), ByteBuffer.allocate(8).putLong(currTxid).array());
fields.put("prev".getBytes(), prev);
fields.put("curr".getBytes(), cur);
redisClient.hmset(pair.getKey().getBytes(), fields);
}
}
Example 97
Project: funj-master File: ReflectionTools.java View source code |
private static Pair<String, Map<String, Object>> buildArgs(Object... args) { Map<String, Object> map = newHashMap(); List<String> varNames = newArrayList(); int i = 0; for (Object arg : args) { String varName = "arg" + i; varNames.add(varName); map.put(varName, arg); i++; } return Pair.of(Joiner.on(',').join(varNames), map); }
Example 98
Project: gobblin-master File: UrlTriePrefixGrouper.java View source code |
@Override
public boolean hasNext() {
if (_retVal != null) {
return true;
}
while (_iterator.hasNext() && _retVal == null) {
Pair<String, UrlTrieNode> nextPair = _iterator.next();
UrlTrieNode nextNode = nextPair.getRight();
if (nextNode.getSize() <= _groupSize) {
_retVal = Triple.of(nextPair.getLeft(), GoogleWebmasterFilter.FilterOperator.CONTAINS, nextNode);
return true;
} else if (nextNode.isExist()) {
_retVal = Triple.of(nextPair.getLeft(), GoogleWebmasterFilter.FilterOperator.EQUALS, nextNode);
return true;
}
}
return false;
}
Example 99
Project: gradoop-master File: ProjectEmbeddingsNodeTest.java View source code |
@Test public void testMetaDataInitialization() throws Exception { EmbeddingMetaData inputMetaData = new EmbeddingMetaData(); inputMetaData.setEntryColumn("a", EntryType.VERTEX, 0); inputMetaData.setEntryColumn("b", EntryType.VERTEX, 1); inputMetaData.setPropertyColumn("a", "age", 0); inputMetaData.setPropertyColumn("b", "name", 1); PlanNode mockNode = new MockPlanNode(null, inputMetaData); List<Pair<String, String>> projectedKeys = new ArrayList<>(); projectedKeys.add(Pair.of("a", "age")); ProjectEmbeddingsNode node = new ProjectEmbeddingsNode(mockNode, projectedKeys); EmbeddingMetaData outputMetaData = node.getEmbeddingMetaData(); assertThat(outputMetaData.getEntryCount(), is(2)); assertThat(outputMetaData.getEntryColumn("a"), is(0)); assertThat(outputMetaData.getEntryColumn("b"), is(1)); assertThat(outputMetaData.getPropertyCount(), is(1)); assertThat(outputMetaData.getPropertyColumn("a", "age"), is(0)); }
Example 100
Project: handlebars.java-master File: ConcurrentMapTemplateCacheTest.java View source code |
@Test public void get() throws IOException { ConcurrentMap<TemplateSource, Pair<TemplateSource, Template>> cache = new ConcurrentHashMap<TemplateSource, Pair<TemplateSource, Template>>(); TemplateSource source = new URLTemplateSource("/template.hbs", getClass().getResource("/template.hbs")); Template template = createMock(Template.class); Parser parser = createMock(Parser.class); expect(parser.parse(source)).andReturn(template); replay(parser, template); // 1st call, parse must be call it assertEquals(template, new ConcurrentMapTemplateCache(cache).get(source, parser)); // 2nd call, should return from cache assertEquals(template, new ConcurrentMapTemplateCache(cache).get(source, parser)); verify(parser, template); }
Example 101
Project: hapi-fhir-master File: SearchParamPresenceSvcImpl.java View source code |
@Override public void updatePresence(ResourceTable theResource, Map<String, Boolean> theParamNameToPresence) { Map<String, Boolean> presenceMap = new HashMap<String, Boolean>(theParamNameToPresence); List<SearchParamPresent> entitiesToSave = new ArrayList<SearchParamPresent>(); List<SearchParamPresent> entitiesToDelete = new ArrayList<SearchParamPresent>(); Collection<SearchParamPresent> existing; existing = mySearchParamPresentDao.findAllForResource(theResource); for (SearchParamPresent nextExistingEntity : existing) { String nextSearchParamName = nextExistingEntity.getSearchParam().getParamName(); Boolean existingValue = presenceMap.remove(nextSearchParamName); if (existingValue == null) { entitiesToDelete.add(nextExistingEntity); } else if (existingValue.booleanValue() == nextExistingEntity.isPresent()) { ourLog.trace("No change for search param {}", nextSearchParamName); } else { nextExistingEntity.setPresent(existingValue); entitiesToSave.add(nextExistingEntity); } } for (Entry<String, Boolean> next : presenceMap.entrySet()) { String resourceType = theResource.getResourceType(); String paramName = next.getKey(); Pair<String, String> key = Pair.of(resourceType, paramName); SearchParam searchParam = myResourceTypeToSearchParamToEntity.get(key); if (searchParam == null) { searchParam = mySearchParamDao.findForResource(resourceType, paramName); if (searchParam != null) { myResourceTypeToSearchParamToEntity.put(key, searchParam); } else { searchParam = new SearchParam(); searchParam.setResourceName(resourceType); searchParam.setParamName(paramName); searchParam = mySearchParamDao.saveAndFlush(searchParam); ourLog.info("Added search param {} with pid {}", paramName, searchParam.getId()); // Don't add the newly saved entity to the map in case the save fails } } SearchParamPresent present = new SearchParamPresent(); present.setResource(theResource); present.setSearchParam(searchParam); present.setPresent(next.getValue()); entitiesToSave.add(present); } mySearchParamPresentDao.deleteInBatch(entitiesToDelete); mySearchParamPresentDao.save(entitiesToSave); }