org.javatuples.Pair - java examples

Here are the examples of the java api org.javatuples.Pair taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

131 Examples 7

19 View Complete Implementation : SeparatorContainer.java
Copyright Apache License 2.0
Author : igloo-project
public clreplaced SeparatorContainer extends WebMarkupContainer {

    private static final long serialVersionUID = 7764638101080488816L;

    private Pair<Component, Component> components;

    public SeparatorContainer(String id) {
        super(id);
    }

    public SeparatorContainer components(Component component1, Component component2) {
        components = new Pair<Component, Component>(component1, component2);
        return this;
    }

    @Override
    protected void onConfigure() {
        super.onConfigure();
        if (components != null) {
            components.getValue0().configure();
            components.getValue1().configure();
            setVisible(components.getValue0().determineVisibility() && components.getValue1().determineVisibility());
        } else {
            setVisible(false);
        }
    }
}

19 View Complete Implementation : SparseSGD.java
Copyright GNU Lesser General Public License v3.0
Author : sanity
static void updateUnnormalizedGradientForInstance(double[] weights, double[] contributionsToTheGradient, SparseClreplacedifierInstance instance) {
    // could do this with a map for truly sparse instances...but
    double postiveClreplacedProbability = probabilityOfThePositiveClreplaced(weights, instance);
    Pair<int[], double[]> sparseAttributes = instance.getSparseAttributes();
    int[] indices = sparseAttributes.getValue0();
    double[] values = sparseAttributes.getValue1();
    for (int i = 0; i < indices.length; i++) {
        int featureIndex = indices[i];
        contributionsToTheGradient[featureIndex] += gradientContributionOfAFeatureValue((Double) instance.getLabel(), postiveClreplacedProbability, values[i]);
    }
}

19 View Complete Implementation : PropertyServiceImpl.java
Copyright Apache License 2.0
Author : igloo-project
@Override
public <T> String getreplacedtring(final PropertyId<T> propertyId) {
    Pair<Converter<String, T>, Supplier2<T>> information = getRegistrationInformation(propertyId);
    String valuereplacedtring = getreplacedtringUnsafe(propertyId);
    if (valuereplacedtring == null) {
        T defaultValue = information.getValue1().get();
        if (defaultValue != null) {
            valuereplacedtring = information.getValue0().reverse().convert(defaultValue);
            LOGGER.debug(String.format("Property '%1s' has no value, fallback on default value.", propertyId));
        } else {
            LOGGER.info(String.format("Property '%1s' has no value and default value is undefined.", propertyId));
        }
    }
    return valuereplacedtring;
}

19 View Complete Implementation : PropertyServiceImpl.java
Copyright Apache License 2.0
Author : igloo-project
private <T> Pair<Converter<String, T>, Supplier2<T>> getRegistrationInformation(PropertyId<T> propertyId) {
    PropertyIdTemplate<T, ?> template = propertyId.getTemplate();
    @SuppressWarnings("unchecked")
    Pair<Converter<String, T>, Supplier2<T>> information = (Pair<Converter<String, T>, Supplier2<T>>) propertyInformationMap.get(template != null ? template : propertyId);
    if (information == null || information.getValue0() == null) {
        throw new PropertyServiceIncompleteRegistrationException(String.format("The following property was not properly registered: %1s", propertyId));
    }
    return information;
}

19 View Complete Implementation : OldTreeBuilder.java
Copyright GNU Lesser General Public License v3.0
Author : sanity
private Pair<? extends OldBranch, Double> getBestNodePair(OldBranch parent, List<T> trainingData) {
    // should not be doing the following operation every time we call growTree
    boolean smallTrainingSet = isSmallTrainingSet(trainingData);
    Pair<? extends OldBranch, Double> bestPair = null;
    // TODO: make this lazy in the sense that only numeric attributes that are not randomly rignored should have this done
    for (final Entry<String, AttributeCharacteristics> attributeCharacteristicsEntry : attributeCharacteristics.entrySet()) {
        if (this.attributeIgnoringStrategy.ignoreAttribute(attributeCharacteristicsEntry.getKey(), parent)) {
            continue;
        }
        Pair<? extends OldBranch, Double> thisPair = null;
        Pair<? extends OldBranch, Double> numericPair = null;
        Pair<? extends OldBranch, Double> categoricalPair = null;
        if (!smallTrainingSet && attributeCharacteristicsEntry.getValue().isNumber) {
            numericPair = createNumericBranch(parent, attributeCharacteristicsEntry.getKey(), trainingData);
        } else if (!attributeCharacteristicsEntry.getValue().isNumber) {
            categoricalPair = createCategoricalNode(parent, attributeCharacteristicsEntry.getKey(), trainingData);
        }
        if (numericPair != null) {
            thisPair = numericPair;
        } else {
            // (numericPair.getValue1() > categoricalPair.getValue1()) ? numericPair : categoricalPair;
            thisPair = categoricalPair;
        }
        if (bestPair == null || (thisPair != null && bestPair != null && thisPair.getValue1() > bestPair.getValue1())) {
            bestPair = thisPair;
        }
    }
    return bestPair;
}

19 View Complete Implementation : SimulateUtils.java
Copyright Apache License 2.0
Author : harmony-dev
public clreplaced SimulateUtils {

    private static Pair<List<Deposit>, List<BLS381.KeyPair>> cachedDeposits = Pair.with(new ArrayList<>(), new ArrayList<>());

    public static synchronized Pair<List<Deposit>, List<BLS381.KeyPair>> getAnyDeposits(Random rnd, BeaconChainSpec spec, int count, boolean isProofVerifyEnabled) {
        if (count > cachedDeposits.getValue0().size()) {
            Pair<List<Deposit>, List<BLS381.KeyPair>> newDeposits = generateRandomDeposits(UInt64.valueOf(cachedDeposits.getValue0().size()), rnd, spec, count - cachedDeposits.getValue0().size(), isProofVerifyEnabled);
            cachedDeposits.getValue0().addAll(newDeposits.getValue0());
            cachedDeposits.getValue1().addAll(newDeposits.getValue1());
        }
        return Pair.with(cachedDeposits.getValue0().subList(0, count), cachedDeposits.getValue1().subList(0, count));
    }

    public static Deposit getDepositForKeyPair(Random rnd, BLS381.KeyPair keyPair, BeaconChainSpec spec, boolean isProofVerifyEnabled) {
        return getDepositForKeyPair(rnd, keyPair, spec, spec.getConstants().getMaxEffectiveBalance(), isProofVerifyEnabled);
    }

    public static synchronized Deposit getDepositForKeyPair(Random rnd, BLS381.KeyPair keyPair, BeaconChainSpec spec, Gwei initBalance, boolean isProofVerifyEnabled) {
        Hash32 credentials = Hash32.random(rnd);
        List<Hash32> depositProof = Collections.singletonList(Hash32.random(rnd));
        return getDepositForKeyPair(keyPair, credentials, initBalance, depositProof, spec, isProofVerifyEnabled);
    }

    @NotNull
    private static Deposit getDepositForKeyPair(BLS381.KeyPair keyPair, Hash32 withdrawalCredentials, Gwei initBalance, List<Hash32> depositProof, BeaconChainSpec spec, boolean isProofVerifyEnabled) {
        DepositData depositDataWithoutSignature = new DepositData(BLSPubkey.wrap(Bytes48.leftPad(keyPair.getPublic().getEncodedBytes())), withdrawalCredentials, initBalance, BLSSignature.wrap(Bytes96.ZERO));
        BLSSignature signature = BLSSignature.ZERO;
        if (isProofVerifyEnabled) {
            Hash32 msgHash = spec.signing_root(depositDataWithoutSignature);
            UInt64 domain = spec.compute_domain(SignatureDomains.DEPOSIT, Bytes4.ZERO);
            signature = BLSSignature.wrap(BLS381.sign(MessageParameters.create(msgHash, domain), keyPair).getEncoded());
        }
        Deposit deposit = Deposit.create(depositProof, new DepositData(depositDataWithoutSignature.getPubKey(), depositDataWithoutSignature.getWithdrawalCredentials(), depositDataWithoutSignature.getAmount(), signature));
        return deposit;
    }

    public static synchronized List<Deposit> getDepositsForKeyPairs(UInt64 startIndex, Random rnd, List<BLS381.KeyPair> keyPairs, BeaconChainSpec spec, boolean isProofVerifyEnabled) {
        return getDepositsForKeyPairs(startIndex, rnd, keyPairs, spec, spec.getConstants().getMaxEffectiveBalance(), isProofVerifyEnabled);
    }

    public static synchronized List<Deposit> getDepositsForKeyPairs(UInt64 startIndex, Random rnd, List<BLS381.KeyPair> keyPairs, BeaconChainSpec spec, Gwei initBalance, boolean isProofVerifyEnabled) {
        List<Hash32> withdrawalCredentials = generateRandomWithdrawalCredentials(rnd, keyPairs);
        List<List<Hash32>> depositProofs = generateRandomDepositProofs(rnd, keyPairs);
        return getDepositsForKeyPairs(keyPairs, withdrawalCredentials, initBalance, depositProofs, spec, isProofVerifyEnabled);
    }

    @NotNull
    public static List<Deposit> getDepositsForKeyPairs(List<BLS381.KeyPair> keyPairs, List<Hash32> withdrawalCredentials, Gwei initBalance, List<List<Hash32>> depositProofs, BeaconChainSpec spec, boolean isProofVerifyEnabled) {
        List<Deposit> deposits = new ArrayList<>();
        for (int i = 0; i < keyPairs.size(); i++) {
            BLS381.KeyPair keyPair = keyPairs.get(i);
            Hash32 credentials = withdrawalCredentials.get(i);
            List<Hash32> depositProof = depositProofs.get(i);
            deposits.add(getDepositForKeyPair(keyPair, credentials, initBalance, depositProof, spec, isProofVerifyEnabled));
        }
        return deposits;
    }

    @NotNull
    public static List<List<Hash32>> generateRandomDepositProofs(Random rnd, List<BLS381.KeyPair> keyPairs) {
        List<List<Hash32>> depositProofs = new ArrayList<>();
        for (BLS381.KeyPair keyPair : keyPairs) {
            List<Hash32> depositProof = Collections.singletonList(Hash32.random(rnd));
            depositProofs.add(depositProof);
        }
        return depositProofs;
    }

    @NotNull
    public static List<Hash32> generateRandomWithdrawalCredentials(Random rnd, List<BLS381.KeyPair> keyPairs) {
        List<Hash32> withdrawalCredentials = new ArrayList<>();
        for (BLS381.KeyPair keyPair : keyPairs) {
            withdrawalCredentials.add(Hash32.random(rnd));
        }
        return withdrawalCredentials;
    }

    /**
     * Generate withdrawal credentials according to mocked start spec.
     * @See <a href="https://github.com/ethereum/eth2.0-pm/tree/master/interop/mocked_start#generate-deposits"/>
     */
    public static List<Hash32> generateInteropCredentials(UInt64 blsWithdrawalPrefix, List<BLS381.KeyPair> keyPairs) {
        List<Hash32> withdrawalCredentials = new ArrayList<>();
        for (BLS381.KeyPair keyPair : keyPairs) {
            MutableBytes32 credentials = Hashes.sha256(keyPair.getPublic().getEncodedBytes()).mutableCopy();
            credentials.set(0, blsWithdrawalPrefix.toBytes8().get(0));
            withdrawalCredentials.add(Hash32.wrap(credentials.copy()));
        }
        return withdrawalCredentials;
    }

    private static synchronized Pair<List<Deposit>, List<BLS381.KeyPair>> generateRandomDeposits(UInt64 startIndex, Random rnd, BeaconChainSpec spec, int count, boolean isProofVerifyEnabled) {
        List<BLS381.KeyPair> validatorsKeys = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            BLS381.KeyPair keyPair = BLS381.KeyPair.create(PrivateKey.create(Bytes32.random(rnd)));
            validatorsKeys.add(keyPair);
        }
        List<Deposit> deposits = getDepositsForKeyPairs(startIndex, rnd, validatorsKeys, spec, isProofVerifyEnabled);
        return Pair.with(deposits, validatorsKeys);
    }
}

19 View Complete Implementation : ReplacedStepTree.java
Copyright MIT License
Author : pietermartin
public void applyComparatorsOnDb() {
    for (ReplacedStep<?, ?> replacedStep : linearPathToLeafNode()) {
        for (Pair<Traversal.Admin<?, ?>, Comparator<?>> comparatorPair : replacedStep.getSqlgComparatorHolder().getComparators()) {
            replacedStep.getDbComparators().add(comparatorPair);
        }
    }
}

19 View Complete Implementation : DBRequestRuleStore.java
Copyright MIT License
Author : lobobrowser
private static Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> decodeBitMask(final Integer existingPermissions) {
    final PermissionSystem.Permission[] resultPermissions = new PermissionSystem.Permission[RequestKind.numKinds()];
    for (int i = 0; i < resultPermissions.length; i++) {
        resultPermissions[i] = decodeBits(existingPermissions, i + 1);
    }
    final Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> resultPair = Pair.with(decodeBits(existingPermissions, 0), resultPermissions);
    return resultPair;
}

19 View Complete Implementation : TestUtils.java
Copyright Apache License 2.0
Author : harmony-dev
public clreplaced TestUtils {

    private static Pair<List<Deposit>, List<KeyPair>> cachedDeposits = Pair.with(new ArrayList<>(), new ArrayList<>());

    public synchronized static Pair<List<Deposit>, List<KeyPair>> getAnyDeposits(Random rnd, BeaconChainSpec spec, int count) {
        if (count > cachedDeposits.getValue0().size()) {
            Pair<List<Deposit>, List<KeyPair>> newDeposits = generateRandomDeposits(rnd, spec, count - cachedDeposits.getValue0().size());
            cachedDeposits.getValue0().addAll(newDeposits.getValue0());
            cachedDeposits.getValue1().addAll(newDeposits.getValue1());
        }
        return Pair.with(cachedDeposits.getValue0().subList(0, count), cachedDeposits.getValue1().subList(0, count));
    }

    private synchronized static Pair<List<Deposit>, List<KeyPair>> generateRandomDeposits(Random rnd, BeaconChainSpec spec, int count) {
        List<Deposit> deposits = new ArrayList<>();
        List<KeyPair> validatorsKeys = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            KeyPair keyPair = KeyPair.create(PrivateKey.create(Bytes32.random(rnd)));
            Hash32 withdrawalCredentials = Hash32.random(rnd);
            DepositData depositDataWithoutSignature = new DepositData(BLSPubkey.wrap(Bytes48.leftPad(keyPair.getPublic().getEncodedBytes())), withdrawalCredentials, spec.getConstants().getMaxEffectiveBalance(), BLSSignature.wrap(Bytes96.ZERO));
            Hash32 msgHash = spec.signing_root(depositDataWithoutSignature);
            UInt64 domain = spec.compute_domain(DEPOSIT, Bytes4.ZERO);
            Signature signature = BLS381.sign(MessageParameters.create(msgHash, domain), keyPair);
            validatorsKeys.add(keyPair);
            Deposit deposit = Deposit.create(Collections.nCopies(spec.getConstants().getDepositContractTreeDepthPlusOne().getIntValue(), Hash32.random(rnd)), new DepositData(BLSPubkey.wrap(Bytes48.leftPad(keyPair.getPublic().getEncodedBytes())), withdrawalCredentials, spec.getConstants().getMaxEffectiveBalance(), BLSSignature.wrap(signature.getEncoded())));
            deposits.add(deposit);
        }
        return Pair.with(deposits, validatorsKeys);
    }

    public static List<Deposit> generateRandomDepositsWithoutSig(Random rnd, BeaconChainSpec spec, int count) {
        List<Deposit> deposits = new ArrayList<>();
        UInt64 counter = UInt64.ZERO;
        for (int i = 0; i < count; i++) {
            Hash32 withdrawalCredentials = Hash32.random(rnd);
            BLSPubkey pubkey = BLSPubkey.wrap(Bytes48.leftPad(counter.toBytesBigEndian()));
            Deposit deposit = Deposit.create(Collections.singletonList(Hash32.random(rnd)), new DepositData(pubkey, withdrawalCredentials, spec.getConstants().getMaxEffectiveBalance(), BLSSignature.ZERO));
            deposits.add(deposit);
            counter = counter.increment();
        }
        return deposits;
    }
}

18 View Complete Implementation : OrderLocalStep.java
Copyright Apache License 2.0
Author : apache
@Override
public OrderLocalStep<S, C> clone() {
    final OrderLocalStep<S, C> clone = (OrderLocalStep<S, C>) super.clone();
    clone.comparators = new ArrayList<>();
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> comparator : this.comparators) {
        clone.comparators.add(new Pair<>(comparator.getValue0().clone(), comparator.getValue1()));
    }
    clone.chainedComparator = null;
    return clone;
}

18 View Complete Implementation : ChainedComparator.java
Copyright Apache License 2.0
Author : apache
@Override
public int compare(final S objectA, final S objectB) {
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        final int comparison = this.traversers ? pair.getValue1().compare(TraversalUtil.apply((Traverser.Admin<S>) objectA, pair.getValue0()), TraversalUtil.apply((Traverser.Admin<S>) objectB, pair.getValue0())) : pair.getValue1().compare(TraversalUtil.apply(objectA, pair.getValue0()), TraversalUtil.apply(objectB, pair.getValue0()));
        if (comparison != 0)
            return comparison;
    }
    return 0;
}

18 View Complete Implementation : PropertyServiceImpl.java
Copyright Apache License 2.0
Author : igloo-project
@Override
public <T> void set(final MutablePropertyId<T> propertyId, final T value) throws ServiceException, SecurityServiceException {
    Preconditions.checkNotNull(propertyId);
    Pair<Converter<String, T>, Supplier2<T>> information = getRegistrationInformation(propertyId);
    mutablePropertyDao.setInTransaction(propertyId.getKey(), information.getValue0().reverse().convert(value));
}

18 View Complete Implementation : Neo4jPersistUtil.java
Copyright Apache License 2.0
Author : apache
public static List<Pair<String, Map<String, Object>>> vertexStatements(Activity activity) {
    List<Pair<String, Map<String, Object>>> statements = new ArrayList<>();
    ;
    ActivityObject actor = activity.getActor();
    ActivityObject object = activity.getObject();
    ActivityObject target = activity.getTarget();
    if (actor != null && StringUtils.isNotBlank(actor.getId())) {
        Pair<String, Map<String, Object>> actorStatement = vertexStatement(actor);
        statements.add(actorStatement);
    }
    if (object != null && StringUtils.isNotBlank(object.getId())) {
        Pair<String, Map<String, Object>> objectStatement = vertexStatement(object);
        statements.add(objectStatement);
    }
    if (target != null && StringUtils.isNotBlank(target.getId())) {
        Pair<String, Map<String, Object>> targetStatement = vertexStatement(target);
        statements.add(targetStatement);
    }
    return statements;
}

18 View Complete Implementation : PropertyServiceImpl.java
Copyright Apache License 2.0
Author : igloo-project
@Override
public <T> T get(final PropertyId<T> propertyId) {
    Preconditions.checkNotNull(propertyId);
    Pair<Converter<String, T>, Supplier2<T>> information = getRegistrationInformation(propertyId);
    T value = information.getValue0().convert(getreplacedtringUnsafe(propertyId));
    if (value == null) {
        T defaultValue = information.getValue1().get();
        if (defaultValue != null) {
            value = defaultValue;
            LOGGER.debug(String.format("Property '%1s' has no value, fallback on default value.", propertyId));
        } else {
            LOGGER.info(String.format("Property '%1s' has no value and default value is undefined.", propertyId));
        }
    }
    return value;
}

18 View Complete Implementation : TestCypherQueryGraphHelper.java
Copyright Apache License 2.0
Author : apache
@Test
public void getVertexRequestIdTest() throws Exception {
    Pair<String, Map<String, Object>> queryAndParams = helper.getVertexRequest("id");
    replacedert (queryAndParams != null);
    replacedert (queryAndParams.getValue0() != null);
}

18 View Complete Implementation : AbstractMapCopyModel.java
Copyright Apache License 2.0
Author : igloo-project
private void updateModels() {
    // Save the previous models for re-use based on the key model's current content
    Map<K, Pair<MK, MV>> oldModels = Maps.newHashMap();
    for (Map.Entry<MK, MV> entry : modelMap.entrySet()) {
        K key = entry.getKey().getObject();
        Object previousModelsForThisKey = oldModels.put(key, Pair.with(entry.getKey(), entry.getValue()));
        if (previousModelsForThisKey != null) {
            LOGGER.warn("Detected multiple models for the key {} in {}. One key/value pair might have been lost while" + " updating models." + " You probably get this warning because you called setObject() on a key model, which is" + " not recommended.", key, modelMap);
        }
    }
    // Build the model map based on the current object
    modelMap.clear();
    Map<K, V> currentObject = getObject();
    for (Entry<K, V> item : currentObject.entrySet()) {
        Pair<MK, MV> existingPair = oldModels.get(item.getKey());
        MK keyModel;
        MV valueModel;
        if (existingPair != null) {
            // Re-use existing models
            keyModel = existingPair.getValue0();
            valueModel = existingPair.getValue1();
            V oldValue = valueModel.getObject();
            V newValue = item.getValue();
            if (!Objects.equals(oldValue, newValue)) {
                valueModel.setObject(newValue);
            }
        } else {
            // Otherwise, create new models
            keyModel = createKeyModel(item.getKey());
            valueModel = createValueModel(item.getValue());
        }
        modelMap.put(keyModel, valueModel);
    }
}

18 View Complete Implementation : InMemoryRequestRuleStore.java
Copyright MIT License
Author : lobobrowser
public clreplaced InMemoryRequestRuleStore implements RequestRuleStore {

    private final Map<String, Map<String, PermissionSystem.Permission[]>> store = new HashMap<>();

    private static final PermissionSystem.Permission[] defaultPermissions = new PermissionSystem.Permission[RequestKind.numKinds() + 1];

    static {
        for (int i = 0; i < defaultPermissions.length; i++) {
            defaultPermissions[i] = PermissionSystem.Permission.Undecided;
        }
    }

    private static final Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> defaultPermissionPair = Pair.with(PermissionSystem.Permission.Undecided, defaultPermissions);

    static private InMemoryRequestRuleStore instance = new InMemoryRequestRuleStore();

    public static InMemoryRequestRuleStore getInstance() {
        instance.dump();
        return instance;
    }

    public InMemoryRequestRuleStore() {
        HelperPrivate.initStore(this);
    }

    public synchronized Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> getPermissions(final String frameHostPattern, final String requestHost) {
        final Map<String, PermissionSystem.Permission[]> reqHostMap = store.get(frameHostPattern);
        if (reqHostMap != null) {
            final PermissionSystem.Permission[] permissions = reqHostMap.get(requestHost);
            if (permissions != null) {
                return Pair.with(permissions[0], Arrays.copyOfRange(permissions, 1, permissions.length));
            } else {
                return defaultPermissionPair;
            }
        } else {
            return defaultPermissionPair;
        }
    }

    public synchronized void storePermissions(final String frameHostPattern, final String requestHost, final Optional<RequestKind> kindOpt, final PermissionSystem.Permission permission) {
        final int index = kindOpt.map(k -> k.ordinal() + 1).orElse(0);
        final Map<String, PermissionSystem.Permission[]> reqHostMap = store.get(frameHostPattern);
        if (reqHostMap != null) {
            final PermissionSystem.Permission[] permissions = reqHostMap.get(requestHost);
            if (permissions != null) {
                permissions[index] = permission;
            } else {
                addPermission(requestHost, index, permission, reqHostMap);
            }
        } else {
            final Map<String, PermissionSystem.Permission[]> newReqHostMap = new HashMap<>();
            addPermission(requestHost, index, permission, newReqHostMap);
            store.put(frameHostPattern, newReqHostMap);
        }
    }

    private static void addPermission(final String requestHost, final int index, final PermissionSystem.Permission permission, final Map<String, PermissionSystem.Permission[]> reqHostMap) {
        final PermissionSystem.Permission[] newPermissions = Arrays.copyOf(defaultPermissions, defaultPermissions.length);
        newPermissions[index] = permission;
        reqHostMap.put(requestHost, newPermissions);
    }

    private void dump() {
        System.out.println("Store: ");
        store.forEach((key, value) -> {
            System.out.println("{" + key + ": ");
            value.forEach((key2, value2) -> {
                System.out.println("  " + key2 + ": " + Arrays.toString(value2));
            });
            System.out.println("}");
        });
    }
}

18 View Complete Implementation : BuilderMapperLinkDescriptorFactory.java
Copyright Apache License 2.0
Author : igloo-project
public final clreplaced BuilderMapperLinkDescriptorFactory<TTarget, TLinkDescriptor> implements IBuilderMapperLinkDescriptorFactory<TLinkDescriptor> {

    private static final long serialVersionUID = 4728523709380372544L;

    private final IBuilderLinkDescriptorFactory<TTarget, TLinkDescriptor> linkDescriptorFactory;

    private final Pair<? extends IDetachableFactory<? extends Tuple, ? extends IModel<? extends TTarget>>, ? extends List<Integer>> targetFactory;

    private final Map<LinkParameterMappingEntryBuilder<?>, List<Integer>> mappingEntryBuilders;

    private final Map<ILinkParameterValidatorFactory<?>, List<Integer>> validatorFactories;

    public BuilderMapperLinkDescriptorFactory(IBuilderLinkDescriptorFactory<TTarget, TLinkDescriptor> linkDescriptorFactory, Pair<? extends IDetachableFactory<? extends Tuple, ? extends IModel<? extends TTarget>>, ? extends List<Integer>> targetFactory, Map<LinkParameterMappingEntryBuilder<?>, List<Integer>> mappingEntryBuilders, Map<ILinkParameterValidatorFactory<?>, List<Integer>> validatorFactories) {
        super();
        this.linkDescriptorFactory = linkDescriptorFactory;
        this.targetFactory = targetFactory;
        this.mappingEntryBuilders = mappingEntryBuilders;
        this.validatorFactories = validatorFactories;
    }

    private static Tuple extractParameters(Tuple parameters, List<Integer> indices) {
        int size = indices.size();
        switch(size) {
            case 0:
                return null;
            case 1:
                return Unit.with(parameters.getValue(indices.get(0)));
            case 2:
                return Pair.with(parameters.getValue(indices.get(0)), parameters.getValue(indices.get(1)));
            case 3:
                return Triplet.with(parameters.getValue(indices.get(0)), parameters.getValue(indices.get(1)), parameters.getValue(indices.get(2)));
            case 4:
                return Quartet.with(parameters.getValue(indices.get(0)), parameters.getValue(indices.get(1)), parameters.getValue(indices.get(2)), parameters.getValue(indices.get(3)));
            default:
                throw new IllegalStateException("Only Unit, Pair, Triplet and Quartet parameters are supported for ILinkParameterMappingEntryFactory");
        }
    }

    @Override
    public final TLinkDescriptor create(Tuple parameters) {
        Collection<ILinkParameterMappingEntry> addedParameterMappingEntries = Lists.newArrayList();
        Collection<ILinkParameterValidator> addedValidators = Lists.newArrayList();
        IModel<? extends TTarget> target = doCreate((IDetachableFactory<? extends Tuple, ? extends IModel<? extends TTarget>>) targetFactory.getValue0(), parameters, targetFactory.getValue1());
        for (Map.Entry<LinkParameterMappingEntryBuilder<?>, List<Integer>> entry : mappingEntryBuilders.entrySet()) {
            List<Integer> indices = entry.getValue();
            Pair<ILinkParameterMappingEntry, Collection<ILinkParameterValidator>> result = doCreate(entry.getKey(), parameters, indices);
            addedParameterMappingEntries.add(result.getValue0());
            addedValidators.addAll(result.getValue1());
        }
        for (Map.Entry<ILinkParameterValidatorFactory<?>, List<Integer>> entry : validatorFactories.entrySet()) {
            List<Integer> indices = entry.getValue();
            ILinkParameterValidator result = doCreate(entry.getKey(), parameters, indices);
            addedValidators.add(result);
        }
        return linkDescriptorFactory.create(target, addedParameterMappingEntries, addedValidators);
    }

    private static <T extends Tuple, R> R doCreate(IDetachableFactory<T, R> factory, Tuple parameters, List<Integer> indices) {
        @SuppressWarnings("unchecked")
        IDetachableFactory<Tuple, R> factoryFromTuple = ((IDetachableFactory<Tuple, R>) factory);
        Tuple parametersAsTuple = extractParameters(parameters, indices);
        return factoryFromTuple.create(parametersAsTuple);
    }

    @Override
    public void detach() {
        targetFactory.getValue0().detach();
        linkDescriptorFactory.detach();
        Detachables.detach(mappingEntryBuilders.keySet());
        Detachables.detach(validatorFactories.keySet());
    }
}

18 View Complete Implementation : AddTraverseMethod.java
Copyright GNU General Public License v2.0
Author : plum-umd
private void generateTraverseMethod() {
    LocalVariablesSorter mv = new LocalVariablesSorter(TRAVERSE_METHOD_ACC_FLAGS, TRAVERSE_METHOD_DESC, this.visitMethod(this.getTraverseMethodAccess(), this.getTraverseMethodName(), TRAVERSE_METHOD_DESC, null, null));
    mv.visitCode();
    if (isAllowed(this.thisClreplaced.getFqn())) {
        this.generateTraverseMethodPreamble(mv);
        if (!this.fields.isEmpty()) {
            for (Pair<String, String> field : this.fields) {
                this.generateFieldAccess(mv, field);
            }
        }
    }
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

18 View Complete Implementation : OrderGlobalStep.java
Copyright Apache License 2.0
Author : apache
private final ProjectedTraverser<S, C> createProjectedTraverser(final Traverser.Admin<S> traverser) {
    final List<C> projections = new ArrayList<>(this.comparators.size());
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        projections.add(TraversalUtil.apply(traverser, pair.getValue0()));
    }
    return new ProjectedTraverser<>(traverser, projections);
}

18 View Complete Implementation : ArtifactEntryServiceImpl.java
Copyright Apache License 2.0
Author : strongbox
@Override
public Long countCoordinates(Collection<Pair<String, String>> storageRepositoryPairList, Map<String, String> coordinates, boolean strict) {
    coordinates = prepareParameterMap(coordinates, strict);
    String sQuery = buildCoordinatesQuery(storageRepositoryPairList, coordinates.keySet(), Collections.emptySet(), 0, 0, null, strict);
    sQuery = sQuery.replace("*", "count(distinct(artifactCoordinates))");
    OSQLSynchQuery<ArtifactEntry> oQuery = new OSQLSynchQuery<>(sQuery);
    Map<String, Object> parameterMap = new HashMap<>(coordinates);
    Pair<String, String>[] p = storageRepositoryPairList.toArray(new Pair[storageRepositoryPairList.size()]);
    IntStream.range(0, storageRepositoryPairList.size()).forEach(idx -> {
        String storageId = p[idx].getValue0();
        String repositoryId = p[idx].getValue1();
        if (storageId != null && !storageId.trim().isEmpty()) {
            parameterMap.put(String.format("storageId%s", idx), p[idx].getValue0());
        }
        if (repositoryId != null && !repositoryId.trim().isEmpty()) {
            parameterMap.put(String.format("repositoryId%s", idx), p[idx].getValue1());
        }
    });
    List<ODoreplacedent> result = getDelegate().command(oQuery).execute(parameterMap);
    return (Long) result.iterator().next().field("count");
}

18 View Complete Implementation : ArtifactEntryServiceImpl.java
Copyright Apache License 2.0
Author : strongbox
@Override
public Long countArtifacts(Collection<Pair<String, String>> storageRepositoryPairList, Map<String, String> coordinates, boolean strict) {
    coordinates = prepareParameterMap(coordinates, strict);
    String sQuery = buildCoordinatesQuery(storageRepositoryPairList, coordinates.keySet(), Collections.emptySet(), 0, 0, null, strict);
    sQuery = sQuery.replace("*", "count(*)");
    OSQLSynchQuery<ArtifactEntry> oQuery = new OSQLSynchQuery<>(sQuery);
    Map<String, Object> parameterMap = new HashMap<>(coordinates);
    Pair<String, String>[] p = storageRepositoryPairList.toArray(new Pair[storageRepositoryPairList.size()]);
    IntStream.range(0, storageRepositoryPairList.size()).forEach(idx -> {
        String storageId = p[idx].getValue0();
        String repositoryId = p[idx].getValue1();
        if (storageId != null && !storageId.trim().isEmpty()) {
            parameterMap.put(String.format("storageId%s", idx), p[idx].getValue0());
        }
        if (repositoryId != null && !repositoryId.trim().isEmpty()) {
            parameterMap.put(String.format("repositoryId%s", idx), p[idx].getValue1());
        }
    });
    List<ODoreplacedent> result = getDelegate().command(oQuery).execute(parameterMap);
    return (Long) result.iterator().next().field("count");
}

18 View Complete Implementation : TestCypherQueryGraphHelper.java
Copyright Apache License 2.0
Author : apache
@Test
public void getVertexRequestLongTest() throws Exception {
    Pair<String, Map<String, Object>> queryAndParams = helper.getVertexRequest(new Long(1));
    replacedert (queryAndParams != null);
    replacedert (queryAndParams.getValue0() != null);
}

18 View Complete Implementation : OrderGlobalStep.java
Copyright Apache License 2.0
Author : apache
@Override
public OrderGlobalStep<S, C> clone() {
    final OrderGlobalStep<S, C> clone = (OrderGlobalStep<S, C>) super.clone();
    clone.comparators = new ArrayList<>();
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> comparator : this.comparators) {
        clone.comparators.add(new Pair<>(comparator.getValue0().clone(), comparator.getValue1()));
    }
    return clone;
}

18 View Complete Implementation : DBRequestRuleStore.java
Copyright MIT License
Author : lobobrowser
public clreplaced DBRequestRuleStore implements RequestRuleStore {

    private final DSLContext userDB;

    private static final PermissionSystem.Permission[] defaultPermissions = new PermissionSystem.Permission[RequestKind.numKinds()];

    static {
        for (int i = 0; i < defaultPermissions.length; i++) {
            defaultPermissions[i] = PermissionSystem.Permission.Undecided;
        }
    }

    private static final Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> defaultPermissionPair = Pair.with(PermissionSystem.Permission.Undecided, defaultPermissions);

    static private DBRequestRuleStore instance = new DBRequestRuleStore();

    public static DBRequestRuleStore getInstance() {
        return instance;
    }

    public DBRequestRuleStore() {
        final StorageManager storageManager = StorageManager.getInstance();
        userDB = storageManager.getDB();
        if (!userDB.fetchOne(Globals.GLOBALS).getPermissionsinitialized()) {
            HelperPrivate.initStore(this);
            userDB.fetchOne(Globals.GLOBALS).setPermissionsinitialized(true);
        }
    }

    private static Condition matchHostsCondition(final String frameHost, final String requestHost) {
        return Permissions.PERMISSIONS.FRAMEHOST.equal(frameHost).and(Permissions.PERMISSIONS.REQUESTHOST.equal(requestHost));
    }

    public Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> getPermissions(final String frameHostPattern, final String requestHost) {
        final Result<PermissionsRecord> permissionRecords = AccessController.doPrivileged((PrivilegedAction<Result<PermissionsRecord>>) () -> {
            return userDB.fetch(Permissions.PERMISSIONS, matchHostsCondition(frameHostPattern, requestHost));
        });
        if (permissionRecords.isEmpty()) {
            return defaultPermissionPair;
        } else {
            final PermissionsRecord existingRecord = permissionRecords.get(0);
            final Integer existingPermissions = existingRecord.getPermissions();
            final Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> permissions = decodeBitMask(existingPermissions);
            return permissions;
        }
    }

    private static Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> decodeBitMask(final Integer existingPermissions) {
        final PermissionSystem.Permission[] resultPermissions = new PermissionSystem.Permission[RequestKind.numKinds()];
        for (int i = 0; i < resultPermissions.length; i++) {
            resultPermissions[i] = decodeBits(existingPermissions, i + 1);
        }
        final Pair<PermissionSystem.Permission, PermissionSystem.Permission[]> resultPair = Pair.with(decodeBits(existingPermissions, 0), resultPermissions);
        return resultPair;
    }

    private static final int BITS_PER_KIND = 2;

    private static PermissionSystem.Permission decodeBits(final Integer existingPermissions, final int i) {
        final int permissionBits = (existingPermissions >> (i * BITS_PER_KIND)) & 0x3;
        if (permissionBits < 2) {
            return PermissionSystem.Permission.Undecided;
        } else {
            return permissionBits == 0x3 ? PermissionSystem.Permission.Allow : PermissionSystem.Permission.Deny;
        }
    }

    public void storePermissions(final String frameHost, final String requestHost, final Optional<RequestKind> kindOpt, final PermissionSystem.Permission permission) {
        final Result<PermissionsRecord> permissionRecords = AccessController.doPrivileged((PrivilegedAction<Result<PermissionsRecord>>) () -> {
            return userDB.fetch(Permissions.PERMISSIONS, matchHostsCondition(frameHost, requestHost));
        });
        final Integer permissionMask = makeBitSetMask(kindOpt, permission);
        if (permissionRecords.isEmpty()) {
            final PermissionsRecord newPermissionRecord = new PermissionsRecord(frameHost, requestHost, permissionMask);
            newPermissionRecord.attach(userDB.configuration());
            newPermissionRecord.store();
        } else {
            final PermissionsRecord existingRecord = permissionRecords.get(0);
            final Integer existingPermissions = existingRecord.getPermissions();
            final int newPermissions = (existingPermissions & makeBitBlockMask(kindOpt)) | permissionMask;
            existingRecord.setPermissions(newPermissions);
            existingRecord.store();
        }
    }

    private static Integer makeBitSetMask(final Optional<RequestKind> kindOpt, final PermissionSystem.Permission permission) {
        if (permission.isDecided()) {
            final Integer bitPos = kindOpt.map(k -> k.ordinal() + 1).orElse(0) * BITS_PER_KIND;
            final int bitset = permission == PermissionSystem.Permission.Allow ? 0x3 : 0x2;
            return bitset << bitPos;
        } else {
            return 0;
        }
    }

    private static Integer makeBitBlockMask(final Optional<RequestKind> kindOpt) {
        final Integer bitPos = kindOpt.map(k -> k.ordinal() + 1).orElse(0) * BITS_PER_KIND;
        return ~(0x3 << bitPos);
    }
}

18 View Complete Implementation : ReplacedStepTree.java
Copyright MIT License
Author : pietermartin
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean orderByIsOrder() {
    for (ReplacedStep<?, ?> replacedStep : linearPathToLeafNode()) {
        for (Pair<Traversal.Admin<?, ?>, Comparator<?>> objects : replacedStep.getSqlgComparatorHolder().getComparators()) {
            if (!(objects.getValue1() instanceof Order && objects.getValue1() != Order.shuffle)) {
                return false;
            }
        }
    }
    return true;
}

18 View Complete Implementation : OrderGlobalStep.java
Copyright Apache License 2.0
Author : apache
private final MultiComparator<C> createMultiComparator() {
    final List<Comparator<C>> list = new ArrayList<>(this.comparators.size());
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        list.add(pair.getValue1());
    }
    return new MultiComparator<>(list);
}

17 View Complete Implementation : CypherQueryGraphHelper.java
Copyright Apache License 2.0
Author : apache
/**
 * getVertexRequest.
 * @param vertexId numericId
 * @return pair (streamsId, parameterMap)
 */
public Pair<String, Map<String, Object>> getVertexRequest(Long vertexId) {
    ST getVertex = new ST(getVertexLongIdStatementTemplate);
    getVertex.add("id", vertexId);
    Pair<String, Map<String, Object>> queryPlusParameters = new Pair(getVertex.render(), null);
    LOGGER.debug("getVertexRequest", queryPlusParameters.toString());
    return queryPlusParameters;
}

17 View Complete Implementation : Neo4jPersistUtil.java
Copyright Apache License 2.0
Author : apache
public static Pair<String, Map<String, Object>> vertexStatement(ActivityObject activityObject) {
    Pair<String, Map<String, Object>> mergeVertexRequest = helper.mergeVertexRequest(activityObject);
    Map<String, Object> props = new HashMap<>();
    props.put("props", mergeVertexRequest.getValue1());
    mergeVertexRequest = mergeVertexRequest.setAt1(props);
    return mergeVertexRequest;
}

17 View Complete Implementation : BranchStep.java
Copyright Apache License 2.0
Author : apache
private List<Traversal.Admin<S, E>> pickBranches(final Object choice) {
    final List<Traversal.Admin<S, E>> branches = new ArrayList<>();
    if (choice instanceof Pick) {
        if (this.traversalPickOptions.containsKey(choice)) {
            branches.addAll(this.traversalPickOptions.get(choice));
        }
    }
    for (final Pair<Traversal.Admin, Traversal.Admin<S, E>> p : this.traversalOptions) {
        if (TraversalUtil.test(choice, p.getValue0())) {
            branches.add(p.getValue1());
        }
    }
    return branches.isEmpty() ? this.traversalPickOptions.get(Pick.none) : branches;
}

17 View Complete Implementation : ChainedComparator.java
Copyright Apache License 2.0
Author : apache
@Override
public ChainedComparator<S, C> clone() {
    try {
        final ChainedComparator<S, C> clone = (ChainedComparator<S, C>) super.clone();
        clone.comparators = new ArrayList<>();
        for (final Pair<Traversal.Admin<S, C>, Comparator<C>> comparator : this.comparators) {
            clone.comparators.add(new Pair<>(comparator.getValue0().clone(), comparator.getValue1()));
        }
        return clone;
    } catch (final CloneNotSupportedException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

17 View Complete Implementation : ResponseCacheImpl.java
Copyright Apache License 2.0
Author : chanjarster
@Override
public ResponseDto getAndRemove(String requestId) {
    Pair<ResponseDto, Long> pair = RESPONSE_MAP.remove(requestId);
    return pair == null ? null : pair.getValue0();
}

17 View Complete Implementation : AuthHeaderMessagePacket.java
Copyright Apache License 2.0
Author : harmony-dev
public void decodeEphemeralPubKey() {
    if (decodedEphemeralPubKeyPt != null) {
        return;
    }
    EphemeralPubKeyDecoded blank = new EphemeralPubKeyDecoded();
    blank.tag = Bytes32.wrap(getBytes().slice(0, 32), 0);
    Pair<RlpList, BytesValue> decodeRes = RlpUtil.decodeFirstList(getBytes().slice(32));
    blank.messageEncrypted = decodeRes.getValue1();
    RlpList authHeaderParts = (RlpList) decodeRes.getValue0().getValues().get(0);
    // [auth-tag, id-nonce, auth-scheme-name, ephemeral-pubkey, auth-response]
    blank.authTag = BytesValue.wrap(((RlpString) authHeaderParts.getValues().get(0)).getBytes());
    blank.idNonce = BytesValue.wrap(((RlpString) authHeaderParts.getValues().get(1)).getBytes());
    replacedert AUTH_SCHEME_NAME.equals(new String(((RlpString) authHeaderParts.getValues().get(2)).getBytes()));
    blank.ephemeralPubkey = BytesValue.wrap(((RlpString) authHeaderParts.getValues().get(3)).getBytes());
    blank.authResponse = BytesValue.wrap(((RlpString) authHeaderParts.getValues().get(4)).getBytes());
    this.decodedEphemeralPubKeyPt = blank;
}

17 View Complete Implementation : SSZReader.java
Copyright Apache License 2.0
Author : harmony-dev
public long readULong(int bitLength) {
    Pair<Bytes, Integer> params = checkAndConsumeNumber(bitLength, Long.BYTES, "decoded number is too large for an long");
    return params.getValue0().slice(0, params.getValue0().size() - params.getValue1()).toLong(LITTLE_ENDIAN);
}

17 View Complete Implementation : SSZReader.java
Copyright Apache License 2.0
Author : harmony-dev
public int readUInt(int bitLength) {
    Pair<Bytes, Integer> params = checkAndConsumeNumber(bitLength, Integer.BYTES, "decoded integer is too large for an int");
    return params.getValue0().slice(0, params.getValue0().size() - params.getValue1()).toInt(LITTLE_ENDIAN);
}

17 View Complete Implementation : JoinerModel.java
Copyright Apache License 2.0
Author : igloo-project
@Override
protected void onDetach() {
    super.onDetach();
    for (Pair<IModel<?>, Condition> conditionnalModel : conditionnalModels) {
        if (conditionnalModel != null && conditionnalModel.getValue0() != null) {
            conditionnalModel.getValue0().detach();
            conditionnalModel.getValue1().detach();
        }
    }
}

17 View Complete Implementation : RedisDemo7.java
Copyright Apache License 2.0
Author : jxnu-liguobin
public void testIndexAndTargetAds(Jedis conn) {
    System.out.println("\n----- testIndexAndTargetAds -----");
    indexAd(conn, "1", new String[] { "USA", "CA" }, CONTENT, Ecpm.CPC, .25);
    indexAd(conn, "2", new String[] { "USA", "VA" }, CONTENT + " wooooo", Ecpm.CPC, .125);
    String[] usa = new String[] { "USA" };
    for (int i = 0; i < 100; i++) {
        targetAds(conn, usa, CONTENT);
    }
    Pair<Long, String> result = targetAds(conn, usa, CONTENT);
    long targetId = result.getValue0();
    String adId = result.getValue1();
    replacedert "1".equals(result.getValue1());
    result = targetAds(conn, new String[] { "VA" }, "wooooo");
    replacedert "2".equals(result.getValue1());
    Iterator<Tuple> range = conn.zrangeWithScores("idx:ad:value:", 0, -1).iterator();
    replacedert new Tuple("2", 0.125).equals(range.next());
    replacedert new Tuple("1", 0.25).equals(range.next());
    range = conn.zrangeWithScores("ad:base_value:", 0, -1).iterator();
    replacedert new Tuple("2", 0.125).equals(range.next());
    replacedert new Tuple("1", 0.25).equals(range.next());
    recordClick(conn, targetId, adId, false);
    range = conn.zrangeWithScores("idx:ad:value:", 0, -1).iterator();
    replacedert new Tuple("2", 0.125).equals(range.next());
    replacedert new Tuple("1", 2.5).equals(range.next());
    range = conn.zrangeWithScores("ad:base_value:", 0, -1).iterator();
    replacedert new Tuple("2", 0.125).equals(range.next());
    replacedert new Tuple("1", 0.25).equals(range.next());
}

17 View Complete Implementation : RedisDemo7.java
Copyright Apache License 2.0
Author : jxnu-liguobin
@SuppressWarnings("unchecked")
public Pair<Long, String> targetAds(Jedis conn, String[] locations, String content) {
    Transaction trans = conn.multi();
    String matchedAds = matchLocation(trans, locations);
    @SuppressWarnings("deprecation")
    String baseEcpm = zintersect(trans, 30, new ZParams().weights(0, 1), matchedAds, "ad:value:");
    Pair<Set<String>, String> result = finishScoring(trans, matchedAds, baseEcpm, content);
    trans.incr("ads:served:");
    trans.zrevrange("idx:" + result.getValue1(), 0, 0);
    List<Object> response = trans.exec();
    long targetId = (Long) response.get(response.size() - 2);
    Set<String> targetedAds = (Set<String>) response.get(response.size() - 1);
    if (targetedAds.size() == 0) {
        return new Pair<Long, String>(null, null);
    }
    String adId = targetedAds.iterator().next();
    recordTargetingResult(conn, targetId, adId, result.getValue0());
    return new Pair<Long, String>(targetId, adId);
}

17 View Complete Implementation : SparseSGD.java
Copyright GNU Lesser General Public License v3.0
Author : sanity
static void sparseUpdateUnnormalizedGradientForInstance(double[] weights, Int2DoubleOpenHashMap contributionsToTheGradient, SparseClreplacedifierInstance instance) {
    // could do this with a map for truly sparse instances...but
    double postiveClreplacedProbability = probabilityOfThePositiveClreplaced(weights, instance);
    Pair<int[], double[]> sparseAttributes = instance.getSparseAttributes();
    int[] indices = sparseAttributes.getValue0();
    double[] values = sparseAttributes.getValue1();
    for (int i = 0; i < indices.length; i++) {
        int featureIndex = indices[i];
        contributionsToTheGradient.addTo(featureIndex, gradientContributionOfAFeatureValue((Double) instance.getLabel(), postiveClreplacedProbability, values[i]));
    }
}

17 View Complete Implementation : OptimizableCostFunctionImp.java
Copyright GNU Lesser General Public License v3.0
Author : sanity
static void updateUnnormalizedGradientForInstance(double[] weights, double[] contributionsToTheGradient, SparseRegressionInstance instance) {
    // could do this with a map for truly sparse instances...but
    double postiveClreplacedProbability = probabilityOfThePositiveClreplaced(weights, instance);
    Pair<int[], double[]> sparseAttributes = instance.getSparseAttributes();
    int[] indices = sparseAttributes.getValue0();
    double[] values = sparseAttributes.getValue1();
    for (int i = 0; i < indices.length; i++) {
        int featureIndex = indices[i];
        contributionsToTheGradient[featureIndex] += gradientContributionOfAFeatureValue((Double) instance.getLabel(), postiveClreplacedProbability, values[i]);
    }
}

17 View Complete Implementation : OptimizableCostFunctionImp.java
Copyright GNU Lesser General Public License v3.0
Author : sanity
static void sparseUpdateUnnormalizedGradientForInstance(double[] weights, Int2DoubleOpenHashMap contributionsToTheGradient, SparseRegressionInstance instance) {
    // could do this with a map for truly sparse instances...but
    double postiveClreplacedProbability = probabilityOfThePositiveClreplaced(weights, instance);
    Pair<int[], double[]> sparseAttributes = instance.getSparseAttributes();
    int[] indices = sparseAttributes.getValue0();
    double[] values = sparseAttributes.getValue1();
    for (int i = 0; i < indices.length; i++) {
        int featureIndex = indices[i];
        contributionsToTheGradient.addTo(featureIndex, gradientContributionOfAFeatureValue((Double) instance.getLabel(), postiveClreplacedProbability, values[i]));
    }
}

17 View Complete Implementation : OldTreeBuilder.java
Copyright GNU Lesser General Public License v3.0
Author : sanity
private Pair<? extends OldBranch, Double> createTwoClreplacedCategoricalNode(OldNode parent, final String attribute, final Iterable<T> instances) {
    double bestScore = 0;
    final Pair<OldClreplacedificationCounter, List<OldAttributeValueWithClreplacedificationCounter>> valueOutcomeCountsPairs = // returns a list of ClreplacedificationCounterList
    OldClreplacedificationCounter.getSortedListOfAttributeValuesWithClreplacedificationCounters(instances, attribute, minorityClreplacedification);
    // clreplacedification counter treating all values the same
    OldClreplacedificationCounter outCounts = new OldClreplacedificationCounter(valueOutcomeCountsPairs.getValue0());
    // the histogram of counts by clreplacedification for the in-set
    OldClreplacedificationCounter inCounts = new OldClreplacedificationCounter();
    // map of value _> clreplacedificationCounter
    final List<OldAttributeValueWithClreplacedificationCounter> valuesWithClreplacedificationCounters = valueOutcomeCountsPairs.getValue1();
    double numTrainingExamples = valueOutcomeCountsPairs.getValue0().getTotal();
    Serializable lastValOfInset = valuesWithClreplacedificationCounters.get(0).attributeValue;
    double probabilityOfBeingInInset = 0;
    int valuesInTheInset = 0;
    int attributesWithSufficientValues = labelAttributeValuesWithInsufficientData(valuesWithClreplacedificationCounters);
    if (attributesWithSufficientValues <= 1)
        // there is just 1 value available.
        return null;
    double intrinsicValueOfAttribute = getIntrinsicValueOfAttribute(valuesWithClreplacedificationCounters, numTrainingExamples);
    for (final OldAttributeValueWithClreplacedificationCounter valueWithClreplacedificationCounter : valuesWithClreplacedificationCounters) {
        final OldClreplacedificationCounter testValCounts = valueWithClreplacedificationCounter.clreplacedificationCounter;
        if (testValCounts == null || valueWithClreplacedificationCounter.attributeValue.equals(MISSING_VALUE)) {
            // Also a kludge, figure out why
            continue;
        }
        if (this.minDiscreteAttributeValueOccurances > 0) {
            if (!testValCounts.hreplacedufficientData())
                continue;
        }
        inCounts = inCounts.add(testValCounts);
        outCounts = outCounts.subtract(testValCounts);
        double numInstances = inCounts.getTotal() + outCounts.getTotal();
        if (!exemptAttributes.contains(attribute) && (inCounts.getTotal() / numInstances < minSplitFraction || outCounts.getTotal() / numInstances < minSplitFraction)) {
            continue;
        }
        if (inCounts.getTotal() < minLeafInstances || outCounts.getTotal() < minLeafInstances) {
            continue;
        }
        double thisScore = oldScorer.scoreSplit(inCounts, outCounts);
        valuesInTheInset++;
        if (penalizeCategoricalSplitsBySplitAttributeIntrinsicValue) {
            thisScore = thisScore * (1 - degreeOfGainRatioPenalty) + degreeOfGainRatioPenalty * (thisScore / intrinsicValueOfAttribute);
        }
        if (thisScore > bestScore) {
            bestScore = thisScore;
            lastValOfInset = valueWithClreplacedificationCounter.attributeValue;
            probabilityOfBeingInInset = inCounts.getTotal() / (inCounts.getTotal() + outCounts.getTotal());
        }
    }
    final Set<Serializable> inSet = Sets.newHashSet();
    final Set<Serializable> outSet = Sets.newHashSet();
    boolean insetIsBuiltNowBuildingOutset = false;
    inCounts = new OldClreplacedificationCounter();
    outCounts = new OldClreplacedificationCounter();
    for (OldAttributeValueWithClreplacedificationCounter oldAttributeValueWithClreplacedificationCounter : valuesWithClreplacedificationCounters) {
        if (!insetIsBuiltNowBuildingOutset && oldAttributeValueWithClreplacedificationCounter.clreplacedificationCounter.hreplacedufficientData()) {
            inSet.add(oldAttributeValueWithClreplacedificationCounter.attributeValue);
            inCounts.add(oldAttributeValueWithClreplacedificationCounter.clreplacedificationCounter);
            if (oldAttributeValueWithClreplacedificationCounter.attributeValue.equals(lastValOfInset)) {
                insetIsBuiltNowBuildingOutset = true;
            }
        } else {
            outCounts.add(oldAttributeValueWithClreplacedificationCounter.clreplacedificationCounter);
        // outSet.add(attributeValueWithClreplacedificationCounter.attributeValue);
        }
    }
    if (bestScore == 0)
        return null;
    else {
        Pair<OldCategoricalOldBranch, Double> bestPair = Pair.with(new OldCategoricalOldBranch(parent, attribute, inSet, probabilityOfBeingInInset), bestScore);
        return bestPair;
    }
}

17 View Complete Implementation : OldTreeBuilder.java
Copyright GNU Lesser General Public License v3.0
Author : sanity
private OldNode growTree(OldBranch parent, List<T> trainingData, final int depth) {
    Preconditions.checkArgument(!Iterables.isEmpty(trainingData), "At Depth: " + depth + ". Can't build a oldTree with no training data");
    if (depth >= maxDepth) {
        return getLeaf(parent, trainingData, depth);
    }
    Pair<? extends OldBranch, Double> bestPair = getBestNodePair(parent, trainingData);
    OldBranch bestNode = bestPair != null ? bestPair.getValue0() : null;
    double bestScore = bestPair != null ? bestPair.getValue1() : 0;
    if (bestNode == null || bestScore < minimumScore) {
        // bestNode will be null if no attribute could provide a split that had enough statistically significant variable values
        // to produce 2 children where each had at least minInstancesPerLeafSamples.
        // The best score condition naturally catches the situation where all instances have the same clreplacedification.
        return getLeaf(parent, trainingData, depth);
    }
    ArrayList<T> trueTrainingSet = Lists.newArrayList();
    ArrayList<T> falseTrainingSet = Lists.newArrayList();
    setTrueAndFalseTrainingSets(trainingData, bestNode, trueTrainingSet, falseTrainingSet);
    bestNode.trueChild = growTree(bestNode, trueTrainingSet, depth + 1);
    bestNode.falseChild = growTree(bestNode, falseTrainingSet, depth + 1);
    return bestNode;
}

17 View Complete Implementation : OldTreeBuilder.java
Copyright GNU Lesser General Public License v3.0
Author : sanity
private Pair<? extends OldBranch, Double> createNClreplacedCategoricalNode(OldNode parent, final String attribute, final Iterable<T> instances) {
    final Set<Serializable> values = getAttrinbuteValues(instances, attribute);
    if (insufficientTrainingDataGivenNumberOfAttributeValues(instances, values))
        return null;
    // the in-set
    final Set<Serializable> inValueSet = Sets.newHashSet();
    // the histogram of counts by clreplacedification for the in-set
    OldClreplacedificationCounter inSetClreplacedificationCounts = new OldClreplacedificationCounter();
    final Pair<OldClreplacedificationCounter, Map<Serializable, OldClreplacedificationCounter>> valueOutcomeCountsPair = OldClreplacedificationCounter.countAllByAttributeValues(instances, attribute);
    // clreplacedification counter treating all values the same
    OldClreplacedificationCounter outSetClreplacedificationCounts = valueOutcomeCountsPair.getValue0();
    // map of value _> clreplacedificationCounter
    final Map<Serializable, OldClreplacedificationCounter> valueOutcomeCounts = valueOutcomeCountsPair.getValue1();
    double insetScore = 0;
    while (true) {
        com.google.common.base.Optional<ScoreValuePair> bestValueAndScore = com.google.common.base.Optional.absent();
        // values should be greater than 1
        for (final Serializable thisValue : values) {
            final OldClreplacedificationCounter testValCounts = valueOutcomeCounts.get(thisValue);
            // TODO: the next 3 lines may no longer be needed. Verify.
            if (testValCounts == null || thisValue == null || thisValue.equals(MISSING_VALUE)) {
                continue;
            }
            if (this.minDiscreteAttributeValueOccurances > 0) {
                if (shouldWeIgnoreThisValue(testValCounts))
                    continue;
            }
            final OldClreplacedificationCounter testInCounts = inSetClreplacedificationCounts.add(testValCounts);
            final OldClreplacedificationCounter testOutCounts = outSetClreplacedificationCounts.subtract(testValCounts);
            double scoreWithThisValueAddedToInset = oldScorer.scoreSplit(testInCounts, testOutCounts);
            if (!bestValueAndScore.isPresent() || scoreWithThisValueAddedToInset > bestValueAndScore.get().getScore()) {
                bestValueAndScore = com.google.common.base.Optional.of(new ScoreValuePair(scoreWithThisValueAddedToInset, thisValue));
            }
        }
        if (bestValueAndScore.isPresent() && bestValueAndScore.get().getScore() > insetScore) {
            insetScore = bestValueAndScore.get().getScore();
            final Serializable bestValue = bestValueAndScore.get().getValue();
            inValueSet.add(bestValue);
            values.remove(bestValue);
            final OldClreplacedificationCounter bestValOutcomeCounts = valueOutcomeCounts.get(bestValue);
            inSetClreplacedificationCounts = inSetClreplacedificationCounts.add(bestValOutcomeCounts);
            outSetClreplacedificationCounts = outSetClreplacedificationCounts.subtract(bestValOutcomeCounts);
        } else {
            break;
        }
    }
    if (inSetClreplacedificationCounts.getTotal() < minLeafInstances || outSetClreplacedificationCounts.getTotal() < minLeafInstances) {
        return null;
    }
    // because inSetClreplacedificationCounts is only mutated to better insets during the for loop...it corresponds to the actual inset here.
    double probabilityOfBeingInInset = inSetClreplacedificationCounts.getTotal() / (inSetClreplacedificationCounts.getTotal() + outSetClreplacedificationCounts.getTotal());
    return Pair.with(new OldCategoricalOldBranch(parent, attribute, inValueSet, probabilityOfBeingInInset), insetScore);
}

17 View Complete Implementation : TuplesTest.java
Copyright Mozilla Public License 2.0
Author : seedstack
@Test
public void testCreateTupleFromVarArgs() {
    Pair<Integer, String> pair = Tuples.create(10, "foo");
    replacedertions.replacedertThat((Iterable<?>) pair).isEqualTo(new Pair<>(10, "foo"));
    Tuple tuple = Tuples.create(String.clreplaced, Long.clreplaced);
    replacedertions.replacedertThat((Iterable<?>) tuple).isInstanceOf(Pair.clreplaced);
    replacedertions.replacedertThat(tuple.containsAll(String.clreplaced, Long.clreplaced)).isTrue();
    replacedertions.replacedertThat(tuple.getSize()).isEqualTo(2);
    tuple = Tuples.create(String.clreplaced, Long.clreplaced, Float.clreplaced);
    replacedertions.replacedertThat((Iterable<?>) tuple).isInstanceOf(Triplet.clreplaced);
}

17 View Complete Implementation : ArtifactEntryServiceImpl.java
Copyright Apache License 2.0
Author : strongbox
protected String buildCoordinatesQuery(Collection<Pair<String, String>> storageRepositoryPairList, Set<String> parameterNameSet, Set<String> tagNameSet, int skip, int limit, String orderBy, boolean strict) {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT * FROM ").append(getEnreplacedyClreplaced().getSimpleName());
    Pair<String, String>[] storageRepositoryPairArray = storageRepositoryPairList.toArray(new Pair[storageRepositoryPairList.size()]);
    // COORDINATES
    StringBuffer c1 = new StringBuffer();
    parameterNameSet.stream().forEach(e -> c1.append(c1.length() > 0 ? " AND " : "").append("artifactCoordinates.coordinates.").append(e).append(".toLowerCase()").append(strict ? " = " : " like ").append(String.format(":%s", e)));
    sb.append(" WHERE ").append(c1.length() > 0 ? c1.append(" AND ").toString() : " true = true AND ");
    // REPOSITORIES
    StringBuffer c2 = new StringBuffer();
    IntStream.range(0, storageRepositoryPairList.size()).forEach(idx -> c2.append(idx > 0 ? " OR " : "").append(calculateStorageAndRepositoryCondition(storageRepositoryPairArray[idx], idx)));
    sb.append(c2.length() > 0 ? c2.toString() : "true");
    // TAGS
    tagNameSet.stream().forEach(t -> sb.append(String.format(" AND tagSet contains (name = :%s)", t)));
    // ORDER
    if ("uuid".equals(orderBy)) {
        sb.append(" ORDER BY artifactCoordinates.uuid");
    } else if (orderBy != null && !orderBy.trim().isEmpty()) {
        sb.append(String.format(" ORDER BY artifactCoordinates.coordinates.%s", orderBy));
    }
    // PAGE
    if (skip > 0) {
        sb.append(String.format(" SKIP %s", skip));
    }
    if (limit > 0) {
        sb.append(String.format(" LIMIT %s", limit));
    }
    // now query should looks like
    // SELECT * FROM Foo WHERE blah = :blah AND moreBlah = :moreBlah
    logger.debug("Executing SQL query> {}", sb);
    return sb.toString();
}

17 View Complete Implementation : MongoDbSafeKey.java
Copyright Apache License 2.0
Author : apache
/**
 * Encodes a string to be safe for use as a MongoDB field name.
 * @param key the unencoded key.
 * @return the encoded key.
 */
public static String encodeKey(final String key) {
    String encodedKey = key;
    for (final Pair<String, String> pair : ESCAPE_CHARACTERS) {
        final String unescapedCharacter = pair.getValue0();
        final String escapedCharacter = pair.getValue1();
        encodedKey = encodedKey.replace(unescapedCharacter, escapedCharacter);
    }
    return encodedKey;
}

17 View Complete Implementation : MongoDbSafeKey.java
Copyright Apache License 2.0
Author : apache
/**
 * Decodes a MongoDB safe field name to an unencoded string.
 * @param key the encoded key.
 * @return the unencoded key.
 */
public static String decodeKey(final String key) {
    String decodedKey = key;
    for (final Pair<String, String> pair : UNESCAPE_CHARACTERS) {
        final String unescapedCharacter = pair.getValue0();
        final String escapedCharacter = pair.getValue1();
        decodedKey = decodedKey.replace(escapedCharacter, unescapedCharacter);
    }
    return decodedKey;
}

17 View Complete Implementation : CypherQueryGraphHelper.java
Copyright Apache License 2.0
Author : apache
public Pair<String, Map<String, Object>> getVertexRequest(String streamsId) {
    ST getVertex = new ST(getVertexStringIdStatementTemplate);
    getVertex.add("id", streamsId);
    Pair<String, Map<String, Object>> queryPlusParameters = new Pair(getVertex.render(), null);
    LOGGER.debug("getVertexRequest", queryPlusParameters.toString());
    return queryPlusParameters;
}

17 View Complete Implementation : CypherQueryGraphHelper.java
Copyright Apache License 2.0
Author : apache
/**
 * getVerticesRequest gets all vertices with a label.
 * @param labelId labelId
 * @return pair (query, parameterMap)
 */
public Pair<String, Map<String, Object>> getVerticesRequest(String labelId) {
    ST getVertex = new ST(getVerticesLabelIdStatementTemplate);
    getVertex.add("type", labelId);
    Pair<String, Map<String, Object>> queryPlusParameters = new Pair(getVertex.render(), null);
    LOGGER.debug("getVertexRequest", queryPlusParameters.toString());
    return queryPlusParameters;
}