@Test
  public void testAddTradeOrder() {

    try {
      String side = this.tradestrategy.getSide();
      String action = Action.BUY;
      if (Side.SLD.equals(side)) {
        action = Action.SELL;
      }

      double risk = this.tradestrategy.getRiskAmount().doubleValue();

      double stop = 0.20;
      BigDecimal price = new BigDecimal(20);
      int quantity = (int) ((int) risk / stop);
      ZonedDateTime createDate = this.tradestrategy.getTradingday().getOpen().plusMinutes(5);

      TradeOrder tradeOrder =
          new TradeOrder(
              this.tradestrategy,
              action,
              OrderType.STPLMT,
              quantity,
              price,
              price.add(new BigDecimal(0.004)),
              TradingCalendar.getDateTimeNowMarketTimeZone());
      tradeOrder.setOrderKey((new BigDecimal((Math.random() * 1000000))).intValue());
      tradeOrder.setClientId(clientId);
      tradeOrder.setTransmit(true);
      tradeOrder.setStatus("SUBMITTED");
      tradeOrder.validate();
      tradeOrder = tradeOrderHome.persist(tradeOrder);
      assertNotNull("1", tradeOrder);
      _log.info("IdOrder: " + tradeOrder.getIdTradeOrder());

      TradeOrder tradeOrder1 =
          new TradeOrder(
              this.tradestrategy,
              Action.SELL,
              OrderType.STP,
              quantity,
              price.subtract(new BigDecimal(1)),
              null,
              createDate);

      tradeOrder1.setAuxPrice(price.subtract(new BigDecimal(1)));
      tradeOrder1.setOrderKey((new BigDecimal((Math.random() * 1000000))).intValue());
      tradeOrder1.setClientId(clientId);
      tradeOrder1.setTransmit(true);
      tradeOrder1.setStatus("SUBMITTED");
      tradeOrder1.validate();
      tradeOrder1 = tradeOrderHome.persist(tradeOrder1);
      assertNotNull("2", tradeOrder1);
    } catch (Exception | AssertionError ex) {
      String msg = "Error running " + name.getMethodName() + " msg: " + ex.getMessage();
      _log.error(msg);
      fail(msg);
    }
  }
  @Test
  public void testAddDetachedTradeOrder() {
    try {
      String side = this.tradestrategy.getSide();
      String action = Action.BUY;
      if (Side.SLD.equals(side)) {
        action = Action.SELL;
      }

      TradeOrder tradeOrder =
          new TradeOrder(
              this.tradestrategy,
              action,
              OrderType.STPLMT,
              100,
              new BigDecimal(20.20),
              new BigDecimal(20.23),
              TradingCalendar.getDateTimeNowMarketTimeZone());
      tradeOrder.setOrderKey((new BigDecimal((Math.random() * 1000000))).intValue());
      // Save new order with detached trade
      tradeOrder = tradeOrderHome.persist(tradeOrder);
      Execution execution = new Execution();
      execution.m_side = side;
      execution.m_time =
          TradingCalendar.getFormattedDate(
              TradingCalendar.getDateTimeNowMarketTimeZone(), "yyyyMMdd HH:mm:ss");
      execution.m_exchange = "ISLAND";
      execution.m_shares = tradeOrder.getQuantity();
      execution.m_price = tradeOrder.getLimitPrice().doubleValue();
      execution.m_avgPrice = tradeOrder.getLimitPrice().doubleValue();
      execution.m_cumQty = tradeOrder.getQuantity();
      execution.m_execId = "1234";
      TradeOrderfill orderfill = new TradeOrderfill();
      TWSBrokerModel.populateTradeOrderfill(execution, orderfill);
      orderfill.setTradeOrder(tradeOrder);
      tradeOrder.addTradeOrderfill(orderfill);
      // Save a detached order with a new order fill
      tradeOrder = tradeOrderHome.persist(tradeOrder);
      if (action.equals(Action.BUY)) {
        action = Action.SELL;

      } else {
        action = Action.BUY;
      }
      TradeOrder tradeOrder1 =
          new TradeOrder(
              this.tradestrategy,
              action,
              OrderType.LMT,
              300,
              null,
              new BigDecimal(23.41),
              TradingCalendar.getDateTimeNowMarketTimeZone());
      tradeOrder1.setOrderKey((new BigDecimal((Math.random() * 1000000))).intValue());
      tradeOrder1 = tradeOrderHome.persist(tradeOrder1);

      Execution execution1 = new Execution();
      execution1.m_side = side;
      execution1.m_time =
          TradingCalendar.getFormattedDate(
              TradingCalendar.getDateTimeNowMarketTimeZone(), "yyyyMMdd HH:mm:ss");
      execution1.m_exchange = "ISLAND";
      execution1.m_shares = tradeOrder1.getQuantity();
      execution1.m_price = tradeOrder1.getLimitPrice().doubleValue();
      execution1.m_avgPrice = tradeOrder1.getLimitPrice().doubleValue();
      execution1.m_cumQty = tradeOrder1.getQuantity();
      execution1.m_execId = "1234";
      TradeOrderfill orderfill1 = new TradeOrderfill();
      TWSBrokerModel.populateTradeOrderfill(execution1, orderfill1);
      orderfill1.setTradeOrder(tradeOrder1);
      tradeOrder1.addTradeOrderfill(orderfill1);
      tradeOrder1 = tradeOrderHome.persist(tradeOrder1);
    } catch (Exception | AssertionError ex) {
      String msg = "Error running " + name.getMethodName() + " msg: " + ex.getMessage();
      _log.error(msg);
      fail(msg);
    }
  }
Example #3
0
 @Test
 public void bloom() throws Exception {
   ECKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
   ECKey key2 = new ECKey();
   BloomFilter filter =
       group.getBloomFilter(
           group.getBloomFilterElementCount(), 0.001, (long) (Math.random() * Long.MAX_VALUE));
   assertTrue(filter.contains(key1.getPubKeyHash()));
   assertTrue(filter.contains(key1.getPubKey()));
   assertFalse(filter.contains(key2.getPubKey()));
   // Check that the filter contains the lookahead buffer and threshold zone.
   for (int i = 0; i < LOOKAHEAD_SIZE + group.getLookaheadThreshold(); i++) {
     ECKey k = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
     assertTrue(filter.contains(k.getPubKeyHash()));
   }
   // We ran ahead of the lookahead buffer.
   assertFalse(filter.contains(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKey()));
   group.importKeys(key2);
   filter =
       group.getBloomFilter(
           group.getBloomFilterElementCount(), 0.001, (long) (Math.random() * Long.MAX_VALUE));
   assertTrue(filter.contains(key1.getPubKeyHash()));
   assertTrue(filter.contains(key1.getPubKey()));
   assertTrue(filter.contains(key2.getPubKey()));
 }
Example #4
0
 public static void testSet(Matrix m) {
   int rows = m.rows();
   int cols = m.columns();
   for (int trials = 0; trials < 100; ++trials) {
     int i = (int) (rows * Math.random());
     int j = (int) (cols * Math.random());
     double v = Math.random();
     m.set(i, j, v);
     assertEquals(v, m.get(i, j), 0.01);
   }
 }
  /** test of iva method of class CalculateIva */
  @Test
  public void testCalculateIva() {
    CalculateIva calculateIva = Mockito.mock(CalculateIva.class);
    Purchase p = BillingCalculator.calculateTotalPurchase(customer, "EL-003,FU-001");

    when(CalculateIva.iva(p.getCode())).thenReturn(new BigDecimal(Math.random() * 0.05));
  }
  @Test
  public void testMerge() throws LinearCountingMergeException {
    int numToMerge = 5;
    int size = 65536;
    int cardinality = 1000;

    LinearCounting[] lcs = new LinearCounting[numToMerge];
    LinearCounting baseline = new LinearCounting(size);
    for (int i = 0; i < numToMerge; i++) {
      lcs[i] = new LinearCounting(size);
      for (int j = 0; j < cardinality; j++) {
        double val = Math.random();
        lcs[i].offer(val);
        baseline.offer(val);
      }
    }

    int expectedCardinality = numToMerge * cardinality;
    long mergedEstimate = LinearCounting.mergeEstimators(lcs).cardinality();
    double error = Math.abs(mergedEstimate - expectedCardinality) / (double) expectedCardinality;
    assertEquals(0.01, error, 0.01);

    LinearCounting lc = lcs[0];
    lcs = Arrays.asList(lcs).subList(1, lcs.length).toArray(new LinearCounting[0]);
    mergedEstimate = lc.merge(lcs).cardinality();
    error = Math.abs(mergedEstimate - expectedCardinality) / (double) expectedCardinality;
    assertEquals(0.01, error, 0.01);

    long baselineEstimate = baseline.cardinality();
    assertEquals(baselineEstimate, mergedEstimate);
  }
 private double getReferenceTime(int n) {
   final long t0 = System.nanoTime();
   for (int i = 0; i < n * 100; i++) { // Jacobi is less than 100 times slower
     Math.acos(1.0e-5 * Math.random());
   }
   final long t1 = System.nanoTime();
   return (t1 - t0) / 1.0e9;
 }
Example #8
0
 private <T> T randomSelect(List<T> salesList) {
   return salesList.get(
       (int)
           (Math.random()
               * salesList
                   .size())); // To change body of created methods use File | Settings | File
   // Templates.
 }
Example #9
0
  @Test
  public void testSendMessageWithAttachment() throws Exception {
    final String ATTACHMENT_NAME = "boring-attachment.txt";

    // mock smtp server
    Wiser wiser = new Wiser();
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    String emailSubject = "grepster testSendMessageWithAttachment: " + dte;
    String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte;

    ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt");
    // a null from should work
    mailEngine.sendMessage(
        new String[] {"*****@*****.**"}, null, cpResource, emailBody, emailSubject, ATTACHMENT_NAME);

    mailEngine.sendMessage(
        new String[] {"*****@*****.**"},
        mailMessage.getFrom(),
        cpResource,
        emailBody,
        emailSubject,
        ATTACHMENT_NAME);

    wiser.stop();
    // one without and one with from
    assertTrue(wiser.getMessages().size() == 2);

    WiserMessage wm = wiser.getMessages().get(0);
    MimeMessage mm = wm.getMimeMessage();

    Object o = wm.getMimeMessage().getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart multi = (MimeMultipart) o;
    int numOfParts = multi.getCount();

    boolean hasTheAttachment = false;
    for (int i = 0; i < numOfParts; i++) {
      BodyPart bp = multi.getBodyPart(i);
      String disp = bp.getDisposition();
      if (disp == null) { // the body of the email
        Object innerContent = bp.getContent();
        MimeMultipart innerMulti = (MimeMultipart) innerContent;
        assertEquals(emailBody, innerMulti.getBodyPart(0).getContent());
      } else if (disp.equals(Part.ATTACHMENT)) { // the attachment to the email
        hasTheAttachment = true;
        assertEquals(ATTACHMENT_NAME, bp.getFileName());
      } else {
        fail("Did not expect to be able to get here.");
      }
    }
    assertTrue(hasTheAttachment);
    assertEquals(emailSubject, mm.getSubject());
  }
Example #10
0
 private int[] generateRandomSortedArray() {
   int arraySize = (int) (Math.random() * MAX_ARRAY_SIZE);
   int[] r = new int[arraySize];
   int previousMax = Integer.MIN_VALUE;
   for (int i = 0; i < arraySize; i++) {
     r[i] = previousMax = Math.max(previousMax, generateRandomInteger());
   }
   return r;
 }
Example #11
0
  @Test
  public void randomlyChangeTextFields() {
    click4PButton();
    JTextFieldDriver tfDrivers[] = new JTextFieldDriver[12];
    for (int i = 0; i < 4; i++) {
      tfDrivers[i * 3] = text(OptionsMenu.RED_TEXT_FIELD_TITLES[i]);
      tfDrivers[i * 3 + 1] = text(OptionsMenu.GREEN_TEXT_FIELD_TITLES[i]);
      tfDrivers[i * 3 + 2] = text(OptionsMenu.BLUE_TEXT_FIELD_TITLES[i]);
    }

    for (int i = 0; i < 15; i++) {
      int j = (int) (Math.random() * 256);
      int k = (int) (Math.random() * 12);
      tfDrivers[k].focusWithMouse();
      tfDrivers[k].replaceAllText("" + j);
      tfDrivers[k].pressReturn();
    }
  }
Example #12
0
  Map<Long, String> fill(StoreWAL e) {
    Map<Long, String> ret = new LinkedHashMap<Long, String>();

    for (int i = 0; i < 1000; i++) {
      String s = UtilsTest.randomString((int) (Math.random() * 10000));
      long recid = e.put(s, Serializer.STRING);
      ret.put(recid, s);
    }

    return ret;
  }
  // Returns are randomly generated email id, part before the domain name
  private String shuffleEmail(String email) {

    String shuffledString = "";

    while (email.length() != 0) {
      int index = (int) Math.floor(Math.random() * email.length());
      char c = email.charAt(index);
      email = email.substring(0, index) + email.substring(index + 1);
      shuffledString += c;
    }

    return shuffledString;
  }
 @Before
 public void beforetestKsplit() {
   this.data = new ArrayList<double[]>();
   double[] tmp = new double[JIGEN];
   for (int i = 0; i < DATASIZE; i++) {
     tmp = new double[JIGEN];
     for (int j = 0; j < JIGEN; j++) {
       tmp[j] = Math.random();
     }
     data.add(tmp);
     tmp = null;
   }
   this.exa = new HamerlyClustering();
 }
 @Test
 public void calculateDiscountPoints() {
   String productsFlatFile = "EL-002,FU-007,FU-008";
   Purchase result = null;
   result = BillingCalculator.calculateTotalPurchase(customer, productsFlatFile);
   Customer client = Mockito.mock(Customer.class);
   client = result.getCustomer();
   when(client.calculateDiscountPoints())
       .thenReturn(result.getTotalPrice().multiply(new BigDecimal(Math.random() * 0.02)));
   when(client.discountPoints()).thenReturn(true);
   if ((client.getPoints().intValue()) > 1000) {
     client.discountPoints();
   }
 }
  @Test
  public void testChannels() {
    TChronoTimer timer = new TChronoTimer();
    assertTrue(timer.powerOn());

    List<Channel> channels = timer.getChannels();
    assertTrue(channels != null);
    assertTrue(channels.size() == ChronoTimer.MAXIMUM_CHANNELS);
    int i = 1;
    for (Channel c : channels) {
      assertTrue(c != null);
      assertEquals(i, c.getID());
      assertEquals(SensorType.NONE, c.getSensorType());
      assertFalse(c.isEnabled());
      assertTrue(c.enable());
      // Test Channel enable/disable/connect
      for (int j = 0; j < 10; ++j) {
        SensorType s = SensorType.values()[(int) (Math.random() * SensorType.values().length)];
        c.setSensorType(s);
        assertEquals(s, c.getSensorType());
        c.setSensorType(SensorType.NONE);
        assertEquals(SensorType.NONE, c.getSensorType());
        assertTrue(timer.disconnect(i));
        assertFalse(c.isEnabled());
      }
      // Test ChronoTimer connect/disconnect
      for (int j = 0; j < 10; ++j) {
        SensorType s = SensorType.values()[(int) (Math.random() * SensorType.values().length)];
        assertTrue(timer.connect(s, i));
        assertFalse(c.isEnabled());
        assertTrue(c.enable());
        assertTrue(timer.disconnect(i));
      }
      ++i;
    }
  }
  @Test
  public void testString() {

    DB db = DBMaker.memoryDB().make();
    Map m = db.treeMap("test").keySerializer(Serializer.STRING).createOrOpen();

    List<String> list = new ArrayList<String>();
    for (long i = 0; i < 1000; i++) {
      String s = "" + Math.random() + (i * i * i);
      m.put(s, s + "aa");
    }

    for (String s : list) {
      assertEquals(s + "aa", m.get(s));
    }
  }
Example #18
0
  void compact_tx_works(final boolean rollbacks, final boolean pre) throws InterruptedException {
    e = openEngine();
    Map<Long, String> m = fill(e);
    e.commit();

    if (pre) e.$_TEST_HACK_COMPACT_PRE_COMMIT_WAIT = true;
    else e.$_TEST_HACK_COMPACT_POST_COMMIT_WAIT = true;

    Thread t =
        new Thread() {
          @Override
          public void run() {
            e.compact();
          }
        };
    t.start();

    Thread.sleep(1000);

    // we should be able to commit while compaction is running
    for (Long recid : m.keySet()) {
      boolean revert = rollbacks && Math.random() < 0.5;
      e.update(recid, "ZZZ", Serializer.STRING);
      if (revert) {
        e.rollback();
      } else {
        e.commit();
        m.put(recid, "ZZZ");
      }
    }

    if (pre) assertTrue(t.isAlive());

    Thread.sleep(1000);

    e.$_TEST_HACK_COMPACT_PRE_COMMIT_WAIT = false;
    e.$_TEST_HACK_COMPACT_POST_COMMIT_WAIT = false;

    t.join();

    for (Long recid : m.keySet()) {
      assertEquals(m.get(recid), e.get(recid, Serializer.STRING));
    }

    e.close();
  }
Example #19
0
  @Test
  public void testGrafo() {
    for (int i = 0; i < 100000000; i++) {
      Math.random();
    }

    GrafoPredicados grafo = generateStar(10, 10, 8);
    ArrayList<Tuple<Integer, Integer>> aristas = generateAristas(10, 10);
    int cantAristas = aristas.size();

    for (int i = 0; i < cantAristas; i++) {
      for (int j = 0; j < 100; j++) {
        Tuple<Integer, Integer> tuple = aristas.get(0);
        aristas.remove(0);
        grafo.connectMateria(tuple.getX(), tuple.getY());
      }

      double tiempoFinal = 0;
      Ejercicio3 ej;
      int conflictos1 = Integer.MAX_VALUE;
      for (int j = 0; j < 3; j++) {
        ej = new Ejercicio3(grafo);
        double tiempo = System.nanoTime();
        conflictos1 = Math.min(conflictos1, ej.checkColoreoFinal());
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.print(tiempoFinal + ";" + conflictos1 + ";");

      conflictos1 = 0;
      for (int j = 0; j < 3; j++) {
        Ejercicio2 ej2 = new Ejercicio2(grafo);
        double tiempo = System.nanoTime();
        if (ej2.solverWithBacktrack()) {
          conflictos1 = 0;
        } else {
          conflictos1 = 1;
        }
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.print(tiempoFinal + ";" + conflictos1 + ";");

      System.out.println();
    }
  }
Example #20
0
  //	@Test
  public void testEstrella() {
    for (int i = 0; i < 100000000; i++) {
      Math.random();
    }

    for (int i = 0; i < 1000; i++) {
      double tiempoFinal = 0;
      Ejercicio3 ej;
      GrafoPredicados grafo = generateStar(i, i, 100);
      int conflictos1 = Integer.MAX_VALUE;
      for (int j = 0; j < 3; j++) {
        ej = new Ejercicio3(grafo);
        double tiempo = System.nanoTime();
        conflictos1 = Math.min(conflictos1, ej.checkColoreo());
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.println(tiempoFinal + ";" + conflictos1);
    }
  }
Example #21
0
  @Test
  public void testMapPutTtlWithListener() throws InterruptedException {
    Config cfg = new Config();
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
    final HazelcastInstance[] instances = factory.newInstances(cfg);
    warmUpPartitions(instances);

    final int k = 10;
    final int putCount = 10000;
    final CountDownLatch latch = new CountDownLatch(k * putCount);
    final IMap map = instances[0].getMap("testMapEvictionTtlWithListener");

    final AtomicBoolean error = new AtomicBoolean(false);
    final Set<Long> times = Collections.newSetFromMap(new ConcurrentHashMap<Long, Boolean>());

    map.addEntryListener(
        new EntryAdapter() {
          public void entryEvicted(final EntryEvent event) {
            final Long expectedEvictionTime = (Long) (event.getOldValue());
            long timeDifference = System.currentTimeMillis() - expectedEvictionTime;
            if (timeDifference > 5000) {
              error.set(true);
              times.add(timeDifference);
            }
            latch.countDown();
          }
        },
        true);

    for (int i = 0; i < k; i++) {
      final int threadId = i;
      int ttl = (int) (Math.random() * 5000 + 3000);
      for (int j = 0; j < putCount; j++) {
        final long expectedEvictionTime = ttl + System.currentTimeMillis();
        map.put(j + putCount * threadId, expectedEvictionTime, ttl, TimeUnit.MILLISECONDS);
      }
    }

    assertTrue(latch.await(1, TimeUnit.MINUTES));
    assertFalse("Some evictions took more than 3 seconds! -> " + times, error.get());
  }
  @Test
  public void testCalcPerformance() {
    final NNffbpAlphaTabFast tab = loadTestNet();

    final double[] nnInput = new double[] {1.0, 3.4, 6.988, 4.4, 7.0, 16.21};

    final long t1 = System.nanoTime();
    final int N = 100000;
    for (int i = 0; i < N; i++) {
      final double[] doubles = nnInput.clone();
      for (int j = 0; j < doubles.length; j++) {
        doubles[j] += 1.0e-5 * Math.random();
      }
      final double[] nnCalc = tab.calc(doubles);
      assertTrue(nnCalc[0] != 0.0);
    }
    final long t2 = System.nanoTime();
    final double seconds = (t2 - t1) / 1.0e9;
    System.out.println("testCalcPerformance: " + seconds + " seconds");
    assertTrue(seconds < 1.0);
  }
Example #23
0
      @Override
      public void run() {

        for (int i = 0; i < 30; i++) {
          System.err.println("wait");
          // wait a bit randomly
          try {
            Thread.sleep((long) (2000 * Math.random()));
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          // run the model
          System.err.println("run !");
          Map<String, Object> result = runModel();
          checkResult(result);
        }
        // return
        synchronized (threadsToWait) {
          this.threadsToWait.remove(this);
        }
      }
Example #24
0
  @Test
  public void testSend() throws Exception {
    // mock smtp server
    Wiser wiser = new Wiser();
    // set the port to a random value so there's no conflicts between tests
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    this.mailMessage.setTo("*****@*****.**");
    String emailSubject = "grepster testSend: " + dte;
    String emailBody = "Body of the grepster testSend message sent at: " + dte;
    this.mailMessage.setSubject(emailSubject);
    this.mailMessage.setText(emailBody);
    this.mailEngine.send(this.mailMessage);

    wiser.stop();
    assertTrue(wiser.getMessages().size() == 1);
    WiserMessage wm = wiser.getMessages().get(0);
    assertEquals(emailSubject, wm.getMimeMessage().getSubject());
    assertEquals(emailBody, wm.getMimeMessage().getContent());
  }
  @Test
  public void testSingleIntFieldIndex() throws Exception {
    final String INDEX_NAME = "singleIntField";
    IndexManager indexManager = new IndexManager(TEST_UTIL.getConfiguration());

    IndexDefinition indexDef = new IndexDefinition(INDEX_NAME, INDEX_NAME);
    indexDef.addIntegerField("field1");
    indexManager.createIndex(indexDef);
    Index index = indexManager.getIndex(INDEX_NAME, INDEX_NAME);

    final int COUNT = 1000;
    final int MAXVALUE = Integer.MAX_VALUE;
    int[] values = new int[COUNT];

    for (int i = 0; i < COUNT; i++) {
      values[i] = (int) (Math.random() * MAXVALUE);
    }

    for (int value : values) {
      IndexEntry entry = new IndexEntry();
      entry.addField("field1", value);
      index.addEntry(entry, Bytes.toBytes("key" + value));
    }

    Query query = new Query();
    query.setRangeCondition("field1", new Integer(0), new Integer(MAXVALUE));
    QueryResult result = index.performQuery(query);

    Arrays.sort(values);

    for (int value : values) {
      assertEquals("key" + value, Bytes.toString(result.next()));
    }

    assertNull(result.next());
  }
Example #26
0
  @Test
  public void bloomFilterForMarriedChains() throws Exception {
    group = createMarriedKeyChainGroup();
    int bufferSize = group.getLookaheadSize() + group.getLookaheadThreshold();
    int expected = bufferSize * 2 /* chains */ * 2 /* elements */;
    assertEquals(expected, group.getBloomFilterElementCount());
    Address address1 = group.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    assertEquals(expected, group.getBloomFilterElementCount());
    BloomFilter filter =
        group.getBloomFilter(expected + 2, 0.001, (long) (Math.random() * Long.MAX_VALUE));
    assertTrue(filter.contains(address1.getHash160()));

    Address address2 = group.freshAddress(KeyChain.KeyPurpose.CHANGE);
    assertTrue(filter.contains(address2.getHash160()));

    // Check that the filter contains the lookahead buffer.
    for (int i = 0; i < bufferSize - 1 /* issued address */; i++) {
      Address address = group.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
      assertTrue("key " + i, filter.contains(address.getHash160()));
    }
    // We ran ahead of the lookahead buffer.
    assertFalse(
        filter.contains(group.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS).getHash160()));
  }
  @SuppressWarnings({"CallToSystemGC"})
  // deactivated this test; it fails sometimes
  public void testCalcJacobiPerformance() {
    final NNffbpAlphaTabFast tab = loadTestNet();

    final double[] nnInput = new double[] {1.0, 3.4, 6.988, 4.4, 7.0, 16.21};
    System.gc(); // call gc in order to prevent garbage collection during performance test
    final long t1 = System.nanoTime();
    final int N = 100000;
    for (int i = 0; i < N; i++) {
      final double[] doubles = nnInput.clone();
      for (int j = 0; j < doubles.length; j++) {
        doubles[j] += 1.0e-5 * Math.random();
      }
      final NNCalc nnCalc = tab.calcJacobi(doubles);
      assertTrue(nnCalc.getNnOutput()[0] != 0.0);
    }
    final long t2 = System.nanoTime();
    final double duration = (t2 - t1) / 1.0e9;
    // using reference time in order to get rid of a constant time the duration is compared to
    System.gc(); // call gc in order to prevent garbage collection during performance test
    final double refTime = getReferenceTime(N);
    assertTrue(duration < refTime);
  }
Example #28
0
  @Test
  public void testGrafoBipartito() {
    for (int i = 0; i < 100000000; i++) {
      Math.random();
    }

    for (int i = 1; i < 1000; i++) {
      GrafoPredicados grafo = generateBiPartitoCompleto(i, i, 2);

      double tiempoFinal = 0;
      Ejercicio3 ej;
      int conflictos1 = Integer.MAX_VALUE;
      for (int j = 0; j < 3; j++) {
        ej = new Ejercicio3(grafo);
        double tiempo = System.nanoTime();
        conflictos1 = Math.min(conflictos1, ej.checkColoreoFinal());
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.print(tiempoFinal + ";" + conflictos1 + ";");

      conflictos1 = 0;
      for (int j = 0; j < 3; j++) {
        Ejercicio2 ej2 = new Ejercicio2(grafo);
        double tiempo = System.nanoTime();
        if (ej2.solverWithBacktrack()) {
          conflictos1 = 0;
        } else {
          conflictos1 = 1;
        }
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.print(tiempoFinal + ";" + conflictos1 + ";");

      System.out.println();
    }
  }
  /**
   * What these lambda expressions end up being? Lambda expressions can be passed whenever a
   * "functional interface" is wanted.
   *
   * <p>Roughly, a functional interface has exactly one abstract method. More info at
   * https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html &
   * https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
   */
  @Test
  public void functionalInterfaces() {
    List<String> names = Lists.newArrayList("Teuvo", "Ari", "Kristiina");

    // Consumer<T>
    Consumer<String> consumer = name -> System.out.println(name);
    System.out.println("forEach with Consumer");
    names.forEach(consumer);

    // Function<T, R>
    Function<String, Integer> lengthFunction = String::length;
    List<Integer> lengths = names.stream().map(lengthFunction).collect(Collectors.toList());
    assertEquals(Lists.newArrayList(5, 3, 9), lengths);

    // Comparator<T>
    Comparator<String> comparator = String::compareToIgnoreCase;
    String[] array = {"Teuvo", "Ari", "Kristiina"};
    Arrays.sort(array, comparator);
    assertArrayEquals(new String[] {"Ari", "Kristiina", "Teuvo"}, array);

    // Supplier
    Supplier<Double> supplier = () -> Math.random();
    System.out.println("Supplied: " + supplier.get());
  }
  public static int randomNumber() {

    return (int) (Math.random() * 10) + 0;
  }