java.util.Random Java Examples

The following examples show how to use java.util.Random. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Tests3x3.java    From Pixelitor with GNU General Public License v3.0 8 votes vote down vote up
public static BufferedImage getRandomImage(boolean withTransparency) {
    BufferedImage img = ImageUtils.createSysCompatibleImage(3, 3);
    Random rand = new Random();
    for (int y = 0; y < 3; y++) {
        for (int x = 0; x < 3; x++) {
            int a;
            if (withTransparency) {
                a = rand.nextInt(256);
            } else {
                a = 255;
            }
            int r = rand.nextInt(256);
            int g = rand.nextInt(256);
            int b = rand.nextInt(256);
            img.setRGB(x, y, ColorUtils.toPackedInt(a, r, g, b));
        }
    }
    return img;
}
 
Example #2
Source File: MLExperimentTester.java    From AILibs with GNU Affero General Public License v3.0 7 votes vote down vote up
@Override
public void evaluate(final ExperimentDBEntry experimentEntry, final IExperimentIntermediateResultProcessor processor) throws ExperimentEvaluationFailedException {
	try {
		if (config.getDatasetFolder() == null || (!config.getDatasetFolder().exists())) {
			throw new IllegalArgumentException("config specifies invalid dataset folder " + config.getDatasetFolder());
		}
		Map<String, String> description = experimentEntry.getExperiment().getValuesOfKeyFields();
		Classifier c = AbstractClassifier.forName(description.get("classifier"), null);
		Instances data = new Instances(new BufferedReader(new FileReader(new File(config.getDatasetFolder() + File.separator + description.get("dataset") + ".arff"))));
		data.setClassIndex(data.numAttributes() - 1);
		int seed = Integer.parseInt(description.get("seed"));

		logger.info("Testing classifier {}", c.getClass().getName());
		Map<String, Object> results = new HashMap<>();

		ILabeledDataset<? extends ILabeledInstance> dataset = new WekaInstances(data);
		SingleRandomSplitClassifierEvaluator eval = new SingleRandomSplitClassifierEvaluator(dataset, .7, new Random(seed));
		double loss = eval.evaluate(new WekaClassifier(c));

		results.put("loss", loss);
		processor.processResults(results);
		this.conductedExperiment = true;
	} catch (Exception e) {
		throw new ExperimentEvaluationFailedException(e);
	}
}
 
Example #3
Source File: Boxing.java    From jdk8u-jdk with GNU General Public License v2.0 7 votes vote down vote up
private void run() {
    Random random = new Random(42); // ensure consistent test domain

    Test proxy = (Test) Proxy.newProxyInstance(
        Test.class.getClassLoader(),
        new Class<?>[] { Test.class },
        new TestHandler());

    for (int rep = 0; rep < REPS; rep++) {
        b = (byte) random.nextInt();
        c = (char) random.nextInt();
        d = random.nextDouble();
        f = random.nextFloat();
        i = random.nextInt();
        j = random.nextLong();
        s = (short) random.nextInt();
        z = random.nextBoolean();
        proxy.m(b,c,d,f,i,j,s,z);
    }
}
 
Example #4
Source File: DocOpGenerator.java    From incubator-retired-wave with Apache License 2.0 7 votes vote down vote up
@Override
public DocOp randomOperation(BootstrapDocument state, final Random random) {
  RandomProvider randomProvider = new RandomProvider() {
    @Override
    public boolean nextBoolean() {
      return random.nextBoolean();
    }

    @Override
    public int nextInt(int upperBound) {
      return random.nextInt(upperBound);
    }
  };
  EvaluatingDocOpCursor<DocOp> builder = new DocOpBuffer();
  RandomDocOpGenerator.generate(randomProvider, new RandomDocOpGenerator.Parameters(),
      state).apply(builder);
  return builder.finish();
}
 
Example #5
Source File: LocationGenerator.java    From Spring-Boot-2.0-Projects with MIT License 7 votes vote down vote up
public static LocationDTO getLocation(double x0, double y0, int radius) {
    Random random = new Random();

    // Convert radius from meters to degrees
    double radiusInDegrees = radius / 111000f;

    double u = random.nextDouble();
    double v = random.nextDouble();
    double w = radiusInDegrees * Math.sqrt(u);
    double t = 2 * Math.PI * v;
    double x = w * Math.cos(t);
    double y = w * Math.sin(t);

    // Adjust the x-coordinate for the shrinking of the east-west distances
    double new_x = x / Math.cos(Math.toRadians(y0));

    double foundLongitude = new_x + x0;
    double foundLatitude = y + y0;

    return new LocationDTO(foundLatitude, foundLongitude, null);
}
 
Example #6
Source File: EigenDecompositionImplTest.java    From astor with GNU General Public License v2.0 7 votes vote down vote up
/** test eigenvalues for a big matrix. */
public void testBigMatrix() {
    Random r = new Random(17748333525117l);
    double[] bigValues = new double[200];
    for (int i = 0; i < bigValues.length; ++i) {
        bigValues[i] = 2 * r.nextDouble() - 1;
    }
    Arrays.sort(bigValues);
    EigenDecomposition ed =
        new EigenDecompositionImpl(createTestMatrix(r, bigValues), MathUtils.SAFE_MIN);
    double[] eigenValues = ed.getRealEigenvalues();
    assertEquals(bigValues.length, eigenValues.length);
    for (int i = 0; i < bigValues.length; ++i) {
        assertEquals(bigValues[bigValues.length - i - 1], eigenValues[i], 2.0e-14);
    }
}
 
Example #7
Source File: SharedFolderWithReadPermissionMoveOutTest.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Test
public void testSynchronizeAddFileAtAMoveOutAtA() throws NoSessionException, NoPeerConnectionException, IOException,
		IllegalArgumentException, IllegalArgumentException, GetFailedException {
	File fileFromAAtA = FileTestUtil.createFileRandomContent("file1FromA", new Random().nextInt(MAX_NUM_CHUNKS) + 1,
			sharedFolderA);
	logger.info("Upload a new file '{}' at A.", fileFromAAtA.toString());
	UseCaseTestUtil.uploadNewFile(nodeA, fileFromAAtA);

	logger.info("Wait till new file '{}' gets synchronized with B.", fileFromAAtA.toString());
	File fileFromAAtB = new File(sharedFolderB, fileFromAAtA.getName());
	waitTillSynchronized(fileFromAAtB, true);

	logger.info("Move file '{}' at A to root folder of A.", fileFromAAtA.toString());
	File movedFileFromAAtA = new File(rootA, fileFromAAtA.getName());
	FileUtils.moveFile(fileFromAAtA, movedFileFromAAtA);
	UseCaseTestUtil.moveFile(nodeA, fileFromAAtA, movedFileFromAAtA);

	logger.info("Wait till moving of file '{}' to '{}' gets synchronized with B.", fileFromAAtA.toString(),
			movedFileFromAAtA.toString());
	waitTillSynchronized(fileFromAAtB, false);
	checkIndexesAfterMoving(fileFromAAtA, fileFromAAtB, movedFileFromAAtA);
}
 
Example #8
Source File: RecordSetUtil.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param seed
 * @param startId
 * @param lines
 * @param columns
 * @param tagLength
 * @return
 */
public static List<IndexedRecord> getRandomRecords(long seed, int startId, int lines, int columns, int tagLength) {

    List<IndexedRecord> generated = new ArrayList<>();
    Random r = new Random(seed);

    for (int id = 0; id < lines; id++) {
        Object[] row = new Object[columns];
        row[0] = startId + id;
        for (int column = 1; column < columns; column++) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < tagLength; i++)
                sb.append(CHARS[r.nextInt(CHARS.length)]);
            row[column] = sb.toString();
        }
        generated.add(GenericDataRecordHelper.createRecord(row));
    }

    return generated;
}
 
Example #9
Source File: TestFrameDecoder.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private static int startRpcServer(boolean allowInsecurePorts) {
  Random rand = new Random();
  int serverPort = 30000 + rand.nextInt(10000);
  int retries = 10;    // A few retries in case initial choice is in use.

  while (true) {
    try {
      RpcProgram program = new TestFrameDecoder.TestRpcProgram("TestRpcProgram",
          "localhost", serverPort, 100000, 1, 2, allowInsecurePorts);
      SimpleTcpServer tcpServer = new SimpleTcpServer(serverPort, program, 1);
      tcpServer.run();
      break;          // Successfully bound a port, break out.
    } catch (ChannelException ce) {
      if (retries-- > 0) {
        serverPort += rand.nextInt(20); // Port in use? Try another.
      } else {
        throw ce;     // Out of retries.
      }
    }
  }
  return serverPort;
}
 
Example #10
Source File: TestCloudJSONFacetSKGEquiv.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * picks a random value for the "overrequest" param, biased in favor of interesting test cases.
 *
 * @return a number to specify in the request, or null to specify nothing (trigger default behavior)
 * @see #UNIQUE_FIELD_VALS
 */
public static Integer randomOverrequestParam(final Random r) {
  switch(r.nextInt(10)) {
    case 0:
    case 1:
    case 2:
    case 3:
      return 0; // 40% of the time, disable overrequest to better stress refinement
    case 4:
    case 5:
      return r.nextInt(UNIQUE_FIELD_VALS); // 20% ask for less them what's needed
    case 6:
      return r.nextInt(Integer.MAX_VALUE); // 10%: completley random value, statisticaly more then enough
    default: break;
  }
  // else.... either leave param unspecified (or redundently specify the -1 default)
  return r.nextBoolean() ? null : -1;
}
 
Example #11
Source File: BigInteger.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find a random number of the specified bitLength that is probably prime.
 * This method is more appropriate for larger bitlengths since it uses
 * a sieve to eliminate most composites before using a more expensive
 * test.
 */
private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
    BigInteger p;
    p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
    p.mag[p.mag.length-1] &= 0xfffffffe;

    // Use a sieve length likely to contain the next prime number
    int searchLen = getPrimeSearchLen(bitLength);
    BitSieve searchSieve = new BitSieve(p, searchLen);
    BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);

    while ((candidate == null) || (candidate.bitLength() != bitLength)) {
        p = p.add(BigInteger.valueOf(2*searchLen));
        if (p.bitLength() != bitLength)
            p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
        p.mag[p.mag.length-1] &= 0xfffffffe;
        searchSieve = new BitSieve(p, searchLen);
        candidate = searchSieve.retrieve(p, certainty, rnd);
    }
    return candidate;
}
 
Example #12
Source File: FreePortFinder.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public static int findFreePort( InetAddress address )
{
    FreePortPredicate check = new FreePortPredicate( address );
    // Randomly choose MAX_PORT_CHECKS ports from the least used ranges
    Range range = LEAST_USED_RANGES.get( new Random().nextInt( LEAST_USED_RANGES.size() ) );
    OptionalInt port = rangeClosed( range.lowerBound, range.higherBound )
        .boxed()
        .collect( collectingAndThen( toList(), collected ->
        {
            collected.removeAll( BLACKLIST );
            shuffle( collected );
            return collected.stream();
        } ) )
        .limit( MAX_PORT_CHECKS )
        .mapToInt( Integer::intValue )
        .filter( check )
        .findFirst();
    return port.orElseThrow( () ->
    {
        IOException exception = new IOException( "Unable to find a free port on " + address );
        check.errors.build().forEach( exception::addSuppressed );
        return new UncheckedIOException( exception );
    } );
}
 
Example #13
Source File: PopulatorRavines.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random) {
    this.random = new Random();
    this.random.setSeed(level.getSeed());
    worldLong1 = this.random.nextLong();
    worldLong2 = this.random.nextLong();

    int i = this.checkAreaSize;

    for (int x = chunkX - i; x <= chunkX + i; x++)
        for (int z = chunkZ - i; z <= chunkZ + i; z++) {
            long l3 = x * worldLong1;
            long l4 = z * worldLong2;
            this.random.setSeed(l3 ^ l4 ^ level.getSeed());
            generateChunk(chunkX, chunkZ, level.getChunk(chunkX, chunkZ));
        }
}
 
Example #14
Source File: ObjGltfAssetCreatorV2.java    From JglTF with MIT License 6 votes vote down vote up
/**
 * Create {@link Material} instances with random colors, and assign 
 * them to the given {@link MeshPrimitive} instances
 * 
 * @param meshPrimitives The {@link MeshPrimitive} instances
 * @param withNormals Whether the {@link MeshPrimitive} instances have
 * normal information
 */
private void assignRandomColorMaterials(
    Iterable<? extends MeshPrimitive> meshPrimitives, boolean withNormals)
{
    Random random = new Random(0);
    for (MeshPrimitive meshPrimitive : meshPrimitives)
    {
        float r = random.nextFloat(); 
        float g = random.nextFloat(); 
        float b = random.nextFloat(); 
        Material material = 
            mtlMaterialHandler.createMaterialWithColor(
                withNormals, r, g, b);
        int materialIndex = Optionals.of(gltf.getMaterials()).size();
        gltf.addMaterials(material);
        meshPrimitive.setMaterial(materialIndex);
    }
}
 
Example #15
Source File: WebSocketDelegateImpl.java    From particle-android with Apache License 2.0 6 votes vote down vote up
@Override
public void processSend(String data) {
    //LOG.entering(CLASS_NAME, "processSend", data);
    ByteBuffer buf = null;
    try {
        buf = ByteBuffer.wrap(data.getBytes("UTF-8"));
    } 
    catch (UnsupportedEncodingException e) {
        // this should not be reached
        String s = "The platform should have already been checked to see if UTF-8 encoding is supported";
        throw new IllegalStateException(s);
    }

    ByteBuffer frame = WsFrameEncodingSupport.rfc6455Encode(new WsMessage(buf, Kind.TEXT), new Random().nextInt());
    send(frame);
    // send(data);
}
 
Example #16
Source File: ParticleSystem.java    From ParticleLayout with Apache License 2.0 6 votes vote down vote up
private ParticleSystem(Activity a, int maxParticles, long timeToLive, int parentResId) {
    mRandom = new Random();
    mParentView = (ViewGroup) a.findViewById(parentResId);

    mModifiers = new ArrayList<ParticleModifier>();
    mInitializers = new ArrayList<ParticleInitializer>();

    mMaxParticles = maxParticles;
    // Create the particles

    mParticles = new ArrayList<Particle>();
    mTimeToLive = timeToLive;

    mParentLocation = new int[2];
    mParentView.getLocationInWindow(mParentLocation);

    DisplayMetrics displayMetrics = a.getResources().getDisplayMetrics();
    mDpToPxScale = (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT);
}
 
Example #17
Source File: FollowingCheckService.java    From droidddle with Apache License 2.0 6 votes vote down vote up
private void notifyNewShots(ArrayList<Shot> shots) {
    if (shots.isEmpty()) {
        return;
    }

    getSharedPreferences().edit().putLong(PREF_LAST_SHOT_ID, shots.get(0).id).apply();

    int size = shots.size();
    // if only one shot, using BigPictureStyle
    // TODO test one notification
    boolean test = false && BuildConfig.DEBUG && new Random().nextBoolean();
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    boolean sound = audio.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
    if (size == 1 || test) {
        postShot(shots.get(0), sound);
    } else {
        //if have more shot, using InboxStyle and wearable pages...
        postShots(shots, sound);

    }

}
 
Example #18
Source File: OrderControllerTest.java    From Mastering-Spring-Cloud with MIT License 5 votes vote down vote up
private void sendAndAcceptOrder() {
	try {
		Random r = new Random();
		Order order = new Order();
		order.setCustomerId((long) r.nextInt(3)+1);
		order.setProductIds(Arrays.asList(new Long[] {(long) r.nextInt(10)+1,(long) r.nextInt(10)+1}));
		order = template.postForObject("http://localhost:8090", order, Order.class);
		if (order.getStatus() != OrderStatus.REJECTED) {
			template.put("http://localhost:8090/{id}", null, order.getId());
		}
	} catch (Exception e) {
		
	}
}
 
Example #19
Source File: GLRenderer.java    From Android-AudioRecorder-App with Apache License 2.0 5 votes vote down vote up
public GLRenderer(@NonNull Context context,
    GLAudioVisualizationView.Configuration configuration) {
  this.configuration = configuration;
  this.random = new Random();
  startTime = System.currentTimeMillis();
  height = context.getResources().getDisplayMetrics().heightPixels;
}
 
Example #20
Source File: WeiXinBaseUtils.java    From roncoo-pay with Apache License 2.0 5 votes vote down vote up
/**
 * 生成随机的字符串
 * 
 * @param length
 * @return
 */
private static String createNoncestr(int length) {
	StringBuilder sb = new StringBuilder();
	Random rd = new Random();
	int clength = chars.length();
	for (int i = 0; i < length; i++) {
		sb.append(chars.charAt(rd.nextInt(clength - 1)));
	}
	return sb.toString();
}
 
Example #21
Source File: RandomUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取 char[] 内的随机数
 * @param chars  随机的数据源
 * @param length 需要最终长度
 * @return 随机字符串
 */
public static String getRandom(final char[] chars, final int length) {
    if (length > 0 && chars != null && chars.length != 0) {
        StringBuilder builder = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            builder.append(chars[random.nextInt(chars.length)]);
        }
        return builder.toString();
    }
    return null;
}
 
Example #22
Source File: DynamicToStaticBNConverter.java    From toolbox with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        DynamicBayesianNetworkGenerator.setNumberOfContinuousVars(0);
        DynamicBayesianNetworkGenerator.setNumberOfDiscreteVars(5);
        DynamicBayesianNetworkGenerator.setNumberOfStates(2);
        DynamicBayesianNetworkGenerator.setNumberOfLinks(5);

        DynamicBayesianNetwork dynamicNaiveBayes = DynamicBayesianNetworkGenerator.generateDynamicNaiveBayes(new Random(0), 2, true);

        System.out.println("ORIGINAL DYNAMIC DAG:");

        System.out.println(dynamicNaiveBayes.getDynamicDAG().toString());
        //System.out.println(dynamicNaiveBayes.toString());
        System.out.println();
        //dynamicNaiveBayes.getDynamicVariables().getListOfDynamicVariables().forEach(var -> System.out.println(var.getName()));
        //dynamicNaiveBayes.getDynamicVariables().getListOfDynamicVariables().forEach(var -> System.out.println(var.getName()));

        BayesianNetwork bn = DynamicToStaticBNConverter.convertDBNtoBN(dynamicNaiveBayes,4);
        System.out.println("NEW STATIC DAG:");
        System.out.println();
        System.out.println(bn.getDAG().toString());

        System.out.println();
        System.out.println("ORIGINAL DYNAMIC BN:");
        System.out.println(dynamicNaiveBayes.toString());

        System.out.println("STATIC BN:");
        System.out.println(bn.toString());
    }
 
Example #23
Source File: BitsTest.java    From jenetics with Apache License 2.0 5 votes vote down vote up
@DataProvider(name = "toLargeIntegerData")
public Iterator<Object[]> toLargeIntegerData() {
	final long seed = System.currentTimeMillis();
	final Random random = new Random(seed);
	final int length = 20;

	return new Iterator<>() {
		private int _pos = 0;

		@Override
		public boolean hasNext() {
			return _pos < length;
		}

		@Override
		public Object[] next() {
			final int size = random.nextInt(1000) + 1;
			final byte[] data = new byte[size];
			random.nextBytes(data);
			_pos += 1;

			return new Object[]{data};
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	};
}
 
Example #24
Source File: ComponentVision.java    From Artifacts with MIT License 5 votes vote down vote up
@Override
public String getPostAdj(Random rand) {
	String str = "";
	switch(rand.nextInt(2)) {
		case 0:
			str = "of Seeing";
			break;
		case 1:
			str = "of Darkvision";
			break;
	}
	return str;
}
 
Example #25
Source File: BayesNetGenerator.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/** 
 * Generate random connected Bayesian network with discrete nodes
 * having all the same cardinality.
 * 
 * @throws Exception if something goes wrong
 */
public void generateRandomNetwork () throws Exception {
	if (m_otherBayesNet == null) {
		// generate from scratch
		Init(m_nNrOfNodes, m_nCardinality);
		generateRandomNetworkStructure(m_nNrOfNodes, m_nNrOfArcs);
		generateRandomDistributions(m_nNrOfNodes, m_nCardinality);
	} else {
		// read from file, just copy parent sets and distributions
		m_nNrOfNodes = m_otherBayesNet.getNrOfNodes();
		m_ParentSets = m_otherBayesNet.getParentSets();
		m_Distributions = m_otherBayesNet.getDistributions();


		random = new Random(m_nSeed);
		// initialize m_Instances
		FastVector attInfo = new FastVector(m_nNrOfNodes);
		// generate value strings

		for (int iNode = 0; iNode < m_nNrOfNodes; iNode++) {
			int nValues = m_otherBayesNet.getCardinality(iNode);
			FastVector nomStrings = new FastVector(nValues + 1);
			for (int iValue = 0; iValue < nValues; iValue++) {
				nomStrings.addElement(m_otherBayesNet.getNodeValue(iNode, iValue));
			}
			Attribute att = new Attribute(m_otherBayesNet.getNodeName(iNode), nomStrings);
			attInfo.addElement(att);
		}

		m_Instances = new Instances(m_otherBayesNet.getName(), attInfo, 100);
		m_Instances.setClassIndex(m_nNrOfNodes - 1);
	}
}
 
Example #26
Source File: BlockMapleSpile.java    From Sakura_mod with MIT License 5 votes vote down vote up
@SideOnly(Side.CLIENT)
@Override
public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) {
	if(canWork(worldIn, pos, stateIn)){
 	if (rand.nextInt(10) == 0) {
         double d0 = pos.getX() + 0.5D;
         double d1 = pos.getY() - 0.15D;
         double d2 = pos.getZ() + 0.5D;
         double d3 = 0D;
         double d4 = ((rand.nextFloat()) * 0.055D) + 0.015D;
         double d5 = 0D;
         SakuraMain.proxy.spawnParticle(SakuraParticleType.SYRUPDROP, d0, d1, d2, d3, -d4, d5);
     }
    }
}
 
Example #27
Source File: ComplexDataClassWithMethodsAndUnique.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
@NonNull
@CheckResult
public static ComplexDataClassWithMethodsAndUnique newRandom() {
  final Random r = new Random();
  return new ComplexDataClassWithMethodsAndUnique(
      r.nextLong(),
      r.nextLong(),
      Utils.randomTableName(),
      SimpleMutableWithUnique.newRandom(),
      SimpleMutableWithUnique.newRandom()
  );
}
 
Example #28
Source File: DrillSqlLineApplication.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public String getInfoMessage() {
  if (config.hasPath(INFO_MESSAGE_TEMPLATE_CONF)) {
    String quote = "";
    if (config.hasPath(QUOTES_CONF)) {
      List<String> quotes = config.getStringList(QUOTES_CONF);
      quote = quotes.get(new Random().nextInt(quotes.size()));
    }
    return String.format(config.getString(INFO_MESSAGE_TEMPLATE_CONF), getVersion(), quote);
  }

  return super.getInfoMessage();
}
 
Example #29
Source File: TestAccounting.java    From XRTB with Apache License 2.0 5 votes vote down vote up
public static String getAdId(Map bid) {
	Random r = new Random();
	int Low = 1;
	int High = 100;
	int k = r.nextInt(High - Low) + Low;
	if (k < 10) {
		return "ben:payday";
	}
	if (k < 50) {
		// return "peter:payday";
	}
	if (k < 80) {
		// return "jim:payday";
		return "ben:payday";
	}
	return "ben:payday";
	// return "ford";
}
 
Example #30
Source File: TestRegressionLearner.java    From tjungblut-online-ml with Apache License 2.0 5 votes vote down vote up
@Test
public void gradCheck() {
  RegressionLearner learner = new RegressionLearner(
      StochasticGradientDescentBuilder.create(0.1).build(),
      new SigmoidActivationFunction(), new LogLoss());
  learner.setRandom(new Random(0));

  // for both classes
  for (int i = 0; i <= 1; i++) {
    gridGradCheck(learner, i, new GradientDescentUpdater());
  }
}