Example usage for java.math BigInteger valueOf

List of usage examples for java.math BigInteger valueOf

Introduction

In this page you can find the example usage for java.math BigInteger valueOf.

Prototype

private static BigInteger valueOf(int val[]) 

Source Link

Document

Returns a BigInteger with the given two's complement representation.

Usage

From source file:com.netflix.imfutility.cpl._2013.Cpl2013ContextBuilderStrategy.java

@Override
public BigFraction getCompositionTimecodeRate() {
    if (cpl2013.getCompositionTimecode() == null) {
        return null;
    }// www . j  a  v a2s . co m
    BigInteger rate = cpl2013.getCompositionTimecode().getTimecodeRate();
    boolean isDropFrame = cpl2013.getCompositionTimecode().isTimecodeDropFrame();
    if (rate == null || BigInteger.ZERO.equals(rate)) {
        return null;
    }

    // return as-is if non-drop
    if (!isDropFrame) {
        return new BigFraction(rate);
    }

    // return as 30000/1001 for 30 if drop frame
    return new BigFraction(rate.multiply(BigInteger.valueOf(1000)), BigInteger.valueOf(1001));
}

From source file:de.decoit.visa.net.IPAddress.java

/**
 * Return a {@link java.math.BigInteger BigInteger} object containing the
 * bit mask of this address.//from  w ww.  java  2 s .c  o  m
 *
 * @return Bit mask of this address
 */
BigInteger toBigIntBitmask() {
    BigInteger rv = BigInteger.ZERO;

    for (int i = 0; i < ipAddressGroups.length; i++) {
        rv = rv.add(BigInteger.valueOf(ipAddressGroups[i]));

        if (i < ipAddressGroups.length - 1) {
            rv = rv.shiftLeft(ipVersion.getSegmentBitCount());
        }
    }

    return rv;
}

From source file:co.rsk.peg.BridgeSerializationUtilsTest.java

@Test
public void serializeFederation() throws Exception {
    PowerMockito.mockStatic(RLP.class);
    mock_RLP_encodeBigInteger();//from   w  ww .  ja va  2s . co m
    mock_RLP_encodeList();
    mock_RLP_encodeElement();

    byte[][] publicKeyBytes = new byte[][] { BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKey(), };

    Federation federation = new Federation(
            Arrays.asList(new BtcECKey[] { BtcECKey.fromPublicOnly(publicKeyBytes[0]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[1]), BtcECKey.fromPublicOnly(publicKeyBytes[2]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[3]), BtcECKey.fromPublicOnly(publicKeyBytes[4]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[5]), }),
            Instant.ofEpochMilli(0xabcdef), //
            42L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST));

    byte[] result = BridgeSerializationUtils.serializeFederation(federation);
    StringBuilder expectedBuilder = new StringBuilder();
    expectedBuilder.append("ff00abcdef"); // Creation time
    expectedBuilder.append("ff2a"); // Creation block number
    federation.getPublicKeys().stream().sorted(BtcECKey.PUBKEY_COMPARATOR).forEach(key -> {
        expectedBuilder.append("dd");
        expectedBuilder.append(Hex.toHexString(key.getPubKey()));
    });
    byte[] expected = Hex.decode(expectedBuilder.toString());
    Assert.assertTrue(Arrays.equals(expected, result));
}

From source file:com.eventsourcing.hlc.HybridTimestamp.java

@Override
public BigInteger getSerializableComparable() {
    TimeStamp t = new TimeStamp(logicalTime);
    return BigInteger.valueOf(t.getSeconds()).shiftLeft(64)
            .add(BigInteger.valueOf(t.getFraction()).shiftLeft(32)).add(BigInteger.valueOf(logicalCounter));
}

From source file:Peer.java

@Override
public Key getSuccessor(Key key) throws Exception {
    lg.log(Level.FINEST, "getSuccessor Entry");

    lg.log(Level.FINER, "getSuccessor Calling succ:" + succ + " from peer:" + nodeid + " with key:" + key);

    // Ensure this peers successor is up to date 
    succ = superpeer.getSuccessor(nodeid);

    // If we have no successor, this peer is the successor
    if (succ == null) {
        return nodeid;
    }// w  w w . ja  v a  2s. c om

    // Ensure this peers predecessor is up to date
    pred = superpeer.getPredecessor(nodeid);

    // Get the max key value 
    Key max = new Key(BigInteger.valueOf((int) Math.pow(2, hasher.getBitSize()))).pred();

    // If this peer knows the which peer that key belongs to ...
    if (
    // Normal increasing range case
    (nodeid.compare(key) < 0 && key.compare(succ) <= 0)
            // Modulo case
            || (pred.compare(nodeid) > 0 && (key.compare(pred) > 0 && key.compare(max) <= 0)
                    || (key.compare(nodeid) <= 0))) {
        lg.log(Level.FINER, "getSuccessor - Known successor.");
        lg.log(Level.FINEST, "getSuccesssor Exit");
        return succ;
    }
    // ... else ask this peers successor
    else {
        lg.log(Level.FINER, "getSuccessor - Unknown successor.");
        try {
            lg.log(Level.FINEST, "getSuccesssor Exit");
            return getPeer(succ).getSuccessor(key);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    lg.log(Level.WARNING, "getSuccessor returning null");
    lg.log(Level.FINEST, "getSuccesssor Exit");
    return null;
}

From source file:org.geoserver.wps.DescribeProcess.java

void dataInputs(DataInputsType inputs, ProcessFactory pf, Name name) {
    Collection<String> outputMimeParameters = AbstractRawData.getOutputMimeParameters(name, pf).values();
    for (Parameter<?> p : pf.getParameterInfo(name).values()) {
        // skip the output mime choice params, they will be filled automatically by WPS
        if (outputMimeParameters.contains(p.key)) {
            continue;
        }/*ww w  .  j av  a2s.com*/

        InputDescriptionType input = wpsf.createInputDescriptionType();
        inputs.getInput().add(input);

        input.setIdentifier(Ows11Util.code(p.key));
        input.setTitle(Ows11Util.languageString(p.title));
        input.setAbstract(Ows11Util.languageString(p.description));

        // WPS spec specifies non-negative for unlimited inputs, so -1 -> 0
        input.setMaxOccurs(
                p.maxOccurs == -1 ? BigInteger.valueOf(Long.MAX_VALUE) : BigInteger.valueOf(p.maxOccurs));

        input.setMinOccurs(BigInteger.valueOf(p.minOccurs));

        List<ProcessParameterIO> ppios = ProcessParameterIO.findAll(p, context);
        if (ppios.isEmpty()) {
            throw new WPSException("Could not find process parameter for type " + p.key + "," + p.type);
        }

        //handle the literal case
        if (ppios.get(0) instanceof LiteralPPIO) {
            LiteralPPIO lppio = (LiteralPPIO) ppios.get(0);

            LiteralInputType literal = wpsf.createLiteralInputType();
            input.setLiteralData(literal);

            // map the java class to an xml type name
            if (!String.class.equals(lppio.getType())) {
                Class type = lppio.getType();
                if (PRIMITIVE_TO_WRAPPER.containsKey(type)) {
                    type = PRIMITIVE_TO_WRAPPER.get(type);
                }
                Name typeName = xsp.name(type);
                if (typeName != null) {
                    literal.setDataType(Ows11Util.type("xs:" + typeName.getLocalPart()));
                }
            }
            if (p.metadata.get(Parameter.OPTIONS) != null) {
                List<Object> options = (List<Object>) p.metadata.get(Parameter.OPTIONS);
                Object[] optionsArray = (Object[]) options.toArray(new Object[options.size()]);
                addAllowedValues(literal, optionsArray);
            } else if (lppio.getType().isEnum()) {
                Object[] enumValues = lppio.getType().getEnumConstants();
                addAllowedValues(literal, enumValues);
            } else {
                literal.setAnyValue(owsf.createAnyValueType());
            }

            try {
                if (p.sample != null) {
                    literal.setDefaultValue(lppio.encode(p.sample));
                }
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,
                        "Failed to fill the default value for input " + p.key + " of process " + name, e);
            }
        } else if (ppios.get(0) instanceof BoundingBoxPPIO) {
            input.setBoundingBoxData(buildSupportedCRSType());
        } else {
            //handle the complex data case
            SupportedComplexDataInputType complex = wpsf.createSupportedComplexDataInputType();
            input.setComplexData(complex);

            complex.setSupported(wpsf.createComplexDataCombinationsType());
            for (ProcessParameterIO ppio : ppios) {
                ComplexPPIO cppio = (ComplexPPIO) ppio;

                ComplexDataDescriptionType format = null;

                if (ppio instanceof RawDataPPIO) {
                    String[] mimeTypes = AbstractRawData.getMimeTypes(p);
                    for (String mimeType : mimeTypes) {
                        ComplexDataDescriptionType ddt = wpsf.createComplexDataDescriptionType();
                        ddt.setMimeType(mimeType);
                        complex.getSupported().getFormat().add(ddt);
                        if (format == null) {
                            format = ddt;
                        }
                    }
                } else {
                    format = wpsf.createComplexDataDescriptionType();
                    format.setMimeType(cppio.getMimeType());
                    // add to supported
                    complex.getSupported().getFormat().add(format);
                }

                //handle the default    
                if (complex.getDefault() == null) {
                    ComplexDataDescriptionType def = wpsf.createComplexDataDescriptionType();
                    def.setMimeType(format.getMimeType());

                    complex.setDefault(wpsf.createComplexDataCombinationType());
                    complex.getDefault().setFormat(def);
                }
            }
        }
    }
}

From source file:com.xerox.amazonws.sqs.MessageQueue.java

/**
 * Attempts to receive a message from the queue. The queue default visibility timeout
 * is used.//from  ww w.j  av  a 2s .  co m
 *
 * @return the message object
 */
public Message receiveMessage() throws SQSException {
    Message amessage[] = receiveMessages(BigInteger.valueOf(1L), ((BigInteger) (null)));
    if (amessage.length > 0)
        return amessage[0];
    else
        return null;
}

From source file:logic.ApachePolyNewtonForm.java

/**
 * Evaluate the Newton polynomial using nested multiplication. It is
 * also called <a href="http://mathworld.wolfram.com/HornersRule.html">
 * Horner's Rule</a> and takes O(N) time.
 *
 * @param a Coefficients in Newton form formula.
 * @param c Centers./*  w w w  . j a v  a2 s .  c o m*/
 * @param z Point at which the function value is to be computed.
 * @return the function value.
 * @throws NullArgumentException if any argument is {@code null}.
 * @throws NoDataException if any array has zero length.
 * @throws DimensionMismatchException if the size difference between
 * {@code a} and {@code c} is not equal to 1.
 */
public static BigInteger evaluate(BigInteger a[], double c[], double z)
        throws NullArgumentException, DimensionMismatchException, NoDataException {
    //        verifyInputArray(a, c);

    final int n = c.length;
    BigInteger value = a[n];
    for (int i = n - 1; i >= 0; i--) {
        value = a[i].add(BigInteger.valueOf((long) (z - c[i])).multiply(value));
    }

    return value;
}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.projects.ProjectsReadersTest.java

/**
 * Test the reader for the table mantis_category_table.
 *
 * @throws Exception/*from  ww w  . ja  v a  2  s . c o m*/
 *          Technical Exception
 */
@Test
public void testProjectCustomFieldsReader() throws Exception {
    final CustomFieldDefinitionData field1 = new CustomFieldDefinitionData();
    field1.setField(new ObjectRef(BigInteger.ONE, "field_1"));
    final CustomFieldDefinitionData field2 = new CustomFieldDefinitionData();
    field2.setField(new ObjectRef(BigInteger.valueOf(2), "field_2"));

    final CustomFieldDefinitionData[] expected = new CustomFieldDefinitionData[] { field1, field2 };

    Mockito.when(clientStub.mc_project_get_custom_fields("toto", "passwd", BigInteger.ONE))
            .thenReturn(expected);

    projectCustomFieldsReader.setClientStub(clientStub);

    for (int i = 0; i <= expected.length; i++) {
        final CustomFieldDefinitionData item = projectCustomFieldsReader.read();
        if (i < expected.length) {
            assertNotNull(item);
            assertEquals(expected[i].getField().getId(), item.getField().getId());
            assertEquals(expected[i].getField().getName(), item.getField().getName());
        } else {
            assertNull(item);
        }
    }
}

From source file:gedi.util.math.stat.distributions.OccupancyNumberDistribution.java

private void computeRational() {
    int maxA = b == 0 ? k : Math.min(k, n / b);
    aToProb = new double[maxA + 1];

    BigFraction[] aToProb = new BigFraction[maxA + 1];

    BigInteger bfac = factorial(b);

    long start = System.currentTimeMillis();
    double maxDiff = 0;

    aToProb[maxA] = BigFraction.ONE;//ww  w.jav a  2s .  c o  m
    for (int a = maxA - 1; a >= 0; a--) {
        int m = Math.min(k - a + 1, aToProb.length - a);
        aToProb[a] = BigFraction.ZERO;
        for (int i = 1; i < m; i++) {
            BigInteger rat = binomialCoefficientLargeInteger(k - a, i).multiply(factorial(n - a * b, i * b));
            if (n - a * b - i * b > 0)
                rat = rat.multiply(BigInteger.valueOf(k - a - i).pow(n - a * b - i * b));
            if (m - i > 0)
                rat = rat.multiply(bfac.pow(m - i));
            aToProb[a] = aToProb[a].add(new BigFraction(rat, BigInteger.ONE).multiply(aToProb[a + i]));
        }

        BigInteger rat = bfac.pow(m).multiply(BigInteger.valueOf(k - a).pow(n - a * b));

        aToProb[a] = BigFraction.ONE.subtract(aToProb[a].multiply(new BigFraction(BigInteger.ONE, rat)));
        this.aToProb[a] = new BigFraction(binomialCoefficientLargeInteger(k, a), BigInteger.ONE)
                .multiply(aToProb[a].multiply(rationalv(a, b, k, n))).doubleValue();

        maxDiff = max(maxDiff, abs(this.aToProb[a] - approximateProbability(a)));
        if (System.currentTimeMillis() - start > 500) {
            aToProxProb = this.aToProb = computeApproximateNormal();
            return;
        }
    }
    //      System.out.printf(Locale.US,"%d\t%d\t%d\t%d\t%.4g\t%.4f\n",b,k,n,maxDigit,maxDiff,(System.currentTimeMillis()-start)/1000.0);
}