Java源码示例:java.util.Random
示例1
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;
}
示例2
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);
}
示例3
/** 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);
}
}
示例4
@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();
}
示例5
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);
}
}
示例6
@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);
}
}
示例7
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 );
} );
}
示例8
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);
}
}
示例9
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;
}
示例10
/**
* 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;
}
示例11
/**
* 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;
}
示例12
@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);
}
示例13
/**
*
* @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;
}
示例14
@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));
}
}
示例15
/**
* 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);
}
}
示例16
@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);
}
示例17
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);
}
示例18
@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);
}
}
}
示例19
/** test that R is upper triangular */
public void testRUpperTriangular() {
RealMatrix matrix = MatrixUtils.createRealMatrix(testData3x3NonSingular);
checkUpperTriangular(new QRDecompositionImpl(matrix).getR());
matrix = MatrixUtils.createRealMatrix(testData3x3Singular);
checkUpperTriangular(new QRDecompositionImpl(matrix).getR());
matrix = MatrixUtils.createRealMatrix(testData3x4);
checkUpperTriangular(new QRDecompositionImpl(matrix).getR());
matrix = MatrixUtils.createRealMatrix(testData4x3);
checkUpperTriangular(new QRDecompositionImpl(matrix).getR());
Random r = new Random(643895747384642l);
int p = (5 * BlockRealMatrix.BLOCK_SIZE) / 4;
int q = (7 * BlockRealMatrix.BLOCK_SIZE) / 4;
matrix = createTestMatrix(r, p, q);
checkUpperTriangular(new QRDecompositionImpl(matrix).getR());
matrix = createTestMatrix(r, p, q);
checkUpperTriangular(new QRDecompositionImpl(matrix).getR());
}
示例20
/**
* Generate a graph with lots of edges and vertices, then test vertex/edge counts on removal of each edge.
*/
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_REMOVE_EDGES)
public void shouldRemoveEdges() {
final int vertexCount = 100;
final int edgeCount = 200;
final List<Vertex> vertices = new ArrayList<>();
final List<Edge> edges = new ArrayList<>();
final Random random = new Random();
IntStream.range(0, vertexCount).forEach(i -> vertices.add(graph.addVertex()));
tryCommit(graph, getAssertVertexEdgeCounts(vertexCount, 0));
IntStream.range(0, edgeCount).forEach(i -> {
boolean created = false;
while (!created) {
final Vertex a = vertices.get(random.nextInt(vertices.size()));
final Vertex b = vertices.get(random.nextInt(vertices.size()));
if (a != b) {
edges.add(a.addEdge(graphProvider.convertLabel("a" + UUID.randomUUID()), b));
created = true;
}
}
});
tryCommit(graph, getAssertVertexEdgeCounts(vertexCount, edgeCount));
int counter = 0;
for (Edge e : edges) {
counter = counter + 1;
e.remove();
final int currentCounter = counter;
tryCommit(graph, getAssertVertexEdgeCounts(vertexCount, edgeCount - currentCounter));
}
}
示例21
/**
* Test that filling up one of the buffers causes us to trigger a flush and
* start using the other buffer, when using PackedBufferManager.
* This also tests that PackedBufferManager can correctly handle a buffer
* getting full.
*/
@Test(timeout = 60000)
public void testFullBufferCausesPackedThreadTrigger() throws Exception {
final Random rand = new Random(321);
final HTracedProcess ht = new HTracedProcess.Builder().build();
try {
HTraceConfiguration conf = HTraceConfiguration.fromMap(
new HashMap<String, String>() {{
put(TracerId.TRACER_ID_KEY,
"testFullBufferCausesPackedThreadTrigger");
put(Conf.ADDRESS_KEY, ht.getHrpcAddr());
put(Conf.PACKED_KEY, "true");
put(Conf.BUFFER_SIZE_KEY, "16384");
put(Conf.BUFFER_SEND_TRIGGER_FRACTION_KEY, "0.95");
}});
TestHandleContentLengthTriggerInjector injector =
new TestHandleContentLengthTriggerInjector();
HTracedSpanReceiver rcvr = new HTracedSpanReceiver(conf, injector);
Span[] spans = TestUtil.randomSpans(rand, 47);
for (Span span : spans) {
rcvr.receiveSpan(span);
}
Assert.assertTrue("The wakePostSpansThread should have been " +
"triggered by the spans added so far. " +
"contentLengthOnTrigger = " + injector.getContentLengthOnTrigger(),
injector.getContentLengthOnTrigger() > 16000);
injector.threadStartSem.release();
rcvr.close();
waitForSpans(ht, spans, 45);
} finally {
ht.destroy();
}
}
示例22
@Test
public void testMixture() throws Exception {
ByteBuf buf = Unpooled.buffer(10000);
ByteBuf derived = buf;
Random rnd = new Random();
for (int i = 0; i < buf.capacity(); i ++) {
ByteBuf newDerived;
switch (rnd.nextInt(4)) {
case 0:
newDerived = derived.slice(1, derived.capacity() - 1);
break;
case 1:
newDerived = derived.duplicate();
break;
case 2:
newDerived = derived.order(
derived.order() == ByteOrder.BIG_ENDIAN ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
break;
case 3:
newDerived = Unpooled.unmodifiableBuffer(derived);
break;
default:
throw new Error();
}
assertThat("nest level of " + newDerived, nestLevel(newDerived), is(lessThanOrEqualTo(3)));
assertThat(
"nest level of " + newDerived.order(ByteOrder.BIG_ENDIAN),
nestLevel(newDerived.order(ByteOrder.BIG_ENDIAN)), is(lessThanOrEqualTo(2)));
derived = newDerived;
}
}
示例23
/**
* Same as java.util.Random.nextBytes except this one we dont have to allocate a new byte array
* @param into byte[]
* @param offset int
* @param length int
* @param r Random
*/
public static void nextBytes(byte[] into, int offset, int length, Random r) {
int numRequested = length;
int numGot = 0, rnd = 0;
while (true) {
for (int i = 0; i < BYTES_PER_INT; i++) {
if (numGot == numRequested) return;
rnd = (i == 0 ? r.nextInt() : rnd >> BITS_PER_BYTE);
into[offset+numGot] = (byte) rnd;
numGot++;
}
}
}
示例24
/**
* description 获取指定位数的随机数
*
* @param length 1
* @return java.lang.String
*/
public static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
示例25
public boolean execute() throws Exception {
Random rdm = new Random();
byte[] plainText=new byte[125];
rdm.nextBytes(plainText);
Cipher ci = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING, "SunJCE");
// TEST FIX 4513830
KeyGenerator kg = KeyGenerator.getInstance(ALGO, "SunJCE");
kg.init(KEYSIZE*8);
SecretKey key = kg.generateKey();
ci.init(Cipher.DECRYPT_MODE, key);
int recoveredTextLength = ci.getOutputSize(16);
if (recoveredTextLength != 16) {
throw new Exception("output size should not increase when decrypting!");
}
// BONUS TESTS
// 1. call getOutputSize with various lengths and see if
// the returned size is correct.
for (int i=0; i<TEXTLENGTHS.length; i++) {
ci.init(Cipher.ENCRYPT_MODE, key);
int cipherTextLength = ci.getOutputSize(TEXTLENGTHS[i]);
if (cipherTextLength != 32) {
throw new Exception("output size " + cipherTextLength
+ " for input size " + TEXTLENGTHS[i]
+ " when encrypting is wrong!");
}
}
// passed all tests...hooray!
return true;
}
示例26
@Test
public void testNumChildrenSize()
{
BitmapFactory bf = new ConciseBitmapFactory();
RTree tree = new RTree(2, new LinearGutmanSplitStrategy(0, 50, bf), bf);
Random rand = new Random();
for (int i = 0; i < 100; i++) {
tree.insert(new float[]{rand.nextFloat(), rand.nextFloat()}, i);
}
Assert.assertTrue(getNumPoints(tree.getRoot()) >= tree.getSize());
}
示例27
/**
* Constructor called only during FJTaskRunnerGroup initialization
**/
protected FJTaskRunner(FJTaskRunnerGroup g) {
group = g;
victimRNG = new Random(System.identityHashCode(this));
runPriority = getPriority();
setDaemon(true);
}
示例28
private void execute() {
Random rand = new Random();
int numRows = matrix.length;
for (int i = 0; i < numMoves; i++) {
int row1 = rand.nextInt(numRows);
int row2 = rand.nextInt(numRows);
while (row1 == row2) {
row2 = rand.nextInt(numRows);
}
swapColumns(row1, row2);
}
}
示例29
@Override
protected Somethingcomposite createWithId() {
Somethingcomposite something = new Somethingcomposite();
something.setSomeid(new Random().nextInt());
something.setSomesecondid(new Random().nextInt());
something.setSomejsonobject(new JsonObject().put("key", "value"));
return something;
}
示例30
protected void genStandardOre(WorldGenMinable gen, WorldGenInfo info, World world, Random random, int x, int z) {
for (int l = 0; l < info.amount; ++l) {
if (random.nextDouble() < info.chance) {
int avgX = x + random.nextInt(16);
int avgY = info.minY + random.nextInt(info.maxY - info.minY) + 1;
int avgZ = z + random.nextInt(16);
gen.generate(world, random, avgX, avgY, avgZ);
}
}
}