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.baasbox.db.DbHelper.java

public static BigInteger getDBStorageFreeSpace() {
    if (BBConfiguration.getDBSizeThreshold() != BigInteger.ZERO)
        return BBConfiguration.getDBSizeThreshold();
    return BigInteger.valueOf(new File(BBConfiguration.getDBDir()).getFreeSpace());
}

From source file:com.javector.soaj.provider.generatedwsdl.TestProviderGeneratedWsdl.java

public void testProviderEJB21Invocation() throws Exception {

    SoajProviderService service = new SoajProviderService();
    SoajProviderPortType port = service.getSoajProviderPort();
    Item item = new Item();
    item.setPrice(3.99);/*w  ww.  j ava 2 s. c om*/
    item.setProductName("Diet Coke");
    item.setQuantity(BigInteger.valueOf(6));
    Items items = new Items();
    items.getItem().add(item);
    BillToType billTo = new BillToType();
    billTo.setCity("Canton");
    billTo.setPhone("(973) 243-8776");
    billTo.setState("OH");
    billTo.setStreet("125 Main Street");
    billTo.setZip("98134");
    PurchaseOrder po = new PurchaseOrder();
    po.setBillTo(billTo);
    po.setItems(items);
    BillToType response;
    try {
        response = port.getBillToFromEJB21(po);
    } catch (SOAPFaultException sfe) {
        SOAPFault sf = sfe.getFault();
        System.out.println("SOAPFault:" + IOUtil.NL + XmlUtil.toFormattedString(sf));
        sf.getDetail();
        throw sfe;
    }
    assertNotNull("SOAP Response should not be null.", response);
    System.out.println("bill to city = " + response.getCity());
    assertEquals("Canton", response.getCity());

}

From source file:org.btc4j.ws.impl.BtcDaemonServicePortImpl.java

@Override
public BigInteger getConnectionCount() throws BtcWsException {
    try {/*from  ww w  .j  a v a2  s.co m*/
        return BigInteger.valueOf(getDaemon("getConnectionCount").getConnectionCount());
    } catch (Throwable t) {
        throw btcWsException(t);
    }
}

From source file:io.hops.hopsworks.common.dao.tensorflow.config.TensorBoardProcessMgr.java

/**
 * Start the TensorBoard process/*from  w w  w.java  2 s  .  c o m*/
 * @param project
 * @param user
 * @param hdfsUser
 * @param hdfsLogdir
 * @return
 * @throws IOException
 */
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public TensorBoardDTO startTensorBoard(Project project, Users user, HdfsUsers hdfsUser, String hdfsLogdir)
        throws IOException {

    String prog = settings.getHopsworksDomainDir() + "/bin/tensorboard.sh";
    Process process = null;
    Integer port = 0;
    BigInteger pid = null;
    String tbBasePath = settings.getStagingDir() + Settings.TENSORBOARD_DIRS + File.separator;
    String projectUserUniquePath = project.getName() + "_" + hdfsUser.getName();
    String tbPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath);
    String certsPath = "\"\"";

    File tbDir = new File(tbPath);
    if (tbDir.exists()) {
        for (File file : tbDir.listFiles()) {
            if (file.getName().endsWith(".pid")) {
                String pidContents = com.google.common.io.Files.readFirstLine(file, Charset.defaultCharset());
                try {
                    pid = BigInteger.valueOf(Long.parseLong(pidContents));
                    if (pid != null && ping(pid) == 0) {
                        killTensorBoard(pid);
                    }
                } catch (NumberFormatException nfe) {
                    LOGGER.log(Level.WARNING,
                            "Expected number in pidfile " + file.getAbsolutePath() + " got " + pidContents);
                }
            }
        }
        FileUtils.deleteDirectory(tbDir);
    }
    tbDir.mkdirs();

    DistributedFileSystemOps dfso = dfsService.getDfsOps();
    try {
        certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs");
        File certsDir = new File(certsPath);
        certsDir.mkdirs();
        HopsUtils.materializeCertificatesForUserCustomDir(project.getName(), user.getUsername(),
                settings.getHdfsTmpCertDir(), dfso, certificateMaterializer, settings, certsPath);
    } catch (IOException ioe) {
        LOGGER.log(Level.SEVERE,
                "Failed in materializing certificates for " + hdfsUser + " in directory " + certsPath, ioe);
        HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(),
                settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings);
    } finally {
        if (dfso != null) {
            dfsService.closeDfsClient(dfso);
        }
    }

    String anacondaEnvironmentPath = settings.getAnacondaProjectDir(project.getName());
    int retries = 3;

    while (retries > 0) {

        if (retries == 0) {
            throw new IOException(
                    "Failed to start TensorBoard for project=" + project.getName() + ", user=" + user.getUid());
        }

        // use pidfile to kill any running servers
        port = ThreadLocalRandom.current().nextInt(40000, 59999);

        String[] command = new String[] { "/usr/bin/sudo", prog, "start", hdfsUser.getName(), hdfsLogdir,
                tbPath, port.toString(), anacondaEnvironmentPath, settings.getHadoopVersion(), certsPath,
                settings.getJavaHome() };

        LOGGER.log(Level.INFO, Arrays.toString(command));
        ProcessBuilder pb = new ProcessBuilder(command);

        try {
            // Send both stdout and stderr to the same stream
            pb.redirectErrorStream(true);

            process = pb.start();

            synchronized (pb) {
                try {
                    // Wait until the launcher bash script has finished
                    process.waitFor(20l, TimeUnit.SECONDS);
                } catch (InterruptedException ex) {
                    LOGGER.log(Level.SEVERE, "Woken while waiting for the TensorBoard to start: {0}",
                            ex.getMessage());
                }
            }

            int exitValue = process.exitValue();
            String pidPath = tbPath + File.separator + port + ".pid";
            File pidFile = new File(pidPath);
            // Read the pid for TensorBoard server
            if (pidFile.exists()) {
                String pidContents = com.google.common.io.Files.readFirstLine(pidFile,
                        Charset.defaultCharset());
                pid = BigInteger.valueOf(Long.parseLong(pidContents));
            }
            if (exitValue == 0 && pid != null) {
                int maxWait = 10;
                String logFilePath = tbPath + File.separator + port + ".log";
                File logFile = new File(logFilePath);
                while (maxWait > 0) {
                    String logFileContents = com.google.common.io.Files.readFirstLine(logFile,
                            Charset.defaultCharset());
                    // It is not possible to have a fixed wait time before showing the TB, we need to be sure it has started
                    if (logFile.length() > 0
                            && (logFileContents.contains("Loaded") | logFileContents.contains("Reloader")
                                    | logFileContents.contains("event")) | maxWait == 1) {
                        Thread.currentThread().sleep(5000);
                        TensorBoardDTO tensorBoardDTO = new TensorBoardDTO();
                        String host = null;
                        try {
                            host = InetAddress.getLocalHost().getHostAddress();
                        } catch (UnknownHostException ex) {
                            Logger.getLogger(TensorBoardProcessMgr.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        tensorBoardDTO.setEndpoint(host + ":" + port);
                        tensorBoardDTO.setPid(pid);
                        return tensorBoardDTO;
                    } else {
                        Thread.currentThread().sleep(1000);
                        maxWait--;
                    }
                }
                TensorBoardDTO tensorBoardDTO = new TensorBoardDTO();
                tensorBoardDTO.setPid(pid);
                String host = null;
                try {
                    host = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException ex) {
                    Logger.getLogger(TensorBoardProcessMgr.class.getName()).log(Level.SEVERE, null, ex);
                }
                tensorBoardDTO.setEndpoint(host + ":" + port);
                return tensorBoardDTO;
            } else {
                LOGGER.log(Level.SEVERE,
                        "Failed starting TensorBoard got exitcode " + exitValue + " retrying on new port");
                if (pid != null) {
                    this.killTensorBoard(pid);
                }
                pid = null;
            }

        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, "Problem starting TensorBoard: {0}", ex);
            if (process != null) {
                process.destroyForcibly();
            }
        } finally {
            retries--;
        }
    }

    //Failed to start TensorBoard, make sure there is no process running for it! (This should not be needed)
    if (pid != null && this.ping(pid) == 0) {
        this.killTensorBoard(pid);
    }

    //Certificates cleanup in case they were materialized but no TB started successfully

    dfso = dfsService.getDfsOps();
    certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs");
    File certsDir = new File(certsPath);
    certsDir.mkdirs();
    try {
        HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(),
                settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings);
    } finally {
        if (dfso != null) {
            dfsService.closeDfsClient(dfso);
        }
    }

    return null;
}

From source file:logic.ApacheInterpolation.java

/**
 * Return a copy of the divided difference array.
 * <p>/*from w w  w. j  a  v  a  2s.  co  m*/
 * The divided difference array is defined recursively by <pre>
 * f[x0] = f(x0)
 * f[x0,x1,...,xk] = (f[x1,...,xk] - f[x0,...,x[k-1]]) / (xk - x0)
 * </pre></p>
 * <p>
 * The computational complexity is O(N^2).</p>
 *
 * @param x Interpolating points array.
 * @param y Interpolating values array.
 * @return a fresh copy of the divided difference array.
 * @throws DimensionMismatchException if the array lengths are different.
 * @throws NumberIsTooSmallException if the number of points is less than 2.
 * @throws NonMonotonicSequenceException
 * if {@code x} is not sorted in strictly increasing order.
 */
protected static BigInteger[] computeDividedDifference(final double x[], final BigInteger y[])
        throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException {

    //        No need to check, the condition must be valid according to the paper
    //        PolynomialFunctionLagrangeForm.verifyInterpolationArray(x, y, true);

    final BigInteger[] divdiff = y.clone(); // initialization

    final int n = x.length;
    final BigInteger[] a = new BigInteger[n];
    a[0] = divdiff[0];
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < n - i; j++) {
            final BigInteger denominator = BigInteger.valueOf((long) (x[j + i] - x[j]));
            divdiff[j] = (divdiff[j + 1].subtract(divdiff[j])).divide(denominator);
        }
        a[i] = divdiff[0];
    }

    return a;
}

From source file:net.big_oh.common.utils.CollectionsUtil.java

protected static <T> BigInteger countCombinations(int n, int k) throws IllegalArgumentException {
    // sanity check
    if (k < 0) {
        throw new IllegalArgumentException("The value of the k parameter cannot be less than zero.");
    }//from ww w. j  a va  2  s .  co m
    if (k > n) {
        throw new IllegalArgumentException(
                "The value of the k parameter cannot be greater than n, the size of the originalSet.");
    }

    // The end result will be equal to n! / (k! * ((n-k)!))

    // start by doing some up front evaluation of the denominator
    int maxDenomArg;
    int minDenomArg;
    if ((n - k) > k) {
        maxDenomArg = (n - k);
        minDenomArg = k;
    } else {
        maxDenomArg = k;
        minDenomArg = (n - k);
    }

    // First, do an efficient calculation of n! / maxDenomArg!
    BigInteger partialCalculation = BigInteger.ONE;
    for (int i = maxDenomArg + 1; i <= n; i++) {
        partialCalculation = partialCalculation.multiply(BigInteger.valueOf(i));
    }

    // Lastly, produce the final solution by calculating partialCalculation / minDenomArg!
    return partialCalculation.divide(MathUtil.factorial(minDenomArg));
}

From source file:de.tudarmstadt.ukp.dkpro.core.decompounding.web1t.Finder.java

public BigInteger getUnigramCount() {
    return BigInteger.valueOf(web1tSearcher.getNrOfNgrams(1));
}

From source file:com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesServiceTest.java

/**
 * Test method for {@link com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesService#insertUserIfNotExists(biz.futureware.mantis.rpc.soap.client.AccountData, java.math.BigInteger)}.
 *///w  ww . ja  v a2 s  .c  o  m
@Test
public void testInsertUserIfNotExistsProjectNull() {
    final AccountData item = new AccountData();
    item.setId(BigInteger.valueOf(1));
    item.setName("new_user_1");

    dao.insertUserIfNotExists(item, null);

    final List<AccountData> list = getJdbcTemplate().query(
            "SELECT usr.id, usr.name" + " FROM mantis_user_table usr",
            new BeanPropertyRowMapper<AccountData>(AccountData.class));

    assertEquals(1, list.size());
    assertEquals(item, list.get(0));
}

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getHistogramPartitions(KmerHistogramRecord[] records, long samples) {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    String As = "";
    String Ts = "";
    for (int i = 0; i < this.kmerSize; i++) {
        As += "A";
        Ts += "T";
    }//from w  w  w  .  j  a  v a2  s.co  m

    long partitionWidth = samples / this.numPartitions;
    long partitionWidthRemain = partitionWidth;
    int partitionIdx = 0;
    int recordIdx = 0;
    long curRecordRemain = records[0].getFrequency();
    BigInteger nextPartitionBegin = BigInteger.ZERO;
    while (partitionIdx < this.numPartitions) {
        long diff = partitionWidthRemain - curRecordRemain;
        if (diff > 0) {
            partitionWidthRemain -= curRecordRemain;
            recordIdx++;
            if (recordIdx < records.length) {
                curRecordRemain = records[recordIdx].getFrequency();
            } else {
                break;
            }
        } else if (diff == 0) {
            BigInteger partitionBegin = nextPartitionBegin;
            BigInteger partitionEnd = null;
            if (partitionIdx == this.numPartitions - 1) {
                partitionEnd = SequenceHelper.convertToBigInteger(Ts);
            } else {
                partitionEnd = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + Ts).substring(0, this.kmerSize));
            }
            BigInteger partitionSize = partitionEnd.subtract(partitionBegin);
            partitions[partitionIdx] = new KmerRangePartition(this.kmerSize, this.numPartitions, partitionIdx,
                    partitionSize, partitionBegin, partitionEnd);

            nextPartitionBegin = partitionEnd.add(BigInteger.ONE);
            partitionIdx++;
            recordIdx++;
            if (recordIdx < records.length) {
                curRecordRemain = records[recordIdx].getFrequency();
            } else {
                break;
            }
            partitionWidthRemain = partitionWidth;
        } else {
            // in between
            BigInteger partitionBegin = nextPartitionBegin;
            BigInteger partitionEnd = null;
            if (partitionIdx == this.numPartitions - 1) {
                partitionEnd = SequenceHelper.convertToBigInteger(Ts);
            } else {
                BigInteger recordBegin = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + As).substring(0, this.kmerSize));
                BigInteger recordEnd = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + Ts).substring(0, this.kmerSize));
                BigInteger recordWidth = recordEnd.subtract(recordBegin);
                BigInteger curWidth = recordWidth.multiply(BigInteger.valueOf(partitionWidthRemain))
                        .divide(BigInteger.valueOf(records[recordIdx].getFrequency()));

                BigInteger bigger = null;
                if (recordBegin.compareTo(partitionBegin) > 0) {
                    bigger = recordBegin;
                } else {
                    bigger = partitionBegin;
                }

                partitionEnd = bigger.add(curWidth);
            }
            BigInteger partitionSize = partitionEnd.subtract(partitionBegin);
            partitions[partitionIdx] = new KmerRangePartition(this.kmerSize, this.numPartitions, partitionIdx,
                    partitionSize, partitionBegin, partitionEnd);

            nextPartitionBegin = partitionEnd.add(BigInteger.ONE);
            partitionIdx++;
            curRecordRemain -= partitionWidthRemain;
            partitionWidthRemain = partitionWidth;
        }
    }

    return partitions;
}

From source file:io.getlime.security.powerauth.app.server.service.behavior.VaultUnlockServiceBehavior.java

/**
 * Method to retrieve the vault unlock key. Before calling this method, it is assumed that
 * client application performs signature validation - this method should not be called unauthenticated.
 * To indicate the signature validation result, 'isSignatureValid' boolean is passed as one of the
 * method parameters./*from  w  w  w .jav a 2s  .  co  m*/
 *
 * @param activationId           Activation ID.
 * @param isSignatureValid       Information about validity of the signature.
 * @param keyConversionUtilities Key conversion utilities.
 * @return Vault unlock response with a properly encrypted vault unlock key.
 * @throws InvalidKeySpecException In case invalid key is provided.
 * @throws InvalidKeyException     In case invalid key is provided.
 */
public VaultUnlockResponse unlockVault(String activationId, boolean isSignatureValid,
        CryptoProviderUtil keyConversionUtilities) throws InvalidKeySpecException, InvalidKeyException {
    // Find related activation record
    ActivationRecordEntity activation = powerAuthRepository.findFirstByActivationId(activationId);

    if (activation != null && activation.getActivationStatus() == ActivationStatus.ACTIVE) {

        // Check if the signature is valid
        if (isSignatureValid) {

            // Get the server private and device public keys
            byte[] serverPrivateKeyBytes = BaseEncoding.base64().decode(activation.getServerPrivateKeyBase64());
            byte[] devicePublicKeyBytes = BaseEncoding.base64().decode(activation.getDevicePublicKeyBase64());
            PrivateKey serverPrivateKey = keyConversionUtilities
                    .convertBytesToPrivateKey(serverPrivateKeyBytes);
            PublicKey devicePublicKey = keyConversionUtilities.convertBytesToPublicKey(devicePublicKeyBytes);

            // Get encrypted vault unlock key and increment the counter
            Long counter = activation.getCounter();
            byte[] cKeyBytes = powerAuthServerVault.encryptVaultEncryptionKey(serverPrivateKey, devicePublicKey,
                    counter);
            activation.setCounter(counter + 1);
            powerAuthRepository.save(activation);

            // return the data
            VaultUnlockResponse response = new VaultUnlockResponse();
            response.setActivationId(activationId);
            response.setActivationStatus(ModelUtil.toServiceStatus(ActivationStatus.ACTIVE));
            response.setRemainingAttempts(BigInteger.valueOf(activation.getMaxFailedAttempts()));
            response.setSignatureValid(true);
            response.setUserId(activation.getUserId());
            response.setEncryptedVaultEncryptionKey(BaseEncoding.base64().encode(cKeyBytes));

            return response;

        } else {

            // Even if the signature is not valid, increment the counter
            Long counter = activation.getCounter();
            activation.setCounter(counter + 1);
            powerAuthRepository.save(activation);

            // return the data
            VaultUnlockResponse response = new VaultUnlockResponse();
            response.setActivationId(activationId);
            response.setActivationStatus(ModelUtil.toServiceStatus(activation.getActivationStatus()));
            response.setRemainingAttempts(
                    BigInteger.valueOf(activation.getMaxFailedAttempts() - activation.getFailedAttempts()));
            response.setSignatureValid(false);
            response.setUserId(activation.getUserId());
            response.setEncryptedVaultEncryptionKey(null);

            return response;
        }

    } else {

        // return the data
        VaultUnlockResponse response = new VaultUnlockResponse();
        response.setActivationId(activationId);
        response.setActivationStatus(ModelUtil.toServiceStatus(ActivationStatus.REMOVED));
        response.setRemainingAttempts(BigInteger.valueOf(0));
        response.setSignatureValid(false);
        response.setUserId("UNKNOWN");
        response.setEncryptedVaultEncryptionKey(null);

        return response;
    }
}