public void test_key(BigInteger keyId, String passphrase) throws Exception {

    PGPSecretKeyRingCollection secretKeyRing = loadSecretKeyCollection("secring.gpg");

    PGPSecretKeyRing secretKey = secretKeyRing.getSecretKeyRing(keyId.longValue());
    assertNotNull("Could not locate secret keyring with Id=" + keyId.toString(16), secretKey);

    PGPSecretKey key = secretKey.getSecretKey();
    assertNotNull("Could not locate secret key!", key);

    try {
      PGPDigestCalculatorProvider calcProvider =
          new JcaPGPDigestCalculatorProviderBuilder()
              .setProvider(BouncyCastleProvider.PROVIDER_NAME)
              .build();

      PBESecretKeyDecryptor decryptor =
          new JcePBESecretKeyDecryptorBuilder(calcProvider)
              .setProvider(BouncyCastleProvider.PROVIDER_NAME)
              .build(passphrase.toCharArray());

      PGPPrivateKey privateKey = key.extractPrivateKey(decryptor);

      assertTrue(privateKey.getKeyID() == keyId.longValue());

    } catch (PGPException e) {
      throw new PGPException("Password incorrect!", e);
    }

    // all fine!
  }
  /**
   * Add <code>valueToAdd</code> metrics to the <code>avg</code> metrics object for the metric
   * <code>metric</code>
   *
   * @param metric the metric type being added
   * @param avg the average metric object that is being added to
   * @param valueToAdd the values being added to <code>avg</code> object
   */
  private void addToAvg(String metric, AvgMetric avg, HCPerfElement valueToAdd) {
    if (valueToAdd == null) return;

    BigInteger execTime = valueToAdd.getExecTime();
    BigInteger ops = valueToAdd.getOps();
    String opsPerSec = valueToAdd.getOpSec();
    if (execTime == null || ops == null || opsPerSec == null) {
      // These should never be null
      Logger.getLogger(CommandPerfStats.class.getName())
          .log(
              Level.WARNING,
              "CLI Internal Error: "
                  + metric
                  + " got unexpected null value, execTime="
                  + execTime
                  + " ops="
                  + ops);
      return;
    }

    // The underlying code on the server always does it calculations
    // using the time interval we specified.  We need the actual time
    // interval to get really accurate calculations here.  However,
    // since the design of performance needs to change (in where
    // the client should do the calculations) for now keep it simple and
    // just use the time interval we set since we know this is what
    // the master is doing for us.  This won't be accurate if 2+ users
    // are doing performance monitoring.
    String kbPerSec = valueToAdd.getKbSec();
    if (kbPerSec == null) avg.add(ops.longValue(), pollingInterval, execTime.longValue());
    else avg.add(ops.longValue(), pollingInterval, execTime.longValue(), Double.valueOf(kbPerSec));
  }
Exemple #3
0
 // Try to convert the specified value.
 private static Number convert(Number value, UnitConverter cvtr, MathContext ctx) {
   if (cvtr instanceof RationalConverter) { // Try converting through Field
     // methods.
     RationalConverter rCvtr = (RationalConverter) cvtr;
     BigInteger dividend = rCvtr.getDividend();
     BigInteger divisor = rCvtr.getDivisor();
     if (dividend.abs().compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
       throw new ArithmeticException("Multiplier overflow");
     if (divisor.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
       throw new ArithmeticException("Divisor overflow");
     return (value.longValue() * dividend.longValue()) / (divisor.longValue());
   } else if (cvtr instanceof AbstractConverter.Compound
       && cvtr.isLinear()) { // Do it in two parts.
     AbstractConverter.Compound compound = (AbstractConverter.Compound) cvtr;
     Number firstConversion = convert(value, compound.getRight(), ctx);
     Number secondConversion = convert(firstConversion, compound.getLeft(), ctx);
     return secondConversion;
   } else { // Try using BigDecimal as intermediate.
     BigDecimal decimalValue = BigDecimal.valueOf(value.doubleValue());
     Number newValue = cvtr.convert(decimalValue.toBigDecimal(), ctx);
     return newValue;
     // if (((FieldNumber)value) instanceof Decimal)
     // return (N)((FieldNumber)Decimal.valueOf(newValue));
     // if (((FieldNumber)value) instanceof Float64)
     // return (N)((FieldNumber)Float64.valueOf(newValue.doubleValue()));
     // throw new ArithmeticException(
     // "Generic amount conversion not implemented for amount of type " +
     // value.getClass());
   }
 }
  @Override
  public int read(DataInputStream dis, final int len) throws IOException {

    byte[] buf = new byte[len];
    dis.readFully(buf);
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest(MOVReader.bytes2hex(buf));
    }

    byte version = buf[0];
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("Version = " + version);
      logger.finest("Flags = " + buf[1] + buf[2] + buf[3]);
    }

    int offset = 4;

    BigInteger creationTime = null;
    if (version == 0x00) {
      creationTime = new BigInteger(Arrays.copyOfRange(buf, offset, offset += 4));
    } else if (version == 0x01) {
      creationTime = new BigInteger(Arrays.copyOfRange(buf, offset, offset += 8));
    }
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("Creation time = " + MOVReader.formatDate(creationTime.longValue()));
    }

    BigInteger modificationTime = null;
    if (version == 0x00) {
      modificationTime = new BigInteger(Arrays.copyOfRange(buf, offset, offset += 4));
    } else if (version == 0x01) {
      modificationTime = new BigInteger(Arrays.copyOfRange(buf, offset, offset += 8));
    }
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("Modification time = " + MOVReader.formatDate(modificationTime.longValue()));
    }

    BigInteger timescale = new BigInteger(Arrays.copyOfRange(buf, offset, offset += 4));
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("Timescale = " + timescale);
    }

    BigInteger duration = null;
    if (version == 0) {
      duration = new BigInteger(Arrays.copyOfRange(buf, offset, offset += 4));
    } else if (version == 1) {
      duration = new BigInteger(Arrays.copyOfRange(buf, offset, offset += 8));
    }
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("Duration = " + duration);
    }

    offset += 2; // language

    offset += 2; // reserved

    return len;
  }
 /** @tests java.math.BigInteger#longValue() */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "longValue",
     args = {})
 public void test_longValue() {
   assertTrue("Incorrect longValue for 2**70", twoToTheSeventy.longValue() == 0);
   assertTrue("Incorrect longValue for 2", two.longValue() == 2);
 }
Exemple #6
0
 /**
  * Method byteArrayToUUID.
  *
  * @param uuidBytes byte[]
  * @return UUID
  */
 public static UUID byteArrayToUUID(byte[] uuidBytes) {
   // uuidBytes is expected to be 16 bytes long
   byte[] ba_msb = new byte[8];
   System.arraycopy(uuidBytes, 0, ba_msb, 0, 8);
   byte[] ba_lsb = new byte[8];
   System.arraycopy(uuidBytes, 8, ba_lsb, 0, 8);
   BigInteger msb = new BigInteger(ba_msb);
   BigInteger lsb = new BigInteger(ba_lsb);
   return new UUID(msb.longValue(), lsb.longValue());
 }
 @Override
 public Page<T> queryNativeSqlPageEntity(String _nativeSql, Object[] _params, Pageable _pageable) {
   List<T> dataList = queryNativeSqlListEntity(_nativeSql, _params, _pageable);
   java.math.BigInteger count = getNativeResultCount(_nativeSql, _params);
   Page<T> page = new PageImpl<T>(dataList, _pageable, count.longValue());
   return page;
 }
  // A java workaround for header fields like seq/ack which are ulongs --M
  public static long convertUnsignedInt(byte[] data, int offset) {
    byte[] target = new byte[4];
    System.arraycopy(data, offset, target, 0, target.length);

    BigInteger placeholder = new BigInteger(1, target);
    return placeholder.longValue();
  }
Exemple #9
0
  public static List range(BigInteger start, BigInteger end) {
    List l = new List();

    long st = start.longValue();
    long en = start.longValue();
    if (BigInteger.valueOf(st).equals(start) && BigInteger.valueOf(en).equals(end)) {
      int dir = st < en ? 1 : -1;
      while (st != en) {
        l.add(BigInteger.valueOf(st));
        st = st + dir;
      }
    } else {
      BigInteger dir;
      if (start.compareTo(end) < 0) {
        dir = BigInteger.ONE;
      } else {
        dir = BigInteger.valueOf(-1);
      }
      while (!start.equals(end)) {
        l.add(start);
        start = start.add(dir);
      }
    }

    return l;
  }
  public void monitorFired(NoSqlEntityManager mgr, PlayOrmCronJob mon) {
    String mode = Play.configuration.getProperty("upgrade.mode");
    if ("NEW".equals(mode) || StringUtils.isEmpty(mode)) {
      runNewCode(mgr, mon);
      return;
    }

    TableMonitor tableMon = TableMonitor.copy(mon);
    if (log.isInfoEnabled()) log.info("monitor firing(old version)=" + tableMon);

    String tableName = tableMon.getTableName();
    // NOTE: d.time>0 is here because PlayOrm does not yet have order by asc(time) which would
    // choose the index
    // so instead PlayOrm randomly chooses an index
    String sql = "select d from " + tableName + " as d where d.time>0";
    NoSqlTypedSession s = mgr.getTypedSession();
    QueryResult result = s.createQueryCursor(sql, 1); // only need last
    // point so batch
    // size of 1

    Cursor<KeyValue<TypedRow>> cursor = result.getPrimaryViewCursor();
    TypedRow r = getLastVal(cursor);
    DateTime now = new DateTime();
    if (r == null) {
      fireEmailStreamIsDown("old", null, now, tableMon);
      return;
    }

    BigInteger timestamp = (BigInteger) r.getRowKey();

    runDataCheck("old", tableMon, now, timestamp.longValue());
  }
Exemple #11
0
 public static long toLong(String values) throws NumberFormatException {
   // Long.parseLong() can't handle HexStrings with MSB set. Sigh.
   BigInteger bi = new BigInteger(values.replaceAll(":", ""), 16);
   if (bi.bitLength() > 64)
     throw new NumberFormatException("Input string too big to fit in long: " + values);
   return bi.longValue();
 }
  @Test
  public void testSimplePayment() throws Exception {
    // Create a PaymentRequest and make sure the correct values are parsed by the PaymentSession.
    MockPaymentSession paymentSession = new MockPaymentSession(newSimplePaymentRequest());
    assertEquals(paymentRequestMemo, paymentSession.getMemo());
    assertEquals(nanoCoins, paymentSession.getValue());
    assertEquals(simplePaymentUrl, paymentSession.getPaymentUrl());
    assertTrue(new Date(time * 1000L).equals(paymentSession.getDate()));
    assertTrue(paymentSession.getSendRequest().tx.equals(tx));
    assertFalse(paymentSession.isExpired());

    // Send the payment and verify that the correct information is sent.
    // Add a dummy input to tx so it is considered valid.
    tx.addInput(new TransactionInput(params, tx, outputToMe.getScriptBytes()));
    ArrayList<Transaction> txns = new ArrayList<Transaction>();
    txns.add(tx);
    Address refundAddr = new Address(params, serverKey.getPubKeyHash());
    paymentSession.sendPayment(txns, refundAddr, paymentMemo);
    assertEquals(1, paymentSession.getPaymentLog().size());
    assertEquals(simplePaymentUrl, paymentSession.getPaymentLog().get(0).getUrl().toString());
    Protos.Payment payment = paymentSession.getPaymentLog().get(0).getPayment();
    assertEquals(paymentMemo, payment.getMemo());
    assertEquals(merchantData, payment.getMerchantData());
    assertEquals(1, payment.getRefundToCount());
    assertEquals(nanoCoins.longValue(), payment.getRefundTo(0).getAmount());
    TransactionOutput refundOutput = new TransactionOutput(params, null, nanoCoins, refundAddr);
    ByteString refundScript = ByteString.copyFrom(refundOutput.getScriptBytes());
    assertTrue(refundScript.equals(payment.getRefundTo(0).getScript()));
  }
 /**
  * Writes unsigned 64-bit integer <code>value</code> if not null, otherwise writes zeros to the
  * <code>output</code> ByteBuf. ByteBuf's writerIndex is increased by 8.
  *
  * @param value BigInteger value to be written to the output.
  * @param output ByteBuf, where value or zeros are written.
  */
 public static void writeUnsignedLong(final BigInteger value, final ByteBuf output) {
   if (value != null) {
     output.writeLong(value.longValue());
   } else {
     output.writeZero(LONG_BYTES_LENGTH);
   }
 }
 public static long unsignedAdd(long v1, long v2) {
   BigInteger a = Lyra2.long2unsigned(v1);
   BigInteger b = Lyra2.long2unsigned(v2);
   a = a.add(b);
   a = Lyra2.overflowUint64_t(a);
   return a.longValue();
 }
 private void writeToDatabase(Date time, Value<?> value) {
   try {
     Parameter<?> parameter = value.getParameter();
     if (!parameter.isNumeric()) {
       throw new IllegalArgumentException("The value '" + value.toString() + "' is not numeric!");
     }
     BigDecimal decimalValue = null;
     BigInteger integerValue = null;
     if (Long.class.isAssignableFrom(parameter.getType())) {
       integerValue = BigInteger.valueOf((Long) value.getValue());
     } else {
       decimalValue = BigDecimal.valueOf((Double) value.getValue());
     }
     preparedStatement.setTime(1, new Time(time.getTime()));
     preparedStatement.setString(2, server);
     preparedStatement.setString(3, parameter.getName());
     preparedStatement.setString(4, parameter.getUnit());
     preparedStatement.setString(5, parameter.getType().getName());
     preparedStatement.setString(6, parameter.getDescription());
     preparedStatement.setBigDecimal(7, decimalValue);
     preparedStatement.setLong(8, integerValue.longValue());
     preparedStatement.setString(9, parameter.getLevelOfMeasurement().name());
     preparedStatement.execute();
   } catch (SQLException e) {
     throw new RuntimeException("Could not insert event into event log.", e);
   }
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigDecimal(obj)) {
     return super.write(buff, obj);
   }
   BigDecimal x = (BigDecimal) obj;
   if (BigDecimal.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_0);
   } else if (BigDecimal.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_1);
   } else {
     int scale = x.scale();
     BigInteger b = x.unscaledValue();
     int bits = b.bitLength();
     if (bits < 64) {
       if (scale == 0) {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL);
       } else {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED);
         DataUtils.writeVarInt(buff, scale);
       }
       DataUtils.writeVarLong(buff, b.longValue());
     } else {
       buff.put((byte) TYPE_BIG_DECIMAL);
       DataUtils.writeVarInt(buff, scale);
       byte[] bytes = b.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
  @Override
  public Object executeFunction() {
    String conc_string = (String) this.getConcArgument(0);
    NonNullReference str_ref = (NonNullReference) this.getSymbArgument(0);

    StringValue symb_string =
        this.env.heap.getField(
            Types.JAVA_LANG_STRING, SymbolicHeap.$STRING_VALUE, conc_string, str_ref, conc_string);

    if (symb_string.containsSymbolicVariable()) {

      NonNullReference symb_big_integer = (NonNullReference) env.topFrame().operandStack.peekRef();

      BigInteger bigInteger = new BigInteger(conc_string);
      long concVal = bigInteger.longValue();

      StringToIntegerCast big_integer_value = new StringToIntegerCast(symb_string, concVal);

      env.heap.putField(
          Types.JAVA_MATH_BIG_INTEGER,
          SymbolicHeap.$BIG_INTEGER_CONTENTS,
          null /* conc_big_integer */,
          symb_big_integer,
          big_integer_value);
    }

    // return void
    return null;
  }
 @Override
 public void write(WriteBuffer buff, Object obj) {
   if (!isBigDecimal(obj)) {
     super.write(buff, obj);
     return;
   }
   BigDecimal x = (BigDecimal) obj;
   if (BigDecimal.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_0);
   } else if (BigDecimal.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_1);
   } else {
     int scale = x.scale();
     BigInteger b = x.unscaledValue();
     int bits = b.bitLength();
     if (bits < 64) {
       if (scale == 0) {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL);
       } else {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED).putVarInt(scale);
       }
       buff.putVarLong(b.longValue());
     } else {
       byte[] bytes = b.toByteArray();
       buff.put((byte) TYPE_BIG_DECIMAL).putVarInt(scale).putVarInt(bytes.length).put(bytes);
     }
   }
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigInteger(obj)) {
     return super.write(buff, obj);
   }
   BigInteger x = (BigInteger) obj;
   if (BigInteger.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_0);
   } else if (BigInteger.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_1);
   } else {
     int bits = x.bitLength();
     if (bits <= 63) {
       buff.put((byte) TAG_BIG_INTEGER_SMALL);
       DataUtils.writeVarLong(buff, x.longValue());
     } else {
       buff.put((byte) TYPE_BIG_INTEGER);
       byte[] bytes = x.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
 @Test(timeout = 5000L)
 public void powExactLongIntExact() {
   for (long base : LONGS) {
     for (int power : INTS) {
       if (power < 0) continue;
       boolean overflow =
           BigInteger.valueOf(63 - Long.numberOfLeadingZeros(Math.abs(base)))
                   .multiply(BigInteger.valueOf(power))
                   .compareTo(BigInteger.valueOf(64))
               > 0;
       BigInteger expected = overflow ? null : BigInteger.valueOf(base).pow(power);
       if (expected != null && expected.bitLength() <= 63) {
         long value = powExact(base, power);
         assertEquals(base + " ^ " + power, expected.longValue(), value);
         if (value < 10000000000000000L)
           assertEquals(
               base + " ^ " + power, power == 1 ? base : (long) Math.pow(base, power), value);
         assertEquals(base + " ^ " + power, pow(base, power), value);
       } else {
         try {
           powExact(base, power);
           fail("Should overflow: " + base + " ^ " + power);
         } catch (ArithmeticException e) {
         }
       }
     }
   }
 }
  private void parseDecimalColumn(int column) {
    // don't include column number in message because it causes boxing which is expensive here
    checkArgument(!isPartitionColumn[column], "Column is a partition key");

    loaded[column] = true;

    Object fieldData = rowInspector.getStructFieldData(rowData, structFields[column]);

    if (fieldData == null) {
      nulls[column] = true;
    } else {
      Object fieldValue =
          ((PrimitiveObjectInspector) fieldInspectors[column]).getPrimitiveJavaObject(fieldData);
      checkState(fieldValue != null, "fieldValue should not be null");

      HiveDecimal decimal = (HiveDecimal) fieldValue;
      DecimalType columnType = (DecimalType) types[column];
      BigInteger unscaledDecimal =
          rescale(decimal.unscaledValue(), decimal.scale(), columnType.getScale());

      if (columnType.isShort()) {
        longs[column] = unscaledDecimal.longValue();
      } else {
        slices[column] = Decimals.encodeUnscaledValue(unscaledDecimal);
      }
      nulls[column] = false;
    }
  }
Exemple #22
0
 public static void main(String[] args) {
   Scanner cin = new Scanner(System.in);
   BigInteger A, B;
   A = cin.nextBigInteger();
   B = cin.nextBigInteger();
   long b = B.longValue();
   if (b == 1) {
     System.out.println(A);
     return;
   }
   long S[] = new long[10010];
   int cnt = 0;
   while (A.compareTo(BigInteger.ZERO) != 0) {
     S[cnt++] = A.mod(B).longValue();
     A = A.divide(B);
   }
   long dp[][] = new long[10010][2];
   dp[0][0] = S[0];
   dp[0][1] = b - S[0];
   for (int i = 1; i < cnt; ++i) {
     dp[i][0] = Math.min(dp[i - 1][0] + S[i], dp[i - 1][1] + S[i] + 1);
     dp[i][1] = Math.min(dp[i - 1][0] + b - S[i], dp[i - 1][1] + b - S[i] - 1);
   }
   long ret = Math.min(dp[cnt - 1][0], dp[cnt - 1][1] + 1);
   System.out.println(ret);
 }
Exemple #23
0
 /**
  * Returns the square root of {@code x}, rounded with the specified rounding mode.
  *
  * @throws IllegalArgumentException if {@code x < 0}
  * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
  *     sqrt(x)} is not an integer
  */
 @GwtIncompatible // TODO
 @SuppressWarnings("fallthrough")
 public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
   checkNonNegative("x", x);
   if (fitsInLong(x)) {
     return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode));
   }
   BigInteger sqrtFloor = sqrtFloor(x);
   switch (mode) {
     case UNNECESSARY:
       checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through
     case FLOOR:
     case DOWN:
       return sqrtFloor;
     case CEILING:
     case UP:
       int sqrtFloorInt = sqrtFloor.intValue();
       boolean sqrtFloorIsExact =
           (sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32
               && sqrtFloor.pow(2).equals(x); // slow exact check
       return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
     case HALF_DOWN:
     case HALF_UP:
     case HALF_EVEN:
       BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor);
       /*
        * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
        * and halfSquare are integers, this is equivalent to testing whether or not x <=
        * halfSquare.
        */
       return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
     default:
       throw new AssertionError();
   }
 }
  public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i = 0; i < primesTo100.length; i++) {
      p1 = p1.nextProbablePrime();
      if (p1.longValue() != primesTo100[i]) {
        System.err.println("low range primes failed");
        System.err.println("p1 is " + p1);
        System.err.println("expected " + primesTo100[i]);
        failCount++;
      }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i = 1; i < aPrimeSequence.length; i++) {
      p1 = p1.nextProbablePrime();
      if (p1.longValue() != aPrimeSequence[i]) {
        System.err.println("prime sequence failed");
        failCount++;
      }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i = 0; i < 100; i += 10) {
      p1 = BigInteger.probablePrime(50 + i, rnd);
      p2 = p1.add(ONE);
      p3 = p1.nextProbablePrime();
      while (p2.compareTo(p3) < 0) {
        if (p2.isProbablePrime(100)) {
          System.err.println("nextProbablePrime failed");
          System.err.println("along range " + p1.toString(16));
          System.err.println("to " + p3.toString(16));
          failCount++;
          break;
        }
        p2 = p2.add(ONE);
      }
    }

    report("nextProbablePrime", failCount);
  }
Exemple #25
0
  private double map(String chromossome) {

    BigInteger bi = new BigInteger(chromossome, 2);

    long l = bi.longValue();

    return min + (max - min) * l / Math.pow(2, numOfbits);
  }
 public List<Event> watch(BigInteger lastIndex) {
   // TODO: parameterized or configurable watch time
   long index = -1;
   if (lastIndex != null) {
     index = lastIndex.longValue();
   }
   Response<List<Event>> watch = consul.eventList(new QueryParams(2, index));
   return filterEvents(readEvents(watch), lastIndex);
 }
 public DialogSendResult(Context context, String address, BigInteger btc, BigInteger fee) {
   super(context);
   setContentView(R.layout.dialog_send_result);
   TextView tvAddress = (TextView) findViewById(R.id.tv_address);
   TextView tvBtc = (TextView) findViewById(R.id.tv_btc);
   TextView tvFee = (TextView) findViewById(R.id.tv_fee);
   Button btnClose = (Button) findViewById(R.id.btn_close);
   tvAddress.setText(address);
   tvBtc.setText(GenericUtils.formatValueWithBold(btc.longValue()));
   tvFee.setText(GenericUtils.formatValueWithBold(fee.longValue()));
   btnClose.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           dismiss();
         }
       });
 }
Exemple #28
0
 public static Long fullHashToId(byte[] hash) {
   if (hash == null || hash.length < 8) {
     throw new IllegalArgumentException("Invalid hash: " + Arrays.toString(hash));
   }
   BigInteger bigInteger =
       new BigInteger(
           1, new byte[] {hash[7], hash[6], hash[5], hash[4], hash[3], hash[2], hash[1], hash[0]});
   return bigInteger.longValue();
 }
  @Override
  public AttributedCharacterIterator formatToCharacterIterator(Object object) {
    if (!(object instanceof Number)) {
      throw new IllegalArgumentException();
    }
    Number number = (Number) object;
    String text = null;
    StringBuffer attributes = new StringBuffer();

    if (number instanceof BigInteger) {
      BigInteger valBigInteger = (BigInteger) number;
      if (valBigInteger.compareTo(new BigInteger(String.valueOf(Long.MAX_VALUE))) > 0) {
        throw (new UnsupportedOperationException(
            "Number too big. BigInteger > Long.MAX_VALUE not yet supported."));
      }
      text =
          NativeDecimalFormat.format(this.addr, valBigInteger.longValue(), null, null, attributes);
    } else if (number instanceof BigDecimal) {
      BigDecimal valBigDecimal = (BigDecimal) number;
      if (valBigDecimal.compareTo(new BigDecimal(String.valueOf(Double.MAX_VALUE))) > 0) {
        throw (new UnsupportedOperationException(
            "Number too big. BigDecimal > Double.MAX_VALUE not yet supported."));
      }
      text =
          NativeDecimalFormat.format(
              this.addr, valBigDecimal.doubleValue(), null, null, attributes);
    } else {
      double dv = number.doubleValue();
      long lv = number.longValue();
      if (dv == lv) {
        text = NativeDecimalFormat.format(this.addr, lv, null, null, attributes);
      } else {
        text = NativeDecimalFormat.format(this.addr, dv, null, null, attributes);
      }
    }

    AttributedString as = new AttributedString(text.toString());

    String[] attrs = attributes.toString().split(";");
    // add NumberFormat field attributes to the AttributedString
    int size = attrs.length / 3;
    if (size * 3 != attrs.length) {
      return as.getIterator();
    }
    for (int i = 0; i < size; i++) {
      Format.Field attribute = getField(attrs[3 * i]);
      as.addAttribute(
          attribute,
          attribute,
          Integer.parseInt(attrs[3 * i + 1]),
          Integer.parseInt(attrs[3 * i + 2]));
    }

    // return the CharacterIterator from AttributedString
    return as.getIterator();
  }
 @Test(timeout = 5000L)
 public void powLongIntExact() {
   BigInteger mod = BigUtils.BI_MAX_LONG.add(BigInteger.ONE).shiftLeft(1);
   for (long i : LONGS)
     for (int j : INTS)
       if (j >= 0) {
         BigInteger expected = BigInteger.valueOf(i).modPow(BigInteger.valueOf(j), mod);
         assertEquals(i + " ^ " + j, expected.longValue(), pow(i, j));
       }
 }