Java Code Examples for java.util.Random

The following are top voted examples for showing how to use java.util.Random. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AmenEye   File: SplashActivity.java   Source Code and License 10 votes vote down vote up
private void setImgBackGround() {
    String[] images = getResources().getStringArray(R.array.splash_background);
    int position = new Random().nextInt(images.length - 1) % (images.length);

    Glide.with(this)
            .load(images[position])
            .into(mImgBackGround);

    String path = SpUtil.getString(this, "path");
    Glide.with(this)
            .load(path)
            .asBitmap()
            .error(R.drawable.def_avatar)
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    mCircleImageView.setImageBitmap(resource);
                }
            });

    //设置图像的透明度
    AlphaAnimation animation = new AlphaAnimation(0.1f, 1.0f);
    animation.setDuration(800);
    mCircleImageView.startAnimation(animation);
    animation.setAnimationListener(this);
}
 
Example 2
Project: Technical   File: TechnicalWorldGenerator.java   Source Code and License 7 votes vote down vote up
private void generateSurface(World world, Random random, int startX, int startZ) {
	/*
	 * if(startingX == 0 && startingZ == 0) { startingX = startX; startingZ = startZ; }
	 * 
	 * if((startX > (startingX + 512)) || (startX < (startingX - 512))) { xWasBad = true; return; } else if(xWasBad) { if(!((startX > (startingX + 512)) || (startX < (startingX - 512)))) { FMLLog.log(Level.INFO,
	 * "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); startingX = startX; xWasBad = false; } }
	 * 
	 * if((startZ > (startingZ + 512)) || (startZ < (startingZ - 512))) { zWasBad = true; return; } else if(zWasBad) { if(!((startZ > (startingZ + 512)) || (startZ < (startingZ - 512)))) { FMLLog.log(Level.INFO,
	 * "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); startingZ = startZ; zWasBad = false; } }
	 * 
	 * /* startingX = 0; startingZ = 0;
	 */

	for(int x = startX; x < startX + 16; x++) {
		for(int z = startZ; z < startZ + 16; z++) {
			removeStone(world, random, x, z);
		}
	}
	addOresSurface(world, random, startX, startZ);
}
 
Example 3
Project: jtk   File: AnnotationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testConstructorsAllEqual() {
  Random r = new Random();
  int x = (int)(r.nextFloat()*100);
  int y = (int)(r.nextFloat()*100);
  int z = (int)(r.nextFloat()*100);
  Point3 p = new Point3(x,y,z);

  Annotation[] ans = new Annotation[4];
  ans[0] = new Annotation(x,y,z);
  ans[1] = new Annotation(p);
  ans[2] = new Annotation(x,y,z,"");
  ans[3] = new Annotation(p,"");

  for (int i=0; i<ans.length; ++i) {
    assertEquals(Color.WHITE,ans[i].getColor());
    assertEquals(p,ans[i].getLocation());
    assertEquals("",ans[i].getText());
    assertEquals(Annotation.Alignment.EAST,ans[i].getAlignment());
    assertEquals(
      new Font("SansSerif",Font.PLAIN,18),ans[i].getFont());
  }
}
 
Example 4
Project: CustomWorldGen   File: Particle.java   Source Code and License 6 votes vote down vote up
protected Particle(World worldIn, double posXIn, double posYIn, double posZIn)
{
    this.boundingBox = EMPTY_AABB;
    this.width = 0.6F;
    this.height = 1.8F;
    this.rand = new Random();
    this.particleAlpha = 1.0F;
    this.worldObj = worldIn;
    this.setSize(0.2F, 0.2F);
    this.setPosition(posXIn, posYIn, posZIn);
    this.prevPosX = posXIn;
    this.prevPosY = posYIn;
    this.prevPosZ = posZIn;
    this.particleRed = 1.0F;
    this.particleGreen = 1.0F;
    this.particleBlue = 1.0F;
    this.particleTextureJitterX = this.rand.nextFloat() * 3.0F;
    this.particleTextureJitterY = this.rand.nextFloat() * 3.0F;
    this.particleScale = (this.rand.nextFloat() * 0.5F + 0.5F) * 2.0F;
    this.particleMaxAge = (int)(4.0F / (this.rand.nextFloat() * 0.9F + 0.1F));
    this.particleAge = 0;
    this.canCollide = true;
}
 
Example 5
Project: logistimo-web-service   File: AuthenticationServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String generatePassword(String id) {
  if (id == null || id.isEmpty()) {
    return null;
  }
  String password = null;
  // Take the first 4 letters of id
  if (id.length() <= 4) {
    password = id;
  } else {
    password = id.substring(0, 4);
  }
  // Generate a 3 digit random number
  Random r = new Random();
  r.setSeed(System.currentTimeMillis());
  float f = r.nextFloat();
  password += String.valueOf((int) ((f * 1000.0f) % 1000));
  return password;
}
 
Example 6
Project: BaseClient   File: WorldGenMegaPineTree.java   Source Code and License 6 votes vote down vote up
public void func_180711_a(World worldIn, Random p_180711_2_, BlockPos p_180711_3_)
{
    this.func_175933_b(worldIn, p_180711_3_.west().north());
    this.func_175933_b(worldIn, p_180711_3_.east(2).north());
    this.func_175933_b(worldIn, p_180711_3_.west().south(2));
    this.func_175933_b(worldIn, p_180711_3_.east(2).south(2));

    for (int i = 0; i < 5; ++i)
    {
        int j = p_180711_2_.nextInt(64);
        int k = j % 8;
        int l = j / 8;

        if (k == 0 || k == 7 || l == 0 || l == 7)
        {
            this.func_175933_b(worldIn, p_180711_3_.add(-3 + k, 0, -3 + l));
        }
    }
}
 
Example 7
Project: BaseClient   File: WorldGenBigTree.java   Source Code and License 6 votes vote down vote up
public boolean generate(World worldIn, Random rand, BlockPos position)
{
    this.world = worldIn;
    this.basePos = position;
    this.rand = new Random(rand.nextLong());

    if (this.heightLimit == 0)
    {
        this.heightLimit = 5 + this.rand.nextInt(this.heightLimitLimit);
    }

    if (!this.validTreeLocation())
    {
        return false;
    }
    else
    {
        this.generateLeafNodeList();
        this.generateLeaves();
        this.generateTrunk();
        this.generateLeafNodeBases();
        return true;
    }
}
 
Example 8
Project: openjdk-jdk10   File: JVMStartupRunner.java   Source Code and License 6 votes vote down vote up
/**
 * Returns {@code unscaledSize} value scaled by a random factor from
 * range (1, 2). If {@code unscaledSize} is not 0, then this
 * method will return value that won't be equal to {@code unscaledSize}.
 *
 * @param unscaledSize The value to be scaled.
 * @return {@code unscaledSize} value scaled by a factor from range (1, 2).
 */
private static long scaleCodeHeapSize(long unscaledSize) {
    Random random = Utils.getRandomInstance();

    long scaledSize = unscaledSize;
    while (scaledSize == unscaledSize && unscaledSize != 0) {
        float scale = 1.0f + random.nextFloat();
        scaledSize = (long) Math.ceil(scale * unscaledSize);
    }
    return scaledSize;
}
 
Example 9
Project: ibench   File: SourceFDGenerator.java   Source Code and License 6 votes vote down vote up
@Override
public void generateScenario(MappingScenario scenario,Configuration configuration) throws Exception 
{
	Random _generator = configuration.getRandomGenerator();
	Map<String, Map<String,FD>> fds = new HashMap<String, Map<String,FD>> ();
	
	if (log.isDebugEnabled()) {log.debug("Attempting to Generate Source FDs");};

	// create PK FDs R(A,B,C) if A is key then add A -> B,C
	if (configuration.getParam(ParameterName.PrimaryKeyFDs) == 1) {
		if (log.isDebugEnabled()) {log.debug("Generating PK FDs for those Relations with PKs");};
		generatePKFDs(scenario, fds);
	}

	if (configuration.getParam(Constants.ParameterName.SourceFDPerc) > 0) {
		if (log.isDebugEnabled()) {log.debug("Generating Random FDs as SourceFDPerc > 0");};	
		generateRandomFDs(scenario, configuration, _generator, fds);
	}

}
 
Example 10
Project: BaseClient   File: StructureVillagePieces.java   Source Code and License 6 votes vote down vote up
public boolean addComponentParts(World worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn)
{
    if (this.field_143015_k < 0)
    {
        this.field_143015_k = this.getAverageGroundLevel(worldIn, structureBoundingBoxIn);

        if (this.field_143015_k < 0)
        {
            return true;
        }

        this.boundingBox.offset(0, this.field_143015_k - this.boundingBox.maxY + 4 - 1, 0);
    }

    this.fillWithBlocks(worldIn, structureBoundingBoxIn, 0, 0, 0, 2, 3, 1, Blocks.air.getDefaultState(), Blocks.air.getDefaultState(), false);
    this.setBlockState(worldIn, Blocks.oak_fence.getDefaultState(), 1, 0, 0, structureBoundingBoxIn);
    this.setBlockState(worldIn, Blocks.oak_fence.getDefaultState(), 1, 1, 0, structureBoundingBoxIn);
    this.setBlockState(worldIn, Blocks.oak_fence.getDefaultState(), 1, 2, 0, structureBoundingBoxIn);
    this.setBlockState(worldIn, Blocks.wool.getStateFromMeta(EnumDyeColor.WHITE.getDyeDamage()), 1, 3, 0, structureBoundingBoxIn);
    boolean flag = this.coordBaseMode == EnumFacing.EAST || this.coordBaseMode == EnumFacing.NORTH;
    this.setBlockState(worldIn, Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, this.coordBaseMode.rotateY()), flag ? 2 : 0, 3, 0, structureBoundingBoxIn);
    this.setBlockState(worldIn, Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, this.coordBaseMode), 1, 3, 1, structureBoundingBoxIn);
    this.setBlockState(worldIn, Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, this.coordBaseMode.rotateYCCW()), flag ? 0 : 2, 3, 0, structureBoundingBoxIn);
    this.setBlockState(worldIn, Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, this.coordBaseMode.getOpposite()), 1, 3, -1, structureBoundingBoxIn);
    return true;
}
 
Example 11
Project: morpheus-core   File: SortingTests.java   Source Code and License 6 votes vote down vote up
@Test(dataProvider = "order")
public void testLocalDateRowSortByKeys(boolean ascending, boolean parallel) {
    final Random random = new Random();
    final Array<LocalDate> rowKeys = Range.ofLocalDates("2000-01-01", "2010-01-01").toArray().shuffle(2);
    final Array<String> colKeys = Array.of("A", "B", "C", "D");
    final DataFrame<LocalDate,String> frame = DataFrame.ofDoubles(rowKeys, colKeys).applyDoubles(v -> random.nextDouble());
    frame.out().print();
    final DataFrame<LocalDate,String> sorted = parallel ? frame.rows().parallel().sort(ascending) : frame.rows().sequential().sort(ascending);
    sorted.out().print();
    sorted.rows().forEach(row -> {
        if (row.ordinal() > 0) {
            final LocalDate key0 = sorted.rows().key(row.ordinal()-1);
            final LocalDate key1 = sorted.rows().key(row.ordinal());
            if (ascending) {
                Assert.assertTrue(key0.compareTo(key1) < 0, "Keys are in ascending order");
            } else {
                Assert.assertTrue(key0.compareTo(key1) > 0, "Keys are in descending order");
            }
        }
    });
}
 
Example 12
Project: Proyecto-DASI   File: MazeDecoratorImplementation.java   Source Code and License 6 votes vote down vote up
private void initRNGs()
{
    // Initialise a RNG for this scene:
    long seed = 0;
    if (this.mazeParams.getSeed() == null || this.mazeParams.getSeed().equals("random"))
        seed = System.currentTimeMillis();
    else
        seed = Long.parseLong(this.mazeParams.getSeed());

    this.pathrand = new Random(seed);
    this.blockrand = new Random(seed);

    // Should we initialise a separate RNG for the block types?
    if (this.mazeParams.getMaterialSeed() != null)
    {
        long bseed = 0;
        if (this.mazeParams.getMaterialSeed().equals("random"))
            bseed = System.currentTimeMillis();
        else
            bseed = Long.parseLong(this.mazeParams.getMaterialSeed());
        this.blockrand = new Random(bseed);
    }
}
 
Example 13
Project: devops-cstack   File: VolumeControllerTestIT.java   Source Code and License 6 votes vote down vote up
/**
* Cannot create two volumes with same name
*
* @throws Exception
*/
@Test()
public void createTwoVolumesWithError()
        throws Exception {
    VolumeResource volumeResource = new VolumeResource();

    volumeResource.setName("shared" + new Random().nextInt(100000));
    ResultActions resultActions = createVolume(volumeResource);
    resultActions.andExpect(status().isCreated());
    // Convert the result to pojo
    volumeResource = getVolumeResource(mapper, resultActions);

    // Try to create a second volume but error
    resultActions = createVolume(volumeResource);
    resultActions.andExpect(status().is4xxClientError());

    // delete the volume
    deleteVolume(volumeResource.getId(), HttpStatus.NO_CONTENT);
}
 
Example 14
Project: CustomWorldGen   File: LootTable.java   Source Code and License 6 votes vote down vote up
public void fillInventory(IInventory inventory, Random rand, LootContext context)
{
    List<ItemStack> list = this.generateLootForPools(rand, context);
    List<Integer> list1 = this.getEmptySlotsRandomized(inventory, rand);
    this.shuffleItems(list, list1.size(), rand);

    for (ItemStack itemstack : list)
    {
        if (list1.isEmpty())
        {
            LOGGER.warn("Tried to over-fill a container");
            return;
        }

        if (itemstack == null)
        {
            inventory.setInventorySlotContents(((Integer)list1.remove(list1.size() - 1)).intValue(), (ItemStack)null);
        }
        else
        {
            inventory.setInventorySlotContents(((Integer)list1.remove(list1.size() - 1)).intValue(), itemstack);
        }
    }
}
 
Example 15
Project: hadoop   File: TestDFSPacket.java   Source Code and License 6 votes vote down vote up
@Test
public void testPacket() throws Exception {
  Random r = new Random(12345L);
  byte[] data =  new byte[chunkSize];
  r.nextBytes(data);
  byte[] checksum = new byte[checksumSize];
  r.nextBytes(checksum);

  DataOutputBuffer os =  new DataOutputBuffer(data.length * 2);

  byte[] packetBuf = new byte[data.length * 2];
  DFSPacket p = new DFSPacket(packetBuf, maxChunksPerPacket,
                              0, 0, checksumSize, false);
  p.setSyncBlock(true);
  p.writeData(data, 0, data.length);
  p.writeChecksum(checksum, 0, checksum.length);
  p.writeTo(os);

  //we have set syncBlock to true, so the header has the maximum length
  int headerLen = PacketHeader.PKT_MAX_HEADER_LEN;
  byte[] readBuf = os.getData();

  assertArrayRegionsEqual(readBuf, headerLen, checksum, 0, checksum.length);
  assertArrayRegionsEqual(readBuf, headerLen + checksum.length, data, 0, data.length);

}
 
Example 16
Project: javaide   File: CrazyLoggerService.java   Source Code and License 6 votes vote down vote up
protected void onHandleIntent(Intent intent) {

        log.d("onHandleIntent()");

        while (!kill) {

            try {
                Thread.sleep(INTERVAL);
            } catch (InterruptedException e) {
                log.e(e, "error");
            }
            Date date = new Date();
            log.i("Log message " + date + " " + (date.getTime() % 1000));

            if (new Random().nextInt(100) % 5 == 0) {
                log.i("email: [email protected]");
                log.i("ftp: ftp://website.com:21/");
                log.i("http: https://website.com/");
            }

        }

    }
 
Example 17
Project: BaseClient   File: StructureNetherBridgePieces.java   Source Code and License 6 votes vote down vote up
public Start(Random p_i2059_1_, int p_i2059_2_, int p_i2059_3_)
{
    super(p_i2059_1_, p_i2059_2_, p_i2059_3_);
    this.primaryWeights = Lists.<StructureNetherBridgePieces.PieceWeight>newArrayList();

    for (StructureNetherBridgePieces.PieceWeight structurenetherbridgepieces$pieceweight : StructureNetherBridgePieces.primaryComponents)
    {
        structurenetherbridgepieces$pieceweight.field_78827_c = 0;
        this.primaryWeights.add(structurenetherbridgepieces$pieceweight);
    }

    this.secondaryWeights = Lists.<StructureNetherBridgePieces.PieceWeight>newArrayList();

    for (StructureNetherBridgePieces.PieceWeight structurenetherbridgepieces$pieceweight1 : StructureNetherBridgePieces.secondaryComponents)
    {
        structurenetherbridgepieces$pieceweight1.field_78827_c = 0;
        this.secondaryWeights.add(structurenetherbridgepieces$pieceweight1);
    }
}
 
Example 18
Project: BaseClient   File: WorldGenDeadBush.java   Source Code and License 6 votes vote down vote up
public boolean generate(World worldIn, Random rand, BlockPos position)
{
    Block block;

    while (((block = worldIn.getBlockState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 0)
    {
        position = position.down();
    }

    for (int i = 0; i < 4; ++i)
    {
        BlockPos blockpos = position.add(rand.nextInt(8) - rand.nextInt(8), rand.nextInt(4) - rand.nextInt(4), rand.nextInt(8) - rand.nextInt(8));

        if (worldIn.isAirBlock(blockpos) && Blocks.deadbush.canBlockStay(worldIn, blockpos, Blocks.deadbush.getDefaultState()))
        {
            worldIn.setBlockState(blockpos, Blocks.deadbush.getDefaultState(), 2);
        }
    }

    return true;
}
 
Example 19
Project: openjdk-jdk10   File: SubExactIRepeatTest.java   Source Code and License 6 votes vote down vote up
public static void runTest(Verify.BinaryMethod method) {
    Random rnd = Utils.getRandomInstance();
    for (int i = 0; i < 50000; ++i) {
        int x = Integer.MIN_VALUE + 10;
        int y = Integer.MAX_VALUE - 10 + rnd.nextInt(5);

        int c = rnd.nextInt() / 2;
        int d = rnd.nextInt() / 2;

        int a = catchingExact(x, y, method);

        if (a != 36) {
            throw new RuntimeException("a != 36 : " + a);
        }

        int b = nonExact(c, d, method);
        int n = exact(c, d, method);


        if (n != b) {
            throw new RuntimeException("n != b : " + n + " != " + b);
        }
    }
}
 
Example 20
Project: greycat   File: OffHeapLMatrix.java   Source Code and License 6 votes vote down vote up
@Override
public LMatrix fillWithRandom(long min, long max, long seed) {
    container.lock();
    try {
        final long addr = container.addrByIndex(index);
        if (addr != OffHeapConstants.NULL_PTR) {
            final long nbRows = POffHeapLongArray.get(addr, INDEX_ROWS);
            final long nbColumns = POffHeapLongArray.get(addr, INDEX_COLUMNS);
            final Random rand = new Random();
            rand.setSeed(seed);
            for (int i = 0; i < nbColumns * nbRows; i++) {
                POffHeapLongArray.set(addr, INDEX_OFFSET + i, rand.nextLong() * (max - min) + min);
            }
            container.declareDirty();
        }
    } finally {
        container.unlock();
    }
    return this;
}
 
Example 21
Project: btrace-demo   File: RemoteClass.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    while (true) {
        Random random = new Random();
        execute(random.nextInt(4000));
    }

}
 
Example 22
Project: openjdk-jdk10   File: BigInteger.java   Source Code and License 5 votes vote down vote up
/**
 * Returns {@code true} if this BigInteger is probably prime,
 * {@code false} if it's definitely composite.
 *
 * This method assumes bitLength > 2.
 *
 * @param  certainty a measure of the uncertainty that the caller is
 *         willing to tolerate: if the call returns {@code true}
 *         the probability that this BigInteger is prime exceeds
 *         {@code (1 - 1/2<sup>certainty</sup>)}.  The execution time of
 *         this method is proportional to the value of this parameter.
 * @return {@code true} if this BigInteger is probably prime,
 *         {@code false} if it's definitely composite.
 */
boolean primeToCertainty(int certainty, Random random) {
    int rounds = 0;
    int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;

    // The relationship between the certainty and the number of rounds
    // we perform is given in the draft standard ANSI X9.80, "PRIME
    // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
    int sizeInBits = this.bitLength();
    if (sizeInBits < 100) {
        rounds = 50;
        rounds = n < rounds ? n : rounds;
        return passesMillerRabin(rounds, random);
    }

    if (sizeInBits < 256) {
        rounds = 27;
    } else if (sizeInBits < 512) {
        rounds = 15;
    } else if (sizeInBits < 768) {
        rounds = 8;
    } else if (sizeInBits < 1024) {
        rounds = 4;
    } else {
        rounds = 2;
    }
    rounds = n < rounds ? n : rounds;

    return passesMillerRabin(rounds, random) && passesLucasLehmer();
}
 
Example 23
Project: MTweaks-KernelAdiutorMOD   File: Values.java   Source Code and License 5 votes vote down vote up
public static int getUniqueId(List<Controls.ControlItem> items) {
    Random random = new Random();
    int r = random.nextInt(10000) + 1;
    for (Controls.ControlItem item : items) {
        if (item.getUniqueId() == r) {
            return getUniqueId(items);
        }
    }
    return r;
}
 
Example 24
Project: Proyecto-DASI   File: ClassroomDecoratorImplementation.java   Source Code and License 5 votes vote down vote up
private void drawPuzzle(World world, Random rand, Palette palette)
{
    int doorLocation = this.front + rand.nextInt(this.back - this.front - 4) + 2;
    
    for(int z=this.front; z<this.back; z++){
        for(int y=this.bottom; y<this.top; y++){
            setBlockState(world, new BlockPos(this.x,y,z), palette.wall);
        }    
        
        if((z - this.front - 1) % 2 == 0 && z < this.back - 1){            		
            setBlockState(world, new BlockPos(this.x - 1, this.bottom + ROOM_HEIGHT - 1, z), palette.light, null, Facing.WEST, null);
            setBlockState(world, new BlockPos(this.x + 1, this.bottom + ROOM_HEIGHT - 1, z), palette.light, null, Facing.EAST, null);                		
        }
    }        	
    
    Facing facing = this.getIn() == this.west ? Facing.WEST : Facing.EAST;
    
    setBlockState(world, new BlockPos(this.x, this.bottom, doorLocation), palette.puzzleDoorLower, null, facing, null);
    setBlockState(world, new BlockPos(this.x, this.bottom + 1, doorLocation), palette.puzzleDoorUpper, null, facing, null);
    if(this.hint){
    	setBlockState(world, new BlockPos(this.x, this.bottom - 1, doorLocation), palette.hint);
    	setBlockState(world, new BlockPos(this.x, this.bottom - 1, doorLocation), palette.hint);
    }
    
    Room room = getIn();
    int triggerZ;
    if(rand.nextDouble() < 0.5){
        triggerZ = doorLocation - 1;
    }else{
        triggerZ = doorLocation + 1;
    }
    
    if(room == this.west){
        setBlockState(world, new BlockPos(this.x - 1, this.bottom + 1, triggerZ), palette.trigger, null, Facing.WEST, null);
    }else{
        setBlockState(world, new BlockPos(this.x + 1, this.bottom + 1, triggerZ), palette.trigger, null, Facing.EAST, null);
    } 
}
 
Example 25
Project: CoreX   File: BlockNetherWart.java   Source Code and License 5 votes vote down vote up
@Override
public int onUpdate(int type) {
    if (type == Level.BLOCK_UPDATE_NORMAL) {
        if (this.down().getId() != SOUL_SAND) {
            this.getLevel().useBreakOn(this);
            return Level.BLOCK_UPDATE_NORMAL;
        }
    } else if (type == Level.BLOCK_UPDATE_RANDOM) {
        if (new Random().nextInt(10) == 1) {
            if (this.meta < 0x03) {
                BlockNetherWart block = (BlockNetherWart) this.clone();
                ++block.meta;
                BlockGrowEvent ev = new BlockGrowEvent(this, block);
                Server.getInstance().getPluginManager().callEvent(ev);

                if (!ev.isCancelled()) {
                    this.getLevel().setBlock(this, ev.getNewState(), true, true);
                } else {
                    return Level.BLOCK_UPDATE_RANDOM;
                }
            }
        } else {
            return Level.BLOCK_UPDATE_RANDOM;
        }
    }

    return 0;
}
 
Example 26
Project: java_mooc_fi   File: MainTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSums() {
  int[] taulukoidenPituudet = {0, 1, 2, 3, 4, 5, 10, 20, 100};

  Random random = new Random();
  for (int i = 0; i < taulukoidenPituudet.length; i++) {
    int pituus = taulukoidenPituudet[i];
    int[] taulukko = new int[pituus];
    for (int j = 0; j < taulukko.length; j++) {
      taulukko[j] = random.nextInt(150);
    }
    tarkistaTaulukko(taulukko);
  }
}
 
Example 27
Project: JSiter   File: UserService.java   Source Code and License 5 votes vote down vote up
public Map<String,Object> register(String username, String password){
        Map<String,Object> map = new HashMap<>();
        Random random = new Random();
//        if (StringUtils.isBlank(username)){
//            map.put("msg","用户名不能为空");
//            return map;
//        }
//
//        if (StringUtils.isBlank(password)){
//            map.put("msg","密码不能为空");
//            return map;
//        }

        User u = userDao.selectByUserName(username);
        if (u!=null){
           //  map.put("msg","用户名已经被占用");
            // return map;
        }

        User user = new User();
        user.setUsername(username);
        user.setId(UUID.randomUUID().toString().substring(0,6));

//        String ticket = addLoginTicket(user.getId());
//        map.put("ticket",ticket);
        map.put("user",user);
        return map;
    }
 
Example 28
Project: ditb   File: GoodBadUglyDB.java   Source Code and License 5 votes vote down vote up
private void delay() {
  final Random random = Utils.random();
  double p = random.nextDouble();
  int mod;
  if (p < 0.9) {
    mod = 0;
  } else if (p < 0.99) {
    mod = 1;
  } else if (p < 0.9999) {
    mod = 2;
  } else {
    mod = 3;
  }
  // this will make mod 3 pauses global
  Lock lock = mod == 3 ? DB_ACCESS.writeLock() : DB_ACCESS.readLock();
  if (mod == 3) {
    System.out.println("OUCH");
  }
  lock.lock();
  try {
    final long baseDelayNs = MICROSECONDS.toNanos(delays[mod]);
    final int delayRangeNs = (int) (MICROSECONDS.toNanos(delays[mod + 1]) - baseDelayNs);
    final long delayNs = baseDelayNs + random.nextInt(delayRangeNs);
    final long deadline = System.nanoTime() + delayNs;
    do {
      LockSupport.parkNanos(deadline - System.nanoTime());
    } while (System.nanoTime() < deadline && !Thread.interrupted());
  } finally {
    lock.unlock();
  }

}
 
Example 29
Project: NanoIconPack   File: SimplePageTransformer.java   Source Code and License 5 votes vote down vote up
public SimplePageTransformer(int animType) {
    if (animType == ANIM_RANDOM) {
        int[] animTypes = {ANIM_DEFAULT, ANIM_ZOOM_OUT, ANIM_DEPTH};
        this.animType = animTypes[(new Random()).nextInt(animTypes.length)];
    } else {
        this.animType = animType;
    }
}
 
Example 30
Project: CustomWorldGen   File: StructureStrongholdPieces.java   Source Code and License 5 votes vote down vote up
public StairsStraight(int p_i45572_1_, Random p_i45572_2_, StructureBoundingBox p_i45572_3_, EnumFacing p_i45572_4_)
{
    super(p_i45572_1_);
    this.setCoordBaseMode(p_i45572_4_);
    this.entryDoor = this.getRandomDoor(p_i45572_2_);
    this.boundingBox = p_i45572_3_;
}
 
Example 31
Project: BaseClient   File: StructureStrongholdPieces.java   Source Code and License 5 votes vote down vote up
public void buildComponent(StructureComponent componentIn, List<StructureComponent> listIn, Random rand)
{
    if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.EAST)
    {
        this.getNextComponentX((StructureStrongholdPieces.Stairs2)componentIn, listIn, rand, 1, 1);
    }
    else
    {
        this.getNextComponentZ((StructureStrongholdPieces.Stairs2)componentIn, listIn, rand, 1, 1);
    }
}
 
Example 32
Project: alfresco-repository   File: PropValGenerator.java   Source Code and License 5 votes vote down vote up
@Override
protected Date createValue()
{
    Random rand = new Random();
    Date date = new Date(rand.nextLong());
    // Dates are stored to day precision, make sure we return the
    // same value that will be stored, for comparison in assert statements etc.
    Date truncDate = PropertyDateValueEntity.truncateDate(date);
    return truncDate;
}
 
Example 33
Project: s-store   File: TestSqlAggregateSuite.java   Source Code and License 5 votes vote down vote up
public void testMultipleAverages() throws IOException, ProcCallException {
    String[] tables = {"P1", "R1"};
    
    Random rand = this.getRandom();
    for (String table : tables) {
        Client client = getClient();
        List<Long> val_nums = new ArrayList<Long>();
        List<Double> val_ratios = new ArrayList<Double>();
        
        for (int i = 0; i < ROWS; ++i) {
            BigDecimal cash = new BigDecimal(10.0);
            long num = i / 2;
            double ratio = rand.nextDouble();
            client.callProcedure("Insert", table, i, "desc", cash, num, ratio);
            val_nums.add(num);
            val_ratios.add(ratio);
        } // FOR
        
        double expected_results[] = {
            MathUtil.arithmeticMean(val_nums),
            MathUtil.arithmeticMean(val_ratios),
        };
        String query = String.format("SELECT AVG(NUM), AVG(RATIO) FROM %s", table);
        VoltTable[] results = client.callProcedure("@AdHoc", query).getResults();
        assertEquals(1, results.length);
        assertEquals(1, results[0].getRowCount());
        assertTrue(results[0].advanceRow());
        for (int i = 0; i < expected_results.length; ++i) {
            double val = ((Number)results[0].get(i, results[0].getColumnType(i))).doubleValue();
            assertEquals(table+"."+i, expected_results[i], val, 0.00001);
        } // FOR
    } // FOR
}
 
Example 34
Project: imagingbook-common   File: KMeansClusteringQuantizer.java   Source Code and License 5 votes vote down vote up
/**
 * We randomly pick k distinct colors from the original image
 * pixels.
 * @param pixels
 * @param k
 * @return
 */
private int[] getColorSamples(int[] pixels, int k) {
	switch (params.samplMethod) {
	case Random:
		return getRandomColors(pixels, k);
	case Most_Frequent:
		return getMostFrequentColors(pixels, k);
	default:
		return null;
	}
}
 
Example 35
Project: candlelight   File: WeightedSet.java   Source Code and License 5 votes vote down vote up
public E getRandomWeightedValue(Random rand)
{
	int target = rand.nextInt(this.getTotalWeight());
	int index = 0;
	for(int i = 0; i < this.mapping.size() - 1; ++i)
	{
		index += this.mapping.valueAt(i);
		if (index >= target)
		{
			return this.mapping.keyAt(i);
		}
	}

	return this.mapping.keyAt(this.mapping.size() - 1);
}
 
Example 36
Project: mirrorgate-jenkins-builds-collector   File: MirrorGateListenerHelperTest.java   Source Code and License 5 votes vote down vote up
@Test
public void sendBuildFromItemResponseError() {
    when(service.publishBuildData(any())).thenReturn(responseError);
    when(service.sendBuildDataToExtraEndpoints(any(), any())).thenReturn(responseError);

    Job[] jobs = new Job[new Random().nextInt(10)];
    Arrays.fill(jobs, createMockingJob());

    helper.sendBuildFromItem(createMockingItem(jobs));

    verify(service, times(jobs.length)).publishBuildData(any());
}
 
Example 37
Project: CustomWorldGen   File: StructureNetherBridgePieces.java   Source Code and License 5 votes vote down vote up
public static StructureNetherBridgePieces.Corridor5 createPiece(List<StructureComponent> p_175877_0_, Random p_175877_1_, int p_175877_2_, int p_175877_3_, int p_175877_4_, EnumFacing p_175877_5_, int p_175877_6_)
{
    StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(p_175877_2_, p_175877_3_, p_175877_4_, -1, 0, 0, 5, 7, 5, p_175877_5_);
    /**
     * Checks if the bounding box's minY is > 10
     */
    return isAboveGround(structureboundingbox) && StructureComponent.findIntersecting(p_175877_0_, structureboundingbox) == null ? new StructureNetherBridgePieces.Corridor5(p_175877_6_, p_175877_1_, structureboundingbox, p_175877_5_) : null;
}
 
Example 38
Project: summer17-android   File: Level4.java   Source Code and License 5 votes vote down vote up
public void updateGreen() {
    if (cam.position.x - cam.viewportWidth / 2 > greenCar.getPosObs().x + greenCar.getWidth()) {
        Random rand = new Random();
        float fluctuation = rand.nextFloat();
        float distance = (fluctuation * 1500) + GameTutorial.WIDTH;
        greenCar.reposition(greenCar.getPosObs().x + distance, 35);
    }
}
 
Example 39
Project: minicraft-plus-revived   File: WorldGenMenu.java   Source Code and License 5 votes vote down vote up
public static long getSeed() {
	String seedStr = worldSeed.getUserInput();
	if(seedStr.length() == 0)
		return new Random().nextLong();
	else
		return Long.parseLong(seedStr);
}
 
Example 40
Project: citizensLoader4a   File: RList.java   Source Code and License 5 votes vote down vote up
/**
 * Crea la cadena aleatoria de caracteres para generar la contraseña
 * 
 * @param longitud
 * @return
 */
private String getCadenaAlfanumAleatoria(int longitud) {
	String cadenaAleatoria = "";
	long milis = new java.util.GregorianCalendar().getTimeInMillis();
	Random r = new Random(milis);
	int i = 0;
	while (i < longitud) {
		char c = (char) r.nextInt(255);
		if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')) {
			cadenaAleatoria += c;
			i++;
		}
	}
	return cadenaAleatoria;
}
 
Example 41
Project: hadoop   File: TestFSDownload.java   Source Code and License 5 votes vote down vote up
static LocalResource createTarFile(FileContext files, Path p, int len,
    Random r, LocalResourceVisibility vis) throws IOException,
    URISyntaxException {
  byte[] bytes = new byte[len];
  r.nextBytes(bytes);

  File archiveFile = new File(p.toUri().getPath() + ".tar");
  archiveFile.createNewFile();
  TarArchiveOutputStream out = new TarArchiveOutputStream(
      new FileOutputStream(archiveFile));
  TarArchiveEntry entry = new TarArchiveEntry(p.getName());
  entry.setSize(bytes.length);
  out.putArchiveEntry(entry);
  out.write(bytes);
  out.closeArchiveEntry();
  out.close();

  LocalResource ret = recordFactory.newRecordInstance(LocalResource.class);
  ret.setResource(ConverterUtils.getYarnUrlFromPath(new Path(p.toString()
      + ".tar")));
  ret.setSize(len);
  ret.setType(LocalResourceType.ARCHIVE);
  ret.setVisibility(vis);
  ret.setTimestamp(files.getFileStatus(new Path(p.toString() + ".tar"))
      .getModificationTime());
  return ret;
}
 
Example 42
Project: GitHub   File: TestHelper.java   Source Code and License 5 votes vote down vote up
public static String getRandomString(int length) {
    Random r = new Random();
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
        sb.append((char) (r.nextInt(26) + 'A')); // Restrict to capital letters
    }
    return sb.toString();
}
 
Example 43
Project: fuck_zookeeper   File: ZooKeeperServer.java   Source Code and License 4 votes vote down vote up
byte[] generatePasswd(long id) {
    Random r = new Random(id ^ superSecret);
    byte p[] = new byte[16];
    r.nextBytes(p);
    return p;
}
 
Example 44
Project: googles-monorepo-demo   File: AbstractNonStreamingHashFunctionTest.java   Source Code and License 4 votes vote down vote up
public void testPutStringWithHighSurrogate() {
  // we pad because the dummy hash function we use to test this, merely copies the input into
  // the output, so the input must be at least 32 bits, since the output has to be that long
  assertPutString(new char[] { 'p', HashTestUtils.randomHighSurrogate(new Random()) });
}
 
Example 45
Project: harshencastle   File: PontusFarBiome.java   Source Code and License 4 votes vote down vote up
@Override
public WorldGenAbstractTree getRandomTreeFeature(Random rand) {
	this.decorator.treesPerChunk = 3;
	return new BasePineTreeGenerator(HarshenBlocks.PONTUS_FAR_WOOD, HarshenBlocks.PONTUS_FAR_LEAVES.getDefaultState());
}
 
Example 46
Project: EchoPet   File: EntityPet.java   Source Code and License 4 votes vote down vote up
public Random random(){
	return this.random;
}
 
Example 47
Project: Backmemed   File: StructureNetherBridgePieces.java   Source Code and License 4 votes vote down vote up
public Throne(int p_i45611_1_, Random p_i45611_2_, StructureBoundingBox p_i45611_3_, EnumFacing p_i45611_4_)
{
    super(p_i45611_1_);
    this.setCoordBaseMode(p_i45611_4_);
    this.boundingBox = p_i45611_3_;
}
 
Example 48
Project: GitHub   File: LoockupPerformanceTest.java   Source Code and License 4 votes vote down vote up
public LoockupPerformanceTest() {
    this.random = new Random();
}
 
Example 49
Project: go-jay   File: Utils.java   Source Code and License 4 votes vote down vote up
public static LatLng getRandLocation(LatLng point, int radius) {

        List<LatLng> randomPoints = new ArrayList<>();
        List<Float> randomDistances = new ArrayList<>();
        Location myLocation = new Location("");
        myLocation.setLatitude(point.latitude);
        myLocation.setLongitude(point.longitude);

        //This is to generate 10 random points
        for (int i = 0; i < 10; i++) {
            double x0 = point.latitude;
            double y0 = point.longitude;

            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(y0);

            double foundLatitude = new_x + x0;
            double foundLongitude = y + y0;
            LatLng randomLatLng = new LatLng(foundLatitude, foundLongitude);
            randomPoints.add(randomLatLng);
            Location l1 = new Location("");
            l1.setLatitude(randomLatLng.latitude);
            l1.setLongitude(randomLatLng.longitude);
            randomDistances.add(l1.distanceTo(myLocation));
        }
        //Get nearest point to the centre
        int indexOfNearestPointToCentre = randomDistances.indexOf(Collections.min(randomDistances));
        return randomPoints.get(indexOfNearestPointToCentre);
    }
 
Example 50
Project: jdk8u-jdk   File: LoggingDeadlock2.java   Source Code and License 4 votes vote down vote up
public static void main(String args[]) throws Throwable {
    final CyclicBarrier startingGate = new CyclicBarrier(2);
    final Throwable[] thrown = new Throwable[1];

    // Some random variation, to help tickle races.
    final Random rnd = new Random();
    final boolean dojoin = rnd.nextBoolean();
    final int JITTER = 1024;
    final int iters1 = rnd.nextInt(JITTER);
    final int iters2 = JITTER - iters1;
    final AtomicInteger counter = new AtomicInteger(0);

    Thread exiter = new Thread() {
        public void run() {
            try {
                startingGate.await();
                for (int i = 0; i < iters1; i++)
                    counter.getAndIncrement();
                System.exit(99);
            } catch (Throwable t) {
                t.printStackTrace();
                System.exit(86);
            }
        }};
    exiter.start();

    startingGate.await();
    for (int i = 0; i < iters2; i++)
        counter.getAndIncrement();
    // This may or may not result in a first call to
    // Runtime.addShutdownHook after shutdown has already
    // commenced.
    LogManager.getLogManager();

    if (dojoin) {
        exiter.join();
        if (thrown[0] != null)
            throw new Error(thrown[0]);
        check(counter.get() == JITTER);
    }
}
 
Example 51
Project: firestore-android-arch-components   File: RestaurantUtil.java   Source Code and License 4 votes vote down vote up
private static double getRandomRating(Random random) {
    double min = 1.0;
    return min + (random.nextDouble() * 4.0);
}
 
Example 52
Project: uniquecrops   File: Collis.java   Source Code and License 4 votes vote down vote up
@Override
   public void updateTick(World world, BlockPos pos, IBlockState state, Random rand) {
	
	checkHighplant(world, pos, state, getAge(state));
}
 
Example 53
Project: CustomWorldGen   File: StructureNetherBridgePieces.java   Source Code and License 4 votes vote down vote up
/**
 * Initiates construction of the Structure Component picked, at the current Location of StructGen
 */
public void buildComponent(StructureComponent componentIn, List<StructureComponent> listIn, Random rand)
{
    this.getNextComponentNormal((StructureNetherBridgePieces.Start)componentIn, listIn, rand, 5, 3, true);
    this.getNextComponentNormal((StructureNetherBridgePieces.Start)componentIn, listIn, rand, 5, 11, true);
}
 
Example 54
Project: Backmemed   File: Biome.java   Source Code and License 4 votes vote down vote up
public BlockFlower.EnumFlowerType pickRandomFlower(Random rand, BlockPos pos)
{
    return rand.nextInt(3) > 0 ? BlockFlower.EnumFlowerType.DANDELION : BlockFlower.EnumFlowerType.POPPY;
}
 
Example 55
Project: ProjectAres   File: CuboidRegion.java   Source Code and License 4 votes vote down vote up
private double randomRange(Random random, double min, double max) {
    return (max - min) * random.nextDouble() + min;
}
 
Example 56
Project: GenericGeneticAlgorithm   File: Population.java   Source Code and License 4 votes vote down vote up
/**
 * Get random chromosome
 * 
 * @return C chromosome
 */
public C getRandomChromosome() {
	// TODO improve random generator
	// maybe use pattern strategy
	return this.getChromosomeByIndex(new Random().nextInt(this.chromosomes.size()));
}
 
Example 57
Project: BaseClient   File: StructureOceanMonumentPieces.java   Source Code and License 4 votes vote down vote up
public DoubleYRoom(EnumFacing p_i45595_1_, StructureOceanMonumentPieces.RoomDefinition p_i45595_2_, Random p_i45595_3_)
{
    super(1, p_i45595_1_, p_i45595_2_, 1, 2, 1);
}
 
Example 58
Project: harshencastle   File: PontusEmeraldOre.java   Source Code and License 4 votes vote down vote up
@Override
public int getExpDrop(IBlockState state, IBlockAccess world, BlockPos pos, int fortune) {
	return new Random().nextInt(2) + fortune;
}
 
Example 59
Project: BaseClient   File: StructureNetherBridgePieces.java   Source Code and License 4 votes vote down vote up
public static StructureNetherBridgePieces.Corridor2 func_175876_a(List<StructureComponent> p_175876_0_, Random p_175876_1_, int p_175876_2_, int p_175876_3_, int p_175876_4_, EnumFacing p_175876_5_, int p_175876_6_)
{
    StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(p_175876_2_, p_175876_3_, p_175876_4_, -1, 0, 0, 5, 7, 5, p_175876_5_);
    return isAboveGround(structureboundingbox) && StructureComponent.findIntersecting(p_175876_0_, structureboundingbox) == null ? new StructureNetherBridgePieces.Corridor2(p_175876_6_, p_175876_1_, structureboundingbox, p_175876_5_) : null;
}
 
Example 60
Project: samza-sql-tools   File: RandomValueGenerator.java   Source Code and License 4 votes vote down vote up
public RandomValueGenerator(long seed) {
  rand = new Random(seed);
}