Java 类org.apache.commons.lang3.tuple.Pair 实例源码

项目:echo    文件:TempSource.java   
@Override
public Iterable<Pair<String, String>> get() {
    List<Pair<String,String>> list = new ArrayList<Pair<String,String>>();
    File dir = new File(sourceDir);
    if(dir.isDirectory())
    {
        File[] files = dir.listFiles();
        for(File file:files) {
                byte[] bytes;
                try {
                    bytes = Files.readAllBytes(file.toPath());
                    String content =  new String(bytes,"UTF-8");
                    Pair<String, String> e = Pair.of(file.getName(), content);
                    list.add(e);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
        }
    }
    return list;
}
项目:sentry    文件:UserCountService.java   
@Scheduled(cron = "10 * * * * ?")
void storeUserCountMetrics() {
    ZonedDateTime timestamp = ZonedDateTime.now().truncatedTo(MINUTES);

    userCountRepository.save(
        metricRegistry.getHistograms((name, metric) -> name.startsWith("discord.ws.users"))
            .entrySet().stream()
            .map(entry -> Pair.of(extractTags(entry.getKey()), (long) entry.getValue().getSnapshot().getMean()))
            .map(pair -> new UserCount()
                .bot(pair.getKey()[0])
                .guild(pair.getKey()[1])
                .status(pair.getKey()[2])
                .value(pair.getValue())
                .timestamp(timestamp))
            .collect(Collectors.toList())
    );
}
项目:EasyPackage    文件:FacadeController.java   
@Post(Constants.Path.PACKAGE + "/{appId:\\d+}")
public String submitPakcageTask(Invocation inv,
        @Param("appId") Integer appId, TaskParam taskParam) {
    taskParam.setUserId(UserStateManager.getLoginUser(inv.getRequest())
            .getId());
    Pair<Boolean, String> checkResult = taskParam.isValid(false);
    if (!checkResult.getLeft()) {
        logger.warn(
                "create task param invalid, reason:{}, taskPara:{}, appId:{}",
                checkResult.getRight(), taskParam, appId);
        return "@" + Result.newInstance(ErrorCode.InvalidParam);
    }
    App app = null;
    if ((app = taskService.findApp(appId)) == null) {
        return "@" + Result.newInstance(ErrorCode.InvalidParam);
    }
    taskParam.setApp(app);
    ErrorCode result = taskService.createTaskGroup(taskParam);
    if (result == ErrorCode.Success) {
        return PathUtil.getRedirectPath(Constants.Path.TASK_LIST + "/"
                + appId);
    }
    return "@" + Result.newInstance(result);
}
项目:AppCoins-ethereumj    文件:EthashTest.java   
@Test
    public void cacheTestFast() {
        EthashAlgo ethash = new EthashAlgo();
        byte[] seed = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~".getBytes();
        long cacheSize = 1024;
        long fullSize = 1024 * 32;
        int[] cache = ethash.makeCache(cacheSize, seed);


        Assert.assertArrayEquals(intsToBytes(cache, false), Hex.decode("2da2b506f21070e1143d908e867962486d6b0a02e31d468fd5e3a7143aafa76a14201f63374314e2a6aaf84ad2eb57105dea3378378965a1b3873453bb2b78f9a8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995ca8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995ca8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995c259440b89fa3481c2c33171477c305c8e1e421f8d8f6d59585449d0034f3e421808d8da6bbd0b6378f567647cc6c4ba6c434592b198ad444e7284905b7c6adaf70bf43ec2daa7bd5e8951aa609ab472c124cf9eba3d38cff5091dc3f58409edcc386c743c3bd66f92408796ee1e82dd149eaefbf52b00ce33014a6eb3e50625413b072a58bc01da28262f42cbe4f87d4abc2bf287d15618405a1fe4e386fcdafbb171064bd99901d8f81dd6789396ce5e364ac944bbbd75a7827291c70b42d26385910cd53ca535ab29433dd5c5714d26e0dce95514c5ef866329c12e958097e84462197c2b32087849dab33e88b11da61d52f9dbc0b92cc61f742c07dbbf751c49d7678624ee60dfbe62e5e8c47a03d8247643f3d16ad8c8e663953bcda1f59d7e2d4a9bf0768e789432212621967a8f41121ad1df6ae1fa78782530695414c6213942865b2730375019105cae91a4c17a558d4b63059661d9f108362143107babe0b848de412e4da59168cce82bfbff3c99e022dd6ac1e559db991f2e3f7bb910cefd173e65ed00a8d5d416534e2c8416ff23977dbf3eb7180b75c71580d08ce95efeb9b0afe904ea12285a392aff0c8561ff79fca67f694a62b9e52377485c57cc3598d84cac0a9d27960de0cc31ff9bbfe455acaa62c8aa5d2cce96f345da9afe843d258a99c4eaf3650fc62efd81c7b81cd0d534d2d71eeda7a6e315d540b4473c80f8730037dc2ae3e47b986240cfc65ccc565f0d8cde0bc68a57e39a271dda57440b3598bee19f799611d25731a96b5dbbbefdff6f4f656161462633030d62560ea4e9c161cf78fc96a2ca5aaa32453a6c5dea206f766244e8c9d9a8dc61185ce37f1fc804459c5f07434f8ecb34141b8dcae7eae704c950b55556c5f40140c3714b45eddb02637513268778cbf937a33e4e33183685f9deb31ef54e90161e76d969587dd782eaa94e289420e7c2ee908517f5893a26fdb5873d68f92d118d4bcf98d7a4916794d6ab290045e30f9ea00ca547c584b8482b0331ba1539a0f2714fddc3a0b06b0cfbb6a607b8339c39bcfd6640b1f653e9d70ef6c985b"));
        int[] i = ethash.calcDatasetItem(cache, 0);
        Assert.assertArrayEquals(intsToBytes(i, false), Hex.decode("b1698f829f90b35455804e5185d78f549fcb1bdce2bee006d4d7e68eb154b596be1427769eb1c3c3e93180c760af75f81d1023da6a0ffbe321c153a7c0103597"));
//
        byte[] blockHash = "~~~X~~~~~~~~~~~~~~~~~~~~~~~~~~~~".getBytes();
        long nonce = 0x7c7c597cL;
        Pair<byte[], byte[]> pair = ethash.hashimotoLight(fullSize, cache, blockHash, longToBytes(nonce));

        // comparing mix hash
        Assert.assertArrayEquals(pair.getLeft(), Hex.decode("d7b668b90c2f26961d98d7dd244f5966368165edbce8cb8162dd282b6e5a8eae"));
        // comparing the final hash
        Assert.assertArrayEquals(pair.getRight(), Hex.decode("b8cb1cb3ac1a7a6e12c4bc90f2779ef97e661f7957619e677636509d2f26055c"));

        System.out.println(Hex.toHexString(pair.getLeft()));
        System.out.println(Hex.toHexString(pair.getRight()));
    }
项目:ExPetrum    文件:TreeGenImpl.java   
public static int trunkGenOliveImpl(Pair<ITreeGenerator, BlockPos> p)
{
    BlockPos initialPos = p.getRight();
    TreeGenerator gen = (TreeGenerator)p.getKey();
    int heightToGenerate = 5 + gen.worldGen.rand.nextInt(4);
    int h = heightToGenerate + 1;
    while (h-- > 0)
    {
        BlockPos pos = initialPos.up(h);
        gen.worldGen.setBlockState(pos, gen.wood, 2);
        gen.worldGen.setBlockState(pos.west(), gen.wood, 2);
        gen.worldGen.setBlockState(pos.south(), gen.wood, 2);
        gen.worldGen.setBlockState(pos.south().west(), gen.wood, 2);
    }

    return heightToGenerate;
}
项目:sponge    文件:DecomposedQueue.java   
/**
 * Puts a new entry (trigger adapter or event set processor group adapter, event) at the end of this decomposed queue.
 *
 * @param entry a pair (trigger adapter or event set processor group adapter).
 * @return {@code false} if the queue is full and can't accept any new entry.
 */
public boolean put(Pair<T, Event> entry) {
    lock.lock();

    try {
        internalLock.lock();

        if (entries.size() >= capacity) {
            return false;
        }

        logger.debug("Put: {}", entry);
        entries.add(entry);
        lockCondition.signal();

        return true;
    } finally {
        internalLock.unlock();
        lock.unlock();
    }
}
项目:pnc-repressurized    文件:AirHandler.java   
/**
 * Retrieves a list of all the connecting pneumatics. It takes sides in account.
 *
 * @return a list of face->air-handler pairs
 */
@Override
public List<Pair<EnumFacing, IAirHandler>> getConnectedPneumatics() {
    List<Pair<EnumFacing, IAirHandler>> teList = new ArrayList<>();
    for (IAirHandler specialConnection : specialConnectedHandlers) {
        teList.add(new ImmutablePair<>(null, specialConnection));
    }
    for (EnumFacing direction : EnumFacing.VALUES) {
        TileEntity te = getTileCache()[direction.ordinal()].getTileEntity();
        IPneumaticMachine machine = ModInteractionUtils.getInstance().getMachine(te);
        if (machine != null && parentPneumatic.getAirHandler(direction) == this && machine.getAirHandler(direction.getOpposite()) != null) {
            teList.add(new ImmutablePair<>(direction, machine.getAirHandler(direction.getOpposite())));
        }
    }
    if (airListener != null) airListener.addConnectedPneumatics(teList);
    return teList;
}
项目:PACE    文件:LocalEncryptionKeyContainer.java   
@Override
public byte[] getKey(String id, int version, int length) throws IllegalKeyRequestException {
  checkArgument(id != null, "id is null");
  checkArgument(version >= 0, "version is negative");
  checkArgument(length > 0, "length is non-positive");

  Map<Integer,KeyWithVersion> versionedKeys = encryptionKeys.get(new KeyLookup(id, length));
  if (versionedKeys == null) {
    throw new IllegalKeyRequestException(getMessage(Pair.of("id", id), Pair.of("length", length)));
  }

  KeyWithVersion key = versionedKeys.get(version);
  if (key == null) {
    throw new IllegalKeyRequestException(getMessage(Pair.of("id", id), Pair.of("length", length), Pair.of("version", version)));
  }

  return key.key;
}
项目:InControl    文件:Tools.java   
public static Pair<Float, ItemStack> parseStackWithFactor(String name) {
    int i = 0;
    while (i < name.length() && (Character.isDigit(name.charAt(i)) || name.charAt(i) == '.')) {
        i++;
    }
    if (i < name.length() && name.charAt(i) == '=') {
        String f = name.substring(0, i);
        float v;
        try {
            v = Float.parseFloat(f);
        } catch (NumberFormatException e) {
            v = 1.0f;
        }
        return Pair.of(v, parseStack(name.substring(i+1)));
    }

    return Pair.of(1.0f, parseStack(name));
}
项目:SamaGamesCore    文件:GameLoginHandler.java   
@Override
public JoinResponse requestJoin(UUID player, JoinResponse response)
{
    if (api.getGame() != null)
    {
        Game game = api.getGame();

        Pair<Boolean, String> gameResponse = game.canJoinGame(player, false);

        if (gameResponse.getKey())
        {
            response.allow();
        }
        else
        {
            response.disallow(gameResponse.getValue());
            return response;
        }

        response = checkState(game, response, player);
    }

    return response;
}
项目:talchain    文件:EthashTest.java   
@Test
    public void cacheTestFast() {
        EthashAlgo ethash = new EthashAlgo();
        byte[] seed = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~".getBytes();
        long cacheSize = 1024;
        long fullSize = 1024 * 32;
        int[] cache = ethash.makeCache(cacheSize, seed);


        Assert.assertArrayEquals(intsToBytes(cache, false), Hex.decode("2da2b506f21070e1143d908e867962486d6b0a02e31d468fd5e3a7143aafa76a14201f63374314e2a6aaf84ad2eb57105dea3378378965a1b3873453bb2b78f9a8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995ca8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995ca8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995c259440b89fa3481c2c33171477c305c8e1e421f8d8f6d59585449d0034f3e421808d8da6bbd0b6378f567647cc6c4ba6c434592b198ad444e7284905b7c6adaf70bf43ec2daa7bd5e8951aa609ab472c124cf9eba3d38cff5091dc3f58409edcc386c743c3bd66f92408796ee1e82dd149eaefbf52b00ce33014a6eb3e50625413b072a58bc01da28262f42cbe4f87d4abc2bf287d15618405a1fe4e386fcdafbb171064bd99901d8f81dd6789396ce5e364ac944bbbd75a7827291c70b42d26385910cd53ca535ab29433dd5c5714d26e0dce95514c5ef866329c12e958097e84462197c2b32087849dab33e88b11da61d52f9dbc0b92cc61f742c07dbbf751c49d7678624ee60dfbe62e5e8c47a03d8247643f3d16ad8c8e663953bcda1f59d7e2d4a9bf0768e789432212621967a8f41121ad1df6ae1fa78782530695414c6213942865b2730375019105cae91a4c17a558d4b63059661d9f108362143107babe0b848de412e4da59168cce82bfbff3c99e022dd6ac1e559db991f2e3f7bb910cefd173e65ed00a8d5d416534e2c8416ff23977dbf3eb7180b75c71580d08ce95efeb9b0afe904ea12285a392aff0c8561ff79fca67f694a62b9e52377485c57cc3598d84cac0a9d27960de0cc31ff9bbfe455acaa62c8aa5d2cce96f345da9afe843d258a99c4eaf3650fc62efd81c7b81cd0d534d2d71eeda7a6e315d540b4473c80f8730037dc2ae3e47b986240cfc65ccc565f0d8cde0bc68a57e39a271dda57440b3598bee19f799611d25731a96b5dbbbefdff6f4f656161462633030d62560ea4e9c161cf78fc96a2ca5aaa32453a6c5dea206f766244e8c9d9a8dc61185ce37f1fc804459c5f07434f8ecb34141b8dcae7eae704c950b55556c5f40140c3714b45eddb02637513268778cbf937a33e4e33183685f9deb31ef54e90161e76d969587dd782eaa94e289420e7c2ee908517f5893a26fdb5873d68f92d118d4bcf98d7a4916794d6ab290045e30f9ea00ca547c584b8482b0331ba1539a0f2714fddc3a0b06b0cfbb6a607b8339c39bcfd6640b1f653e9d70ef6c985b"));
        int[] i = ethash.calcDatasetItem(cache, 0);
        Assert.assertArrayEquals(intsToBytes(i, false), Hex.decode("b1698f829f90b35455804e5185d78f549fcb1bdce2bee006d4d7e68eb154b596be1427769eb1c3c3e93180c760af75f81d1023da6a0ffbe321c153a7c0103597"));
//
        byte[] blockHash = "~~~X~~~~~~~~~~~~~~~~~~~~~~~~~~~~".getBytes();
        long nonce = 0x7c7c597cL;
        Pair<byte[], byte[]> pair = ethash.hashimotoLight(fullSize, cache, blockHash, longToBytes(nonce));

        // comparing mix hash
        Assert.assertArrayEquals(pair.getLeft(), Hex.decode("d7b668b90c2f26961d98d7dd244f5966368165edbce8cb8162dd282b6e5a8eae"));
        // comparing the final hash
        Assert.assertArrayEquals(pair.getRight(), Hex.decode("b8cb1cb3ac1a7a6e12c4bc90f2779ef97e661f7957619e677636509d2f26055c"));

        System.out.println(Hex.toHexString(pair.getLeft()));
        System.out.println(Hex.toHexString(pair.getRight()));
    }
项目:saluki    文件:CommonProto2Java.java   
private Pair<String, String> packageClassName(FileOptions options) {
  String packageName = null;
  String className = null;
  for (Map.Entry<FieldDescriptor, Object> entry : options.getAllFields().entrySet()) {
    if (entry.getKey().getName().equals("java_package")) {
      packageName = entry.getValue().toString();
    }
    if (entry.getKey().getName().equals("java_outer_classname")) {
      className = entry.getValue().toString();
    }
  }
  if (packageName != null && className != null) {
    return new ImmutablePair<String, String>(packageName, className);
  }
  return null;
}
项目:OperatieBRP    文件:ZoekwaardenLengteValidator.java   
@Override
public Optional<Antwoord> apply(final WebserviceBericht vraag) {
    Map<Integer, String> rubrieken = vraag.getZoekCriteria().stream()
            .map(categorie -> categorie.getElementen().entrySet().stream().map(e -> Pair.of(categorie, e)))
            .flatMap(Function.identity())
            .filter(this::isGeenLegeWaarde)
            .filter(this::isExactZoeken)
            .filter(this::heeftIncorrecteLengte)
            .filter(this::isGeenGedeeltelijkOnbekendeDatum)
            .collect(toMap(this::format, this::extractWaarde));

    return rubrieken.isEmpty()
            ? Optional.empty()
            : Optional.of(Antwoorden.foutief(
                    AntwoordBerichtResultaat.TECHNISCHE_FOUT_026,
                    rubrieken.entrySet().stream()
                            .sorted(Comparator.comparing(Map.Entry::getKey))
                            .map(e -> e.getKey() + "=" + e.getValue())
                            .collect(Collectors.joining(", "))));
}
项目:ExPetrum    文件:FoodManager.java   
public static Pair<Float, EnumMap<FoodGroup, Float>> provideFoodStats(ItemStack stack)
{
    if (simpleMappings.containsKey(Pair.of(stack.getItem(), stack.getMetadata())))
    {
        return simpleMappings.get(Pair.of(stack.getItem(), stack.getMetadata()));
    }
    else
    {
        for (Function<ItemStack, Pair<Float, EnumMap<FoodGroup, Float>>> f : mappings)
        {
            Pair<Float, EnumMap<FoodGroup, Float>> ret = f.apply(stack);
            if (ret != null)
            {
                return ret;
            }
        }

        return null;
    }
}
项目:dremio-oss    文件:TestEarlyLimit0Optimization.java   
@Test
public void mod() throws Exception {
  final String query = "select mod(student_id, 3), mod(age, 2), mod(studentnum, 1235) from " + stddevTypesViewName + " where student_id=10";

  @SuppressWarnings("unchecked")
  final List<Pair<SchemaPath, MajorType>> expectedSchema = Lists.newArrayList(
      Pair.of(SchemaPath.getSimplePath("EXPR$0"), Types.optional(MinorType.INT)),
      Pair.of(SchemaPath.getSimplePath("EXPR$1"), Types.optional(MinorType.INT)),
      Pair.of(SchemaPath.getSimplePath("EXPR$2"), Types.optional(MinorType.INT)));

  testBuilder()
      .sqlQuery(query)
      .ordered()
      .baselineColumns("EXPR$0", "EXPR$1", "EXPR$2")
      .baselineValues(1, 0, 304)
      .go();
  testBuilder()
      .sqlQuery(wrapLimit0(query))
      .schemaBaseLine(expectedSchema)
      .go();

  checkThatQueryPlanIsOptimized(query);
}
项目:MegaSparkDiff    文件:JdbcToJdbcTest.java   
private Pair<Dataset<Row>, Dataset<Row>> returnDiff(String table1, String table2)
{
    AppleTable leftAppleTable = SparkFactory.parallelizeJDBCSource("org.hsqldb.jdbc.JDBCDriver",
            "jdbc:hsqldb:hsql://127.0.0.1:9001/testDb",
            "SA",
            "",
            "(select * from " + table1 + ")", "table1");

    AppleTable rightAppleTable = SparkFactory.parallelizeJDBCSource("org.hsqldb.jdbc.JDBCDriver",
            "jdbc:hsqldb:hsql://127.0.0.1:9001/testDb",
            "SA",
            "",
            "(select * from " + table2 + ")", "table2");

    return SparkCompare.compareAppleTables(leftAppleTable, rightAppleTable);
}
项目:bech32    文件:SegwitAddressUtil.java   
public Pair<Byte, byte[]> decode(String hrp, String addr) throws Exception {

        Pair<byte[], byte[]> p = Bech32Util.getInstance().bech32Decode(addr);

        byte[] hrpgot = p.getLeft();
        if (!hrp.equals(new String(hrpgot)))    {
            throw new Exception("mismatching bech32 human readeable part");
        }

        byte[] data = p.getRight();
        byte[] decoded = convertBits(Bytes.asList(Arrays.copyOfRange(data, 1, data.length)), 5, 8, false);
        if(decoded.length < 2 || decoded.length > 40)   {
            throw new Exception("invalid decoded data length");
        }

        byte witnessVersion = data[0];
        if (witnessVersion > 16)   {
            throw new Exception("invalid decoded witness version");
        }

        if (witnessVersion == 0 && decoded.length != 20 && decoded.length != 32)   {
            throw new Exception("decoded witness version 0 with unknown length");
        }

        return Pair.of(witnessVersion, decoded);
    }
项目:openvisualtraceroute    文件:WWJPanel.java   
/**
 * Highlight the given annotation
 *
 * @param annotation
 * @param point
 */
private void highlightAnnotation(final LabeledPath label, final GeoPoint point) {
    final ScreenAnnotation annotation = label.getAnnotation();
    if (_lastSelection != null) {
        final LabeledPath lastSelectedLabel = _lastSelection.getLeft();
        final ScreenAnnotation lastSelectedAnnotation = lastSelectedLabel.getAnnotation();
        final GeoPoint lastSelectedPoint = _lastSelection.getRight();
        if (_mapShowLabel) {
            lastSelectedAnnotation.setAttributes(createAnnotationAttr(false, lastSelectedPoint.getCountryFlag(IMAGE_RESOLUTION), getText(lastSelectedPoint)));
            lastSelectedAnnotation.setAlwaysOnTop(false);
        } else {
            _renderableLayer.removeRenderable(lastSelectedLabel);
        }
    }
    final ImageIcon image = point.getCountryFlag(IMAGE_RESOLUTION);
    final String text = getText(point);
    annotation.setAttributes(createAnnotationAttr(true, image, text));
    annotation.setAlwaysOnTop(true);
    if (!_mapShowLabel) {
        _renderableLayer.addRenderable(label);
        _controller.redraw();
    }
    _lastSelection = Pair.of(label, point);
}
项目:camunda-task-dispatcher    文件:TaskProcessorRegistryImplTest.java   
@Test
public void testProcess() {
    String taskName = "task";
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(TaskProcessorRegistryImpl.class, "taskProcessorMap")
            , registry
            , ImmutableListMultimap.builder()
                                   .put(taskName, Pair.of(Objects.class, taskProcessor))
                                   .build()
    );

    registry.process(taskName, "some body");

    Mockito.verify(taskMapper, Mockito.atLeastOnce()).map(Mockito.anyString(), Mockito.any());
    Mockito.verify(taskProcessor, Mockito.atLeastOnce()).process(Mockito.any());
}
项目:smaph    文件:CachedWAT2Annotator.java   
@Override
protected JSONObject queryJson(String baseUrl, List<Pair<String, String>> getParameters) throws Exception {

    URI requestUri = getRequestUri(baseUrl, getParameters);

    String cacheKey = requestUri.toString();
    byte[] compressed = url2jsonCache.get(cacheKey);
    if (compressed != null) {
        try {
            String jsonString = SmaphUtils.decompress(compressed);
            return new JSONObject(jsonString);
        } catch (IOException e) {
            LOG.warn("Broken Gzip, re-downloading");
        }
    }

    increaseFlushCounter();
    JSONObject obj = super.queryJson(baseUrl, getParameters);
    url2jsonCache.put(cacheKey, SmaphUtils.compress(obj.toString()));
    return obj;

}
项目:smarti    文件:NamedEntityCollectorTest.java   
private void assertNerProcessingResults(ProcessingData processingData, List<Pair<String,Hint[]>> expected) {
    expected = new LinkedList<>(expected); //copy so we can remove
    Conversation conv = processingData.getConversation();
    Assert.assertFalse(conv.getTokens().isEmpty());
    for(Token token : conv.getTokens()){
        log.debug("Token(idx: {}, span[{},{}], type: {}): {}", token.getMessageIdx(), token.getStart(), token.getEnd(), token.getType(), token.getValue());
        Assert.assertNotNull(token.getType());
        Assert.assertTrue(conv.getMeta().getLastMessageAnalyzed() < token.getMessageIdx());
        Assert.assertTrue(conv.getMessages().size() > token.getMessageIdx());
        Message message = conv.getMessages().get(token.getMessageIdx());
        Assert.assertTrue(message.getOrigin() == Origin.User);
        Assert.assertTrue(token.getStart() >= 0);
        Assert.assertTrue(token.getEnd() > token.getStart());
        Assert.assertTrue(token.getEnd() <= message.getContent().length());
        Assert.assertEquals(message.getContent().substring(token.getStart(), token.getEnd()), String.valueOf(token.getValue()));
        Pair<String,Hint[]> p = expected.remove(0);
        Assert.assertEquals("Wrong Named Entity",p.getKey(), token.getValue());
        for(Hint hint : p.getValue()){
            Assert.assertTrue("Missing expected hint " + hint,token.hasHint(hint));
        }
    }
}
项目:bullet-core    文件:ProjectionTest.java   
@Test
public void testRepeatedProjections() {
    Projection first = new Projection();
    first.setFields(singletonMap("field", "id"));

    Projection second = new Projection();
    second.setFields(singletonMap("map_field.foo", "bar"));

    RecordBox box = RecordBox.get().add("field", "test").addMap("map_field", Pair.of("foo", "baz"));

    BulletRecord record = box.getRecord();
    BulletRecord firstProjection = first.project(record);
    BulletRecord secondProjection = second.project(record);

    box = RecordBox.get().add("field", "test").addMap("map_field", Pair.of("foo", "baz"));
    BulletRecord expectedOriginal = box.getRecord();
    Assert.assertEquals(record, expectedOriginal);

    box = RecordBox.get().add("id", "test");
    BulletRecord expectedFirstProjection = box.getRecord();
    Assert.assertEquals(firstProjection, expectedFirstProjection);

    box = RecordBox.get().add("bar", "baz");
    BulletRecord expectedSecondProjection = box.getRecord();
    Assert.assertEquals(secondProjection, expectedSecondProjection);
}
项目:dremio-oss    文件:TestFunctionsWithTypeExpoQueries.java   
/**
 * In the following query, the extract function would be borrowed from Calcite,
 * which asserts the return type as be BIG-INT
 */
@Test
public void testExtractSecond() throws Exception {
  String query = "select extract(second from time '02:30:45.100') as col \n" +
      "from cp.`tpch/region.parquet` \n" +
      "limit 0";

  List<Pair<SchemaPath, MajorType>> expectedSchema = Lists.newArrayList();
  MajorType majorType = Types.required(MinorType.BIGINT);
  expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));

  testBuilder()
      .sqlQuery(query)
      .schemaBaseLine(expectedSchema)
      .build()
      .run();
}
项目:MegaSparkDiff    文件:JdbcToJdbcTest.java   
@Test
public void testCompareAFewDifferences()
{
    Pair<Dataset<Row>,Dataset<Row>> pair = returnDiff("Test1","Test3");

    //the expectation is that there are only a few differences
    if (pair.getLeft().count() != 2)
        Assert.fail("Expected 2 differences coming from left table." +
                "  Instead, found " + pair.getLeft().count() + ".");

    if (pair.getRight().count() != 2)
        Assert.fail("Expected 2 differences coming from right table." +
                "  Instead, found " + pair.getRight().count() + ".");
}
项目:talchain    文件:EthashAlgo.java   
public long mineLight(long fullSize, final int[] cache, byte[] blockHeaderTruncHash, long difficulty, long startNonce) {
    long nonce = startNonce;
    BigInteger target = valueOf(2).pow(256).divide(valueOf(difficulty));
    while(!Thread.currentThread().isInterrupted()) {
        nonce++;
        Pair<byte[], byte[]> pair = hashimotoLight(fullSize, cache, blockHeaderTruncHash, longToBytes(nonce));
        BigInteger h = new BigInteger(1, pair.getRight() /* ?? */);
        if (h.compareTo(target) < 0) break;
    }
    return nonce;
}
项目:CustomWorldGen    文件:MinecraftForgeClient.java   
public static ChunkCache getRegionRenderCache(World world, BlockPos pos)
{
    int x = pos.getX() & ~0xF;
    int y = pos.getY() & ~0xF;
    int z = pos.getZ() & ~0xF;
    return regionCache.getUnchecked(Pair.of(world, new BlockPos(x, y, z)));
}
项目:twister2    文件:MPIMultiMessageDeserializer.java   
private Object buildMessage(MPIMessage mpiMessage, List<MPIBuffer> message, int length) {
  MessageType type = mpiMessage.getType();
  if (keyed) {
    Pair<Object, Integer> keyPair = KeyDeserializer.deserializeKey(mpiMessage.getKeyType(),
        message, serializer);

    return DataDeserializer.deserializeData(message, length - keyPair.getValue(),
        serializer, type);
  } else {
    return DataDeserializer.deserializeData(message, length, serializer, type);
  }
}
项目:ExPetrum    文件:TreeGenImpl.java   
public static void leavesGenEucalyptusImpl(Pair<ITreeGenerator, BlockPos> p, int height)
{
    BlockPos start = p.getRight().up(height + 2);
    for (int i = 0; i < 6 + p.getLeft().genWorld().rand.nextInt(3) && i < height - 1; ++i)
    {
        BlockPos at = start.down(i);
        leavesGenHickoryImplLayer(p.getKey(), p.getKey().genWorld(), at, i);
    }
}
项目:saluki    文件:PrintMessageFile.java   
private Map<String, Pair<DescriptorProto, List<FieldDescriptorProto>>> transform(
    DescriptorProto sourceMessageDesc) {
  Map<String, Pair<DescriptorProto, List<FieldDescriptorProto>>> nestedFieldMap =
      Maps.newHashMap();
  sourceMessageDesc.getNestedTypeList().forEach(new Consumer<DescriptorProto>() {

    @Override
    public void accept(DescriptorProto t) {
      nestedFieldMap.put(t.getName(),
          new ImmutablePair<DescriptorProto, List<FieldDescriptorProto>>(t, t.getFieldList()));
    }

  });
  return nestedFieldMap;
}
项目:AppCoins-ethereumj    文件:EthashAlgoSlow.java   
/**
 * This the slower miner version which uses only cache thus taking much less memory than
 * regular {@link #mine} method
 */
public long mineLight(long fullSize, final byte[][] cache, byte[] blockHeaderTruncHash, long difficulty) {
    BigInteger target = valueOf(2).pow(256).divide(valueOf(difficulty));
    long nonce = new Random().nextLong();
    while(!Thread.currentThread().isInterrupted()) {
        nonce++;
        Pair<byte[], byte[]> pair = hashimotoLight(fullSize, cache, blockHeaderTruncHash, longToBytes(nonce));
        BigInteger h = new BigInteger(1, pair.getRight() /* ?? */);
        if (h.compareTo(target) < 0) break;
    }
    return nonce;
}
项目:schedule-dataflow-appengine    文件:DataFlowUtils.java   
public static Pair<JobStatus,String> isJobRunning(DataflowPipelineOptions options, String jobName, int jobIntervalinMinutes) throws IOException {
    DataflowClient dataflowClient = DataflowClient.create(options);
    ListJobsResponse currentJobs = dataflowClient.listJobs(null);
    final List<Job> jobs = currentJobs.getJobs();
    if (jobs!=null) {
        List<Job> runningJobs = jobs.stream()
                .filter(job -> job.getName().startsWith(jobName))
                .filter(job -> job.getCurrentState().equals("JOB_STATE_RUNNING"))
                .collect(Collectors.toList());
        //check if x minutes have passed sine last run
        if (runningJobs.size() == 0) {
            Optional<Job> job_state_done = jobs.stream()
                    .filter(job -> job.getName().startsWith(jobName))
                    .filter(job -> job.getCurrentState().equals("JOB_STATE_DONE"))
                    .max(Comparator.comparingLong(p -> ISODateTimeFormat.dateTimeParser().parseDateTime(p.getCreateTime()).getMillis()));
            if (job_state_done.isPresent()) {
                long millis = ISODateTimeFormat.dateTimeParser().parseDateTime(job_state_done.get().getCreateTime()).getMillis();
                long passedMinutes = (System.currentTimeMillis() - millis) / 1000 / 60;
                if (passedMinutes < jobIntervalinMinutes)
                    return Pair.of(JobStatus.QuitePeriod,job_state_done.get().getCreateTime());
                else
                    return Pair.of(JobStatus.Nothing,"");
            }

        } else
            return Pair.of(JobStatus.Running,runningJobs.get(0).getCreateTime());
    }
    return Pair.of(JobStatus.Nothing,"");
}
项目:PEF    文件:CLToolChangedPCAPIT.java   
@Test
public void testIPv6UDPLLMNR() throws IOException {
    final Pair<ParseGraph, ParseGraph> values = CLToolTestUtil.getPacketValues(new File(_basePath + "/1ipv6udpllmnr.pcap"), _tempFolder.newFile(), CLToolTestUtil.PEF_COMMAND);

    final ParseGraph preValues = values.getLeft();
    final ParseGraph postValues = values.getRight();

    assertAddressesDiffer(preValues, postValues);

    assertEq(TestUtil.valueAtDepth(preValues, "udpchecksum", 0), new byte[]{(byte) 0x4F, (byte) 0x84});
    assertEq(TestUtil.valueAtDepth(postValues, "udpchecksum", 0), new byte[]{(byte) 0xD2, 0x0C});
}
项目:pnc-repressurized    文件:TileEntityVortexTube.java   
private void updateConnections() {
    List<Pair<EnumFacing, IAirHandler>> connections = getAirHandler(null).getConnectedPneumatics();
    Arrays.fill(sidesConnected, false);
    for (Pair<EnumFacing, IAirHandler> entry : connections) {
        sidesConnected[entry.getKey().ordinal()] = true;
    }
}
项目:nest-spider    文件:WebpageDAO.java   
public Pair<Map<String, List<Bucket>>, List<Webpage>> relatedInfo(String query, int size) {
    SearchResponse response = search().setQuery(QueryBuilders.queryStringQuery(query))
            .addAggregation(AggregationBuilders.terms("People").field("namedEntity.nr"))
            .addAggregation(AggregationBuilders.terms("Location").field("namedEntity.ns"))
            .addAggregation(AggregationBuilders.terms("Institution").field("namedEntity.nt"))
            .addAggregation(AggregationBuilders.terms("Keyword").field("keyword"))
            .setSize(size).get();
    Map<String, List<Bucket>> map = new HashMap<>();
    map.put("People", response.getAggregations().get("People"));
    map.put("Location", response.getAggregations().get("Location"));
    map.put("Institution", response.getAggregations().get("Institution"));
    map.put("Keyword", response.getAggregations().get("Keyword"));
    return Pair.of(map, hitsToList(response.getHits()));
}
项目:pnc-repressurized    文件:TileEntityPressureTube.java   
private void updateConnections() {
    sidesConnected = new boolean[6];

    List<Pair<EnumFacing, IAirHandler>> connections = getAirHandler(null).getConnectedPneumatics();
    Arrays.fill(sidesConnected, false);
    for (Pair<EnumFacing, IAirHandler> entry : connections) {
        sidesConnected[entry.getKey().ordinal()] = true;
    }

    boolean hasModule = false;
    for (int i = 0; i < 6; i++) {
        if (modules[i] != null) {
            hasModule = true;
            break;
        }
    }

    int sidesCount = 0;
    for (boolean bool : sidesConnected) {
        if (bool) sidesCount++;
    }
    if (sidesCount == 1 && !hasModule) {
        for (int i = 0; i < 6; i++) {
            if (sidesConnected[i]) {
                EnumFacing opposite = EnumFacing.getFront(i).getOpposite();
                if (isConnectedTo(opposite)) sidesConnected[opposite.ordinal()] = true;
                break;
            }
        }
    }
    for (int i = 0; i < 6; i++) {
        if (modules[i] != null && modules[i].isInline()) sidesConnected[i] = false;
    }
}
项目:pnc-repressurized    文件:TileEntityPressureChamberValve.java   
@Override
public void addConnectedPneumatics(List<Pair<EnumFacing, IAirHandler>> teList) {
    if (accessoryValves != null) {
        for (TileEntityPressureChamberValve valve : accessoryValves) {
            if (valve != this) teList.add(new ImmutablePair<>(null, valve.getAirHandler(null)));
        }
    }
}
项目:nest-spider    文件:CommonSpiderService.java   
public String exportQuartz() {
    Map<String, Long> result = new HashMap<>();
    for(JobKey key:manager.listAll(QUARTZ_JOB_GROUP_NAME)) {
        Pair<JobDetail, Trigger> pair = manager.findInfo(key);
        String name = ((SpiderInfo)pair.getLeft().getJobDataMap().get("spiderInfo")).getId();
        Long hours = ((SimpleTrigger)((SimpleScheduleBuilder)pair.getRight().getScheduleBuilder()).build()).getRepeatInterval()/DateBuilder.MILLISECONDS_IN_HOUR;
        result.put(name, hours);
    }
    return gson.toJson(result);
}
项目:NGB-master    文件:FeatureIndexManagerTest.java   
private void checkDuplicates(List<VcfIndexEntry> entryList) {
    Map<Pair<Integer, Integer>, FeatureIndexEntry> duplicateMap = new HashMap<>();
    entryList.stream().forEach(e -> {
        Pair<Integer, Integer> indexPair = new ImmutablePair<>(e.getStartIndex(), e.getEndIndex());
        Assert.assertFalse(String.format("Found duplicate: %d, %d", e.getStartIndex(), e.getEndIndex()),
                duplicateMap.containsKey(indexPair));
        duplicateMap.put(indexPair, e);
    });
}
项目:NGB-master    文件:NCBIShortVarManager.java   
/**
 * Retrieves variations from snp database in given region
 *
 * @param organism   -- organism name
 * @param start      -- start position
 * @param finish     -- end position
 * @param chromosome -- chromosome number
 * @return list of found variations
 * @throws ExternalDbUnavailableException
 */
public List<Variation> fetchVariationsOnRegion(
        String organism, String start, String finish, String chromosome)
        throws ExternalDbUnavailableException {

    String term = String.format("%s:%s[Base Position] AND \"%s\"[CHR] AND \"%s\"[ORGN]",
            start, finish, chromosome, organism);
    String searchResultXml = ncbiAuxiliaryManager.searchWithHistory(NCBIDatabase.SNP.name(), term, MAX_RESULT);

    Pair<String, String> stringStringPair =
            ncbiGeneInfoParser.parseHistoryResponse(searchResultXml, NCBIUtility.NCBI_SEARCH);

    String queryKey = stringStringPair.getLeft();
    String webEnv = stringStringPair.getRight();

    String dataXml = ncbiAuxiliaryManager.fetchWithHistory(queryKey, webEnv, NCBIDatabase.SNP);

    ExchangeSet snpResultJaxb = null;

    try {

        JAXBContext jaxbContext = JAXBContext.newInstance("com.epam.catgenome.manager.externaldb.bindings.dbsnp");
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        StringReader reader = new StringReader(dataXml);
        Object uniprotObject = unmarshaller.unmarshal(reader);

        if (uniprotObject instanceof ExchangeSet) {
            snpResultJaxb = (ExchangeSet) uniprotObject;
        }

    } catch (JAXBException e) {
        throw new ExternalDbUnavailableException("Error parsing ncbi snp response", e);
    }
    return getResultList(snpResultJaxb);
}
项目:CustomWorldGen    文件:AnimationTESR.java   
public void renderTileEntityFast(T te, double x, double y, double z, float partialTick, int breakStage, VertexBuffer renderer)
{
    if(!te.hasCapability(CapabilityAnimation.ANIMATION_CAPABILITY, null))
    {
        return;
    }
    if(blockRenderer == null) blockRenderer = Minecraft.getMinecraft().getBlockRendererDispatcher();
    BlockPos pos = te.getPos();
    IBlockAccess world = MinecraftForgeClient.getRegionRenderCache(te.getWorld(), pos);
    IBlockState state = world.getBlockState(pos);
    if(state.getPropertyNames().contains(Properties.StaticProperty))
    {
        state = state.withProperty(Properties.StaticProperty, false);
    }
    if(state instanceof IExtendedBlockState)
    {
        IExtendedBlockState exState = (IExtendedBlockState)state;
        if(exState.getUnlistedNames().contains(Properties.AnimationProperty))
        {
            float time = Animation.getWorldTime(getWorld(), partialTick);
            Pair<IModelState, Iterable<Event>> pair = te.getCapability(CapabilityAnimation.ANIMATION_CAPABILITY, null).apply(time);
            handleEvents(te, time, pair.getRight());

            // TODO: caching?
            IBakedModel model = blockRenderer.getBlockModelShapes().getModelForState(exState.getClean());
            exState = exState.withProperty(Properties.AnimationProperty, pair.getLeft());

            renderer.setTranslation(x - pos.getX(), y - pos.getY(), z - pos.getZ());

            blockRenderer.getBlockModelRenderer().renderModel(world, model, exState, pos, renderer, false);
        }
    }
}