Java Code Examples for java.util.Random

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project abalone-android, under directory /src/com/bytopia/abalone/mechanics/.

Source file: ArtificialIntilligence.java

  18 
vote

/** 
 * Passes the given arguments and parameters to the evaluation method and returns the best move that an AI have found.
 * @param b board to find the move on
 * @param side side to find a move for
 * @param steps number of steps (depth of analysis)
 * @param aiType clever or stupid
 * @param countNeighbours if true, takes into account neighbouring marbles of every marble
 * @return best move
 */
public Move findNextMove(Board b,byte side,int steps,int aiType,boolean countNeighbours){
  Random r=new Random();
  if (r.nextDouble() > 0.25 || aiType == CLEVER)   evaluatePosition(b,side,steps,Double.NEGATIVE_INFINITY,CLEVER,countNeighbours);
 else   evaluatePosition(b,side,steps,Double.NEGATIVE_INFINITY,STUPID,countNeighbours);
  return bestMove;
}
 

Example 2

From project accesointeligente, under directory /src/org/accesointeligente/server/.

Source file: RandomPassword.java

  18 
vote

public static String getRandomString(int length){
  Random rand=new Random(System.currentTimeMillis());
  StringBuffer sb=new StringBuffer();
  for (int i=0; i < length; i++) {
    int pos=rand.nextInt(charset.length());
    sb.append(charset.charAt(pos));
  }
  return sb.toString();
}
 

Example 3

From project adbcj, under directory /tck/src/test/java/org/adbcj/tck/.

Source file: PopulateLarge.java

  18 
vote

private static String randString(){
  Random rand=new Random();
  StringBuilder sb=new StringBuilder();
  for (int i=0; i < 255; i++) {
    char c=(char)(rand.nextInt(26) + 65);
    sb.append(c);
  }
  return sb.toString();
}
 

Example 4

From project Agot-Java, under directory /src/main/java/got/pojo/.

Source file: GameInfo.java

  18 
vote

public void shuffleWestorsDeckI(){
  for (  WesterosDeckI card : WesterosDeckI.values()) {
    for (int i=0; i < card.getCardNum(); i++) {
      shuffledWesterosDeckI.add(card);
    }
  }
  Random rand=new Random(System.currentTimeMillis());
  Collections.shuffle(shuffledWesterosDeckI,rand);
}
 

Example 5

From project alg-vis, under directory /src/algvis/core/.

Source file: WordGenerator.java

  18 
vote

public static String getABWord(int n){
  Random r=WordGenerator.getInstance().getGenerator();
  StringBuilder s=new StringBuilder("");
  for (int i=0; i < n; ++i) {
    if (r.nextBoolean())     s.append("A");
 else     s.append("B");
  }
  s.append("$");
  return s.toString();
}
 

Example 6

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/entity/mime/.

Source file: MultipartEntity.java

  18 
vote

protected String generateBoundary(){
  StringBuilder buffer=new StringBuilder();
  Random rand=new Random();
  int count=rand.nextInt(11) + 30;
  for (int i=0; i < count; i++) {
    buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
  }
  return buffer.toString();
}
 

Example 7

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/util/.

Source file: StringUtil.java

  18 
vote

public static String getRandomString(int size){
  Random random=new Random();
  StringBuffer sb=new StringBuffer(size);
  for (int i=0; i < size; i++) {
    sb.append(c[Math.abs(random.nextInt()) % c.length]);
  }
  return sb.toString();
}
 

Example 8

From project android-api_1, under directory /android-lib/src/com/android/http/multipart/.

Source file: MultipartEntity.java

  18 
vote

/** 
 * Generates a random multipart boundary string.
 */
private static byte[] generateMultipartBoundary(){
  Random rand=new Random();
  byte[] bytes=new byte[rand.nextInt(11) + 30];
  for (int i=0; i < bytes.length; i++) {
    bytes[i]=MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)];
  }
  return bytes;
}
 

Example 9

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: SimpleMultipartEntity.java

  18 
vote

public SimpleMultipartEntity(){
  final StringBuffer buf=new StringBuffer();
  final Random rand=new Random();
  for (int i=0; i < 30; i++) {
    buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
  }
  this.boundary=buf.toString();
}
 

Example 10

From project android-shuffle, under directory /server/src/org/dodgybits/shuffle/web/server/service/.

Source file: TaskServiceImpl.java

  18 
vote

private TaskValue createRandomAction(){
  Random rnd=new Random();
  String title=titles[rnd.nextInt(titles.length)];
  String description=descriptions[rnd.nextInt(descriptions.length)];
  int dayOffset=rnd.nextInt(11) - 5;
  Date dueDate=new Date(System.currentTimeMillis() + MILLIS_IN_DAY * dayOffset);
  return new TaskValue(null,"XX" + title,description,null,null,dueDate);
}
 

Example 11

From project androidpn, under directory /androidpn-server-bin-tomcat/src/org/androidpn/server/xmpp/push/.

Source file: NotificationManager.java

  18 
vote

/** 
 * Creates a new notification IQ and returns it.
 */
private IQ createNotificationIQ(String apiKey,String title,String message,String uri){
  Random random=new Random();
  String id=Integer.toHexString(random.nextInt());
  Element notification=DocumentHelper.createElement(QName.get("notification",NOTIFICATION_NAMESPACE));
  notification.addElement("id").setText(id);
  notification.addElement("apiKey").setText(apiKey);
  notification.addElement("title").setText(title);
  notification.addElement("message").setText(message);
  notification.addElement("uri").setText(uri);
  IQ iq=new IQ();
  iq.setType(IQ.Type.set);
  iq.setChildElement(notification);
  return iq;
}
 

Example 12

From project android_packages_apps_Gallery2, under directory /tests/src/com/android/gallery3d/common/.

Source file: BlobCacheTest.java

  18 
vote

@LargeTest public void testSmallSize() throws IOException {
  BlobCache bc=new BlobCache(TEST_FILE_NAME,MAX_ENTRIES,40,true);
  Random rand=new Random(0);
  for (int i=0; i < 100; i++) {
    byte[] data=new byte[rand.nextInt(3)];
    bc.insert(rand.nextLong(),data);
  }
  bc.close();
}
 

Example 13

From project apjp, under directory /APJP_KEY_JAVA/src/main/java/APJP/.

Source file: Main.java

  18 
vote

public static void main(String[] args){
  Random random=new Random();
  String buffer="";
  for (int i=0; i < 16; i=i + 1) {
    int j=random.nextInt(61);
    buffer=buffer + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".substring(j,j + 1);
  }
  System.out.println("APJP_KEY=" + buffer);
}
 

Example 14

From project aranea, under directory /admin-api/src/main/java/no/dusken/aranea/util/.

Source file: PasswordGenerator.java

  18 
vote

/** 
 * Generates a String containing a-z, A-Z, 0-9, +, -, @
 * @param length
 * @return String containing a-z, A-Z, 0-9, +, -, @
 */
public static String generatePassword(int length){
  char[] goodChar={'a','b','c','d','e','f','g','h','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','J','K','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','2','3','4','5','6','7','8','9','+','-','@'};
  Random r=new java.util.Random();
  StringBuffer sb=new StringBuffer();
  for (int i=0; i < length; i++) {
    sb.append(goodChar[r.nextInt(goodChar.length)]);
  }
  return sb.toString();
}
 

Example 15

From project ATHENA, under directory /core/apa/src/test/java/org/fracturedatlas/athena/apa/.

Source file: ApaAdapterIndexSearchTest.java

  18 
vote

private void addFishermen(int howMany){
  Random r=new Random();
  String alphabet="1234567890qwertyuioplkjhgfddsazxcvbnmMNBVCXZASDFGHJKLPOIUYTREWQ";
  for (int i=0; i < howMany; i++) {
    addRecord("person","firstName",Character.toString(alphabet.charAt(r.nextInt(alphabet.length()))),"occupation","fisherman");
  }
}
 

Example 16

From project AuthDB, under directory /src/main/java/com/authdb/util/.

Source file: Util.java

  18 
vote

public static String getRandomString(int length){
  String charset="0123456789abcdefghijklmnopqrstuvwxyz";
  Random rand=new Random(System.currentTimeMillis());
  StringBuffer sb=new StringBuffer();
  for (int i=0; i < length; i++) {
    int pos=rand.nextInt(charset.length());
    sb.append(charset.charAt(pos));
  }
  return sb.toString();
}
 

Example 17

From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/.

Source file: Utils.java

  18 
vote

private String generateToken(){
  Random rnd=new Random();
  char[] arr=new char[5];
  for (int i=0; i < 5; i++) {
    int n=rnd.nextInt(36);
    arr[i]=(char)(n < 10 ? '0' + n : 'a' + n - 10);
  }
  return new String(arr);
}
 

Example 18

From project avro, under directory /lang/java/avro/src/test/java/org/apache/avro/io/.

Source file: Perf.java

  18 
vote

@Override void genSourceData(){
  Random r=newRandom();
  sourceData=new int[count];
  for (int i=0; i < sourceData.length; i+=4) {
    sourceData[i]=r.nextInt(50);
    sourceData[i + 1]=r.nextInt(5000);
    sourceData[i + 2]=r.nextInt(500000);
    sourceData[i + 3]=r.nextInt(150000000);
  }
}
 

Example 19

From project babel, under directory /src/babel/util/jerboa/.

Source file: LSH.java

  18 
vote

public LSH(){
  try {
    m_hashes=Hash.getRandomHashes(NUM_BITS);
    m_pool=new double[POOL_SIZE];
    Random random=new Random();
    for (int i=0; i < m_pool.length; i++) {
      m_pool[i]=random.nextGaussian();
    }
  }
 catch (  Exception e) {
    m_hashes=null;
    LOG.error("Failed to instantiate class",e);
  }
}
 

Example 20

From project bam, under directory /samples/jbossas/activityclient/src/main/java/org/overlord/bam/samples/jbossas/activityclient/.

Source file: ActivityClient.java

  18 
vote

/** 
 * This method performs a random series of business transactions.
 */
public void scheduleTxns(int num){
  Random rand=new Random(System.currentTimeMillis());
  int count=0;
  while (num == -1 || count < num) {
    int pos=Math.abs(rand.nextInt()) % _txnList.size();
    String txnName=_txnList.get(pos);
    send(txnName);
    count++;
  }
}
 

Example 21

From project Battlepath, under directory /src/engine/.

Source file: Field.java

  18 
vote

/** 
 * Creates a circle of value 1 tiles in a field
 * @param pos world position of the circle
 * @param r radius of the circle
 */
public void createCircle(Vector2D pos,double r){
  Point topleft=tileIndexAt(new Vector2D(pos.x - r,pos.y - r));
  Point bottomright=tileIndexAt(new Vector2D(pos.x + r,pos.y + r));
  clamp(topleft);
  clamp(bottomright);
  for (int x=topleft.x; x < bottomright.x; x++) {
    for (int y=topleft.y; y < bottomright.y; y++) {
      Random rand=new Random();
      if (pos.distance(getWorldPos(new Point(x,y))) < r)       tiles[x][y].setValue(1);
    }
  }
}
 

Example 22

From project beam-meris-icol, under directory /src/main/java/org/esa/beam/meris/icol/.

Source file: CoeffW.java

  18 
vote

/** 
 * Creates an array of the specified size, containing some random data
 */
public static double[] createRandomDoubleData(int x,double stdev){
  Random random=new Random(0);
  double a[]=new double[x];
  for (int i=0; i < x; i++) {
    a[i]=stdev * random.nextGaussian();
  }
  return a;
}
 

Example 23

From project BHT-FPA, under directory /template-codebeispiele/de.bht.fpa.mail.s000000.templates.tableviewerbuilder/src/de/bht/fpa/mail/s000000/templates/tableviewerbuilder/.

Source file: RandomData.java

  18 
vote

public String someDigits(int count){
  StringBuilder string=new StringBuilder();
  Random random=new Random(seed);
  for (int i=1; i <= count; i++) {
    string.append(String.valueOf(random.nextInt(NR_DIGITS_SOME)));
  }
  return string.toString();
}
 

Example 24

From project Binaural-Beats, under directory /src/com/ihunda/android/binauralbeat/viz/.

Source file: Flash.java

  18 
vote

public void redraw(Canvas c,int width,int height,float now,float totalTime){
  float ratio;
  float dperiod=period * 2;
  ratio=(now % dperiod) / dperiod;
  if (ratio < 0.8)   c.drawColor(COLOR_BG);
 else {
    Random r=new Random();
    if (r.nextBoolean())     c.drawColor(COLOR_FLASH1);
 else     c.drawColor(COLOR_FLASH2);
  }
}
 

Example 25

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.

Source file: BlameSubversionSCM.java

  18 
vote

/** 
 * @param keyFile stores SSH private key. The file will be copied.
 */
public SshPublicKeyCredential(String userName,String passphrase,File keyFile) throws SVNException {
  this.userName=userName;
  this.passphrase=Scrambler.scramble(passphrase);
  Random r=new Random();
  StringBuilder buf=new StringBuilder();
  for (int i=0; i < 16; i++)   buf.append(Integer.toHexString(r.nextInt(16)));
  this.id=buf.toString();
  try {
    FileUtils.copyFile(keyFile,getKeyFile());
  }
 catch (  IOException e) {
    throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to save private key"),e);
  }
}
 

Example 26

From project blogs, under directory /wicket6-native-websockets/src/main/java/com/wicketinaction/charts/.

Source file: WebSocketChart.java

  18 
vote

/** 
 * Generates some random data to send to the client
 * @return records with random data
 */
private Record[] generateData(){
  Random randomGenerator=new Random();
  Record[] data=new Record[1000];
  for (int i=0; i < 1000; i++) {
    Record r=new Record();
    r.year=2000 + i;
    r.field=(i % 2 == 0) ? "Company 1" : "Company 2";
    r.value=randomGenerator.nextInt(1500);
    data[i]=r;
  }
  return data;
}
 

Example 27

From project BombusLime, under directory /src/org/bombusim/sasl/.

Source file: SASL_DigestMD5.java

  18 
vote

@Override public String response(String challenge){
  int nonceIndex=challenge.indexOf("nonce=");
  if (nonceIndex >= 0) {
    nonceIndex+=7;
    String nonce=challenge.substring(nonceIndex,challenge.indexOf('\"',nonceIndex));
    Random rnd=new Random(System.currentTimeMillis());
    String cnonce="Lime" + rnd.nextLong();
    String username=jid.getUser();
    String server=jid.getServer();
    return responseMd5Digest(username,password,server,"xmpp/" + server,nonce,cnonce);
  }
  if (challenge.contains(resp3))   serverAuthenticated=true;
  return "";
}
 

Example 28

From project BookingRoom, under directory /src/org/androidaalto/bookingroom/logic/.

Source file: MeetingManager.java

  18 
vote

private static int generatePin(){
  Random rand=new Random();
  int r=rand.nextInt(9000) + 1000;
  Log.d(TAG,"My rand " + r);
  return r;
}
 

Example 29

From project candlepin, under directory /src/test/java/org/candlepin/policy/js/compliance/.

Source file: ComplianceRulesTest.java

  18 
vote

private Entitlement mockStackedEntitlement(Consumer consumer,String stackId,String productId,String... providedProductIds){
  Entitlement e=mockEntitlement(consumer,productId,providedProductIds);
  Random gen=new Random();
  int id=gen.nextInt(Integer.MAX_VALUE);
  e.setId(String.valueOf(id));
  Pool p=e.getPool();
  p.addProductAttribute(new ProductPoolAttribute("stacking_id",stackId,productId));
  p.addProductAttribute(new ProductPoolAttribute("sockets","2",productId));
  return e;
}
 

Example 30

From project ChessCraft, under directory /src/main/java/fr/free/jchecs/core/.

Source file: MoveGeneratorTest.java

  18 
vote

/** 
 * Joue une partie.
 */
@Override public void run(){
  final Random randomizer=new Random(1000);
  MoveGenerator etat=BoardFactory.valueOf(_type,BoardFactory.State.STARTING);
  for (int cps=50; cps >= 0; cps--) {
    final Move[] mvts=etat.getValidMoves(etat.isWhiteActive());
    final int nbMvts=mvts.length;
    if (nbMvts == 0) {
      break;
    }
    etat=etat.derive(mvts[randomizer.nextInt(nbMvts)],true);
  }
  _ok=true;
}
 

Example 31

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/util/.

Source file: ConstRateAdaptor.java

  18 
vote

public ChunkImpl nextChunk(int arraySize){
  byte[] data=new byte[arraySize];
  Random dataPattern=new Random(offset ^ seed);
  long s=this.seed;
  offset+=data.length;
  dataPattern.nextBytes(data);
  for (int i=0; i < 8; ++i) {
    data[7 - i]=(byte)(s & 0xFF);
    s>>=8;
  }
  ChunkImpl evt=new ChunkImpl(type,"random (" + this.seed + ")",offset,data,this);
  return evt;
}
 

Example 32

From project ciel-java, under directory /examples/kmeans/src/java/skywriting/examples/kmeans/.

Source file: KMeansDataGenerator.java

  18 
vote

@Override public void invoke() throws Exception {
  double minValue=-1000000.0;
  double maxValue=1000000.0;
  WritableReference out=Ciel.RPC.getOutputFilename(0);
  DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(out.open(),1048576));
  Random rand=new Random(this.seed);
  for (int i=0; i < this.numVectors; ++i) {
    for (int j=0; j < this.numDimensions; ++j) {
      dos.writeDouble((rand.nextDouble() * (maxValue - minValue)) + minValue);
    }
  }
  dos.close();
}
 

Example 33

From project cipango, under directory /cipango-sip/src/main/java/org/cipango/sip/labs/.

Source file: HexString.java

  18 
vote

public static void main(String[] args){
  byte[] b=new byte[16];
  Random random=new Random();
  random.nextBytes(b);
  System.out.println(HexString.toHexString(b));
  System.out.println(TypeUtil.toString(b,16));
}
 

Example 34

From project cleo, under directory /src/examples/java/cleo/examples/.

Source file: MyFriendsTypeahead.java

  18 
vote

/** 
 * Indexes a number of typeahead elements that represent people.
 * @param elemIndexer - the element indexer
 * @throws Exception
 */
public static void indexElements(Indexer<TypeaheadElement> elemIndexer) throws Exception {
  Random rand=new Random();
  elemIndexer.index(createElement(5,new String[]{"jay","kaspers"},"J Kaspers","Senior Software Engineer","/photos/00000005.png",rand.nextFloat()));
  elemIndexer.index(createElement(29,new String[]{"peter","smith"},"Peter Smith","Product Manager","/photos/00000029.png",rand.nextFloat()));
  elemIndexer.index(createElement(167,new String[]{"steve","jobs"},"Steve Jobs","Apple CEO","/photos/00000167.png",rand.nextFloat()));
  elemIndexer.index(createElement(1007,new String[]{"ken","miller"},"Ken Miller","Micro Blogging","/photos/00001007.png",rand.nextFloat()));
  elemIndexer.index(createElement(2007,new String[]{"kay","moore"},"Kay Moore","","/photos/00002007.png",rand.nextFloat()));
  elemIndexer.index(createElement(180208,new String[]{"snow","white"},"Snow White","Princess","/photos/00180208.png",rand.nextFloat()));
  elemIndexer.index(createElement(119205,new String[]{"richard","jackson"},"Richard Jackson","Engineering Director","/photos/00119205.png",rand.nextFloat()));
  elemIndexer.flush();
}
 

Example 35

From project Cloud9, under directory /src/test/edu/umd/cloud9/io/benchmark/.

Source file: GenerateRandomPairsOfInts.java

  18 
vote

/** 
 * Runs this program.
 */
public static void main(String[] args) throws Exception {
  Random r=new Random();
  Configuration conf=new Configuration();
  FileSystem fs=FileSystem.get(conf);
  SequenceFile.Writer writer=SequenceFile.createWriter(fs,conf,new Path("random-pairs.seq"),PairOfInts.class,IntWritable.class);
  IntWritable n=new IntWritable();
  PairOfInts pair=new PairOfInts();
  for (int i=0; i < 1000000; i++) {
    n.set(i);
    pair.set(r.nextInt(1000),r.nextInt(1000));
    writer.append(pair,n);
  }
  writer.close();
}
 

Example 36

From project AdminCmd, under directory /src/main/java/be/Balor/Manager/Commands/Player/.

Source file: Roll.java

  17 
vote

@Override public void execute(final CommandSender sender,final CommandArgs args) throws ActionNotPermitedException, PlayerNotFound {
  int dice=6;
  if (args.length >= 1) {
    try {
      dice=args.getInt(0);
    }
 catch (    final NumberFormatException e) {
    }
  }
  final Random rand=new Random();
  if (dice < 1) {
    dice=rand.nextInt(19) + 1;
  }
  final HashMap<String,String> replace=new HashMap<String,String>();
  replace.put("face",String.valueOf(dice));
  if (Utils.isPlayer(sender,false)) {
    replace.put("player",Utils.getPlayerName((Player)sender));
  }
 else {
    replace.put("player","Server Admin");
  }
  replace.put("result",String.valueOf(rand.nextInt(dice) + 1));
  Utils.broadcastMessage(Utils.I18n("roll",replace));
}
 

Example 37

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.

Source file: DataManagement.java

  17 
vote

private static String anonymiseNote(List<String> capitalisedWords,String note){
  String[] alphabet={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
  Pattern numeralPattern=Pattern.compile("[123456789]");
  Pattern capitalWordsPattern=Pattern.compile("[A-Z][a-z0-9]+");
  String newNote=note;
  Matcher capitalWordMatcher=capitalWordsPattern.matcher(note);
  Random randomGenerator=new Random();
  while (capitalWordMatcher.find()) {
    int capitalWordIndex=randomGenerator.nextInt(capitalisedWords.size());
    String capitalWord=capitalisedWords.get(capitalWordIndex);
    newNote=newNote.replace(capitalWordMatcher.group(),capitalWord);
  }
  Matcher numeralMatcher=numeralPattern.matcher(newNote);
  char[] keyChars=newNote.toCharArray();
  while (numeralMatcher.find()) {
    int position=numeralMatcher.start();
    keyChars[position]=alphabet[randomGenerator.nextInt(26)].charAt(0);
  }
  return String.valueOf(keyChars);
}
 

Example 38

From project agraph-java-client, under directory /src/test/stress/.

Source file: TransactionStressTest.java

  17 
vote

public Worker(int from1,int to1){
  from=from1;
  to=to1;
  rnd=new Random(from1);
  rnd.nextInt();
}
 

Example 39

From project airlift, under directory /stats/src/test/java/io/airlift/stats/.

Source file: BenchmarkQuantileDigest.java

  17 
vote

public static void main(String[] args) throws Exception {
  Duration warmupTime=new Duration(3,TimeUnit.SECONDS);
  Duration benchmarkTime=new Duration(5,TimeUnit.SECONDS);
  final QuantileDigest digest=new QuantileDigest(0.01,0,new TestingTicker(),true);
  final Random random=new Random();
  Benchmark.Results results=Benchmark.run(new Runnable(){
    public void run(){
      digest.add(Math.abs(random.nextInt(100000)));
    }
  }
,warmupTime,benchmarkTime);
  digest.validate();
  System.out.println(String.format("Processed %s entries in %s ms. Insertion rate = %s entries/s (%.4f?s per operation)",results.getOperations(),results.getTime().toMillis(),results.getOperationsPerSecond(),results.getTimePerOperation().convertTo(TimeUnit.MICROSECONDS)));
  System.out.println(String.format("Compressions: %s, %s entries/compression",digest.getCompressions(),digest.getCount() / digest.getCompressions()));
}
 

Example 40

From project AlgorithmsNYC, under directory /ALGO101/UNIT_02/util/.

Source file: CommonFunctions.java

  17 
vote

public static int partition(int[] array,int start,int end){
  int n=end + 1 - start;
  int pivotIndex=start + (new Random().nextInt(n));
  int pivotValue=array[pivotIndex];
  System.out.print("-pivotIndex=" + pivotIndex + ", pivotValue="+ pivotValue);
  CommonFunctions.swap(array,pivotIndex,end);
  int slow=start - 1;
  for (int fast=start; fast < end; fast++)   if (array[fast] < pivotValue)   CommonFunctions.swap(array,++slow,fast);
  CommonFunctions.swap(array,++slow,end);
  System.out.println(", tmpArray=" + Arrays.toString(array));
  return slow;
}
 

Example 41

From project anadix, under directory /anadix-tests/src/test/java/org/anadix/section508/rules/.

Source file: ParagraphCTest.java

  17 
vote

@Test(dataProvider="colors") public void testColorRules5(String color){
  Random r=new Random();
  char[] chars=color.toCharArray();
  for (int i=0; i < chars.length; i++) {
    chars[i]=r.nextBoolean() ? Character.toLowerCase(chars[i]) : Character.toUpperCase(chars[i]);
  }
  color=new String(chars);
  final String textContent="some talking about " + color + " and so on...";
  HtmlElement e=factory.createPTag(getUniqueId(),body,dummyAttributes);
  e.setSource(dummySource);
  e.setTextContent(textContent);
  Collection<ReportItem> result=evaluate(e);
  assertReportContains(result,TextContainsColor.class,dummySource);
  assertReportContains(result,TextContainsColor.class,color.toLowerCase());
}
 

Example 42

From project android-gltron, under directory /GlTron/src/com/glTron/Game/.

Source file: Player.java

  17 
vote

public Player(int player_number,float gridSize,Model mesh,HUD hud){
  int colour=0;
  boolean done=false;
  Random rand=new Random();
  Direction=rand.nextInt(3);
  LastDirection=Direction;
  Trails[0]=new Segment();
  trailOffset=0;
  Trails[trailOffset].vStart.v[0]=START_POS[player_number][0] * gridSize;
  Trails[trailOffset].vStart.v[1]=START_POS[player_number][1] * gridSize;
  Trails[trailOffset].vDirection.v[0]=0.0f;
  Trails[trailOffset].vDirection.v[1]=0.0f;
  trailHeight=TRAIL_HEIGHT;
  tronHUD=hud;
  Speed=10.0f;
  exp_radius=0.0f;
  Cycle=mesh;
  Player_num=player_number;
  Score=0;
  if (player_number == GLTronGame.OWN_PLAYER) {
    for (colour=0; colour < GLTronGame.MAX_PLAYERS; colour++) {
      ColourTaken[colour]=false;
    }
    ColourTaken[GLTronGame.mPrefs.PlayerColourIndex()]=true;
    mPlayerColourIndex=GLTronGame.mPrefs.PlayerColourIndex();
  }
 else {
    while (!done) {
      if (!ColourTaken[colour]) {
        ColourTaken[colour]=true;
        mPlayerColourIndex=colour;
        done=true;
      }
      colour++;
    }
  }
}
 

Example 43

From project androidTileMapEditor_1, under directory /src/it/sineo/android/tileMapEditor/.

Source file: ImageAdapter.java

  17 
vote

public ImageAdapter(Context ctx){
  this.ctx=ctx;
  this.images=new ArrayList<String>();
  this.htImages=new Hashtable<String,BitmapDrawable>();
  this.rand=new Random(System.currentTimeMillis());
  Log.d(TAG,"initialized random generator");
}
 

Example 44

From project android_packages_apps_QuickSearchBox, under directory /src/com/android/quicksearchbox/.

Source file: EventLogLogger.java

  17 
vote

public EventLogLogger(Context context,Config config){
  mContext=context;
  mConfig=config;
  mPackageName=mContext.getPackageName();
  mRandom=new Random();
}
 

Example 45

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: Utils.java

  17 
vote

public static long genID(){
  long time=System.currentTimeMillis();
  long id;
  int rand;
  Random random=new Random();
  if (sIdTree == null) {
    sIdTree=new TreeSet<Integer>();
    sIdTime=time;
  }
 else   if (sIdTime != time) {
    sIdTime=time;
    sIdTree.clear();
  }
  while (true) {
    rand=random.nextInt(2 ^ 23);
    if (!sIdTree.contains(new Integer(rand))) {
      sIdTree.add(new Integer(rand));
      break;
    }
  }
  id=rand << 41 | time;
  return id;
}
 

Example 46

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/visualizers/component/grid/.

Source file: GridVisualizer.java

  17 
vote

/** 
 * Merges the rows. This function uses a heuristical approach that guarantiess to merge  all rows into one if there is no conflict at all. If there are conflicts the heuristic will be best-efford but with linear runtime (given a a number of rows).
 * @param rows Will be altered, if no conflicts occcured this wil have onlyone element.
 */
private void mergeAllRowsIfPossible(ArrayList<Row> rows){
  Random rand=new Random(5711l);
  int tries=0;
  final int maxTries=rows.size() * 2;
  while (rows.size() > 1 && tries < maxTries) {
    int oneIdx=rand.nextInt(rows.size());
    int secondIdx=rand.nextInt(rows.size());
    if (oneIdx == secondIdx) {
      continue;
    }
    Row one=rows.get(oneIdx);
    Row second=rows.get(secondIdx);
    if (one.merge(second)) {
      rows.remove(secondIdx);
      tries=0;
    }
 else {
      tries++;
    }
  }
}
 

Example 47

From project ardverk-commons, under directory /src/test/java/org/ardverk/io/.

Source file: InputOutputStreamTest.java

  17 
vote

@Test public void produce() throws IOException {
  final byte[] expected=new byte[8 * 1024];
  Random generator=new Random();
  generator.nextBytes(expected);
  InputStream in=new InputOutputStream(){
    @Override protected void produce(    OutputStream out) throws IOException {
      out.write(expected);
    }
  }
;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  byte[] buffer=new byte[4 * 1024];
  int len=-1;
  while ((len=in.read(buffer)) != -1) {
    baos.write(buffer,0,len);
  }
  baos.close();
  in.close();
  byte[] actual=baos.toByteArray();
  TestCase.assertEquals(expected.length,actual.length);
  for (int i=0; i < expected.length; i++) {
    TestCase.assertEquals(expected[i],actual[i]);
  }
}
 

Example 48

From project Arecibo, under directory /util/src/test/java/com/ning/arecibo/util/timeline/samples/.

Source file: TestSampleCoder.java

  17 
vote

@SuppressWarnings("unchecked") @Test(groups="fast") public void testCombineSampleBytes() throws Exception {
  final ScalarSample[] samplesToChoose=new ScalarSample[]{new ScalarSample(SampleOpcode.DOUBLE,2.0),new ScalarSample(SampleOpcode.DOUBLE,1.0),new ScalarSample(SampleOpcode.INT_ZERO,0)};
  final int[] repetitions=new int[]{1,2,3,4,5,240,250,300};
  final Random rand=new Random(0);
  int count=0;
  final TimelineChunkAccumulator accum=new TimelineChunkAccumulator(0,0,sampleCoder);
  final List<ScalarSample> samples=new ArrayList<ScalarSample>();
  for (int i=0; i < 20; i++) {
    final ScalarSample sample=samplesToChoose[rand.nextInt(samplesToChoose.length)];
    final int repetition=repetitions[rand.nextInt(repetitions.length)];
    for (int r=0; r < repetition; r++) {
      samples.add(sample);
      accum.addSample(sample);
      count++;
    }
  }
  final byte[] sampleBytes=sampleCoder.compressSamples(samples);
  final byte[] accumBytes=accum.getEncodedSamples().getEncodedBytes();
  Assert.assertEquals(accumBytes,sampleBytes);
  final List<ScalarSample> restoredSamples=sampleCoder.decompressSamples(sampleBytes);
  Assert.assertEquals(restoredSamples.size(),samples.size());
  for (int i=0; i < count; i++) {
    Assert.assertEquals(restoredSamples.get(i),samples.get(i));
  }
  for (int fragmentLength=2; fragmentLength < count / 2; fragmentLength++) {
    final List<byte[]> fragments=new ArrayList<byte[]>();
    final int fragmentCount=(int)Math.ceil((double)count / (double)fragmentLength);
    for (int fragCounter=0; fragCounter < fragmentCount; fragCounter++) {
      final int fragIndex=fragCounter * fragmentLength;
      final List<ScalarSample> fragment=samples.subList(fragIndex,Math.min(count,fragIndex + fragmentLength));
      fragments.add(sampleCoder.compressSamples(fragment));
    }
    final byte[] combined=sampleCoder.combineSampleBytes(fragments);
    final List<ScalarSample> restored=sampleCoder.decompressSamples(combined);
    Assert.assertEquals(restored.size(),samples.size());
    for (int i=0; i < count; i++) {
      Assert.assertEquals(restored.get(i),samples.get(i));
    }
  }
}
 

Example 49

From project astyanax, under directory /src/test/java/com/netflix/astyanax/connectionpool/impl/.

Source file: Stress.java

  17 
vote

private static void think(int min,int max){
  try {
    if (max > min) {
      Thread.sleep(min + new Random().nextInt(max - min));
    }
 else {
      Thread.sleep(min);
    }
  }
 catch (  InterruptedException e) {
  }
}
 

Example 50

From project autopsy, under directory /Testing/test/qa-functional/src/org/sleuthkit/autopsy/testing/.

Source file: RegressionTest.java

  17 
vote

public void testIngest(){
  logger.info("Ingest 3");
  long start=System.currentTimeMillis();
  IngestManager man=IngestManager.getDefault();
  while (man.isEnqueueRunning()) {
    new Timeout("pausing",5000).sleep();
  }
  logger.info("Enqueue took " + (System.currentTimeMillis() - start) + "ms");
  while (man.isIngestRunning()) {
    new Timeout("pausing",1000).sleep();
  }
  new Timeout("pausing",15000).sleep();
  boolean sleep=true;
  while (man.areModulesRunning()) {
    new Timeout("pausing",5000).sleep();
  }
  logger.info("Ingest (including enqueue) took " + (System.currentTimeMillis() - start) + "ms");
  Random rand=new Random();
  new Timeout("pausing",10000 + (rand.nextInt(15000) + 5000)).sleep();
  screenshot("Finished Ingest");
}
 

Example 51

From project azkaban, under directory /azkaban/src/unit/azkaban/utils/.

Source file: UtilsTest.java

  17 
vote

public File createTestFiles(String... files) throws IOException {
  Random rand=new Random();
  File f=Utils.createTempDir();
  for (  String s : files) {
    File newFile=new File(f,s);
    newFile.getParentFile().mkdirs();
    int size=rand.nextInt(5 * 1024);
    byte[] bytes=new byte[size];
    rand.nextBytes(bytes);
    OutputStream out=new FileOutputStream(newFile);
    out.write(bytes);
    out.close();
  }
  return f;
}
 

Example 52

From project Backpack, under directory /src/main/java/com/almuramc/backpack/bukkit/listener/.

Source file: BackpackListener.java

  17 
vote

@EventHandler public void onItemPickup(PlayerPickupItemEvent event){
  if (!PERM.has(event.getPlayer().getWorld(),event.getPlayer().getName(),"backpack.overflow")) {
    return;
  }
  Player player=event.getPlayer();
  if (!InventoryUtil.hasOnlyOneFreeSlot(player.getInventory())) {
    return;
  }
  ItemStack item=event.getItem().getItemStack();
  World world=PermissionHelper.getWorldToOpen(player,player.getWorld());
  BackpackInventory inventory=STORE.load(player,world);
  if (inventory.firstEmpty() == -1) {
    return;
  }
  HashMap<Integer,? extends ItemStack> withinInventory=event.getPlayer().getInventory().all(item);
  for (  ItemStack stack : withinInventory.values()) {
    if (stack.getAmount() < event.getPlayer().getInventory().getMaxStackSize()) {
      return;
    }
  }
  List<ItemStack> blacklistedItems=inventory.getIllegalItems(CONFIG.getBlacklistedItems());
  if (blacklistedItems.contains(item)) {
    if (CONFIG.useSpout() && BackpackPlugin.getInstance().getHooks().isSpoutPluginEnabled()) {
      SafeSpout.sendMessage(player,"Picking up illegal item(s)!","Backpack",Material.LAVA);
    }
 else {
      MessageHelper.sendMessage(player,"Trying to pickup illegal item(s)! Stopping the pickup...");
    }
    return;
  }
  inventory.addItem(item);
  STORE.save(player,world,inventory);
  event.getItem().remove();
  Random random=new Random();
  player.playSound(player.getLocation(),Sound.ITEM_PICKUP,0.2F,((random.nextFloat() - random.nextFloat()) * 0.7F + 1.0F) * 2.0F);
  event.setCancelled(true);
}
 

Example 53

From project BeeQueue, under directory /test/org/beequeue/hash/.

Source file: HashKeyTest.java

  17 
vote

@Test public void test(){
  Random r=new Random();
  byte[] bytes=new byte[100];
  r.nextBytes(bytes);
  MessageDigest md=MessageDigestUtils.md();
  md.update(bytes);
  HashKey sc=new HashKey(HashKeyResource.F,md.digest());
  System.out.println(sc);
  HashKey sc2=HashKey.valueOf(sc.toString());
  assertEquals(sc.toString(),sc2.toString());
  assertEquals(sc,sc2);
  System.out.println(ToStringUtil.toString(sc2));
  HashKey sc3=new HashKey(HashKeyResource.D,md.digest());
  bytes=new byte[200];
  r.nextBytes(bytes);
  MessageDigest md2=MessageDigestUtils.md();
  md2.update(bytes);
  HashKey sc4=new HashKey(HashKeyResource.F,md2.digest());
  assertFalse(sc2.equals(sc3));
  System.out.println(sc3);
  System.out.println(sc4);
  assertFalse(sc2.equals(sc4));
}
 

Example 54

From project Bifrost, under directory /src/main/java/com/craftfire/bifrost/scripts/forum/.

Source file: SMF.java

  17 
vote

@Override public void createUser(ScriptUser user) throws SQLException {
  if (isRegistered(user.getUsername())) {
    return;
  }
  Random r=new Random();
  int rand=r.nextInt(1000000);
  String salt=CraftCommons.encrypt(Encryption.MD5,rand).substring(0,4);
  HashMap<String,Object> data=new HashMap<String,Object>();
  user.setPasswordSalt(salt);
  user.setRegDate(new Date());
  user.setLastLogin(new Date());
  data.put(this.membernamefield,user.getUsername());
  data.put("passwd",user.getPassword());
  if (this.getVersionRanges()[0].inVersionRange(this.getVersion())) {
    data.put("dateregistered",user.getRegDate().getTime() / 1000);
    data.put("realname",user.getUsername());
    data.put("emailaddress",user.getEmail());
    data.put("memberip",user.getRegIP());
    data.put("memberip2",user.getLastIP());
    data.put("passwordsalt",user.getPasswordSalt());
  }
 else   if (this.getVersionRanges()[1].inVersionRange(this.getVersion())) {
    data.put("date_registered",user.getRegDate().getTime() / 1000);
    data.put("real_name",user.getUsername());
    data.put("email_address",user.getEmail());
    data.put("member_ip",user.getRegIP());
    data.put("member_ip2",user.getLastIP());
    data.put("password_salt",user.getPasswordSalt());
  }
  this.getDataManager().insertFields(data,"members");
  user.setID(getUserID(user.getUsername()));
  this.getDataManager().executeQueryVoid("UPDATE `" + this.getDataManager().getPrefix() + "settings"+ "` SET `value` ="+ " '"+ user.getUsername()+ "' WHERE `variable` = 'latestRealName'");
  this.getDataManager().executeQueryVoid("UPDATE `" + this.getDataManager().getPrefix() + "settings"+ "` SET `value` ="+ " '"+ user.getID()+ "' WHERE `variable` = 'latestMember'");
  this.getDataManager().executeQueryVoid("UPDATE `" + this.getDataManager().getPrefix() + "settings"+ "` SET `value` ="+ " '"+ (user.getRegDate().getTime() / 1000)+ "' WHERE `variable` = 'memberlist_updated'");
  this.getDataManager().executeQueryVoid("UPDATE `" + this.getDataManager().getPrefix() + "settings"+ "` SET `value` ="+ " value + 1 WHERE `variable` = 'totalMembers'");
}
 

Example 55

From project big-data-plugin, under directory /test-src/org/pentaho/di/job/entries/hadoopjobexecutor/.

Source file: SecurityManagerStackTest.java

  17 
vote

@Test public void randomized_executions() throws Exception {
  final SecurityManagerStack stack=new SecurityManagerStack();
  final Random random=new Random();
  NoExitSecurityManager test=new NoExitSecurityManager(null);
  SecurityManager original=System.getSecurityManager();
  stack.setSecurityManager(test);
  final int NUM_TASKS=10;
  ExecutorService exec=Executors.newFixedThreadPool(NUM_TASKS);
  exec.invokeAll(Collections.nCopies(NUM_TASKS,new Callable<Void>(){
    @Override public Void call() throws Exception {
      NoExitSecurityManager sm=new NoExitSecurityManager(null);
      try {
        Thread.sleep(random.nextInt(1000));
        System.out.println("set: " + sm);
        stack.setSecurityManager(sm);
        Thread.sleep(random.nextInt(1000));
      }
 catch (      Exception ex) {
      }
 finally {
        System.out.println("rm : \t" + sm);
        stack.removeSecurityManager(sm);
      }
      return null;
    }
  }
));
  exec.shutdown();
  exec.awaitTermination(3,TimeUnit.SECONDS);
  assertEquals(test,System.getSecurityManager());
  stack.removeSecurityManager(test);
  assertEquals(original,System.getSecurityManager());
}
 

Example 56

From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/ea/fitness/.

Source file: EAFitness.java

  17 
vote

public EAFitness(EAConfiguration config){
  this.config=config;
  rand=new Random(System.currentTimeMillis());
  Simulator sim=Simulator.getInstance();
  behaviorModule=new BehaviorModuleSL(sim.getDrone(0),sim.getDrone(0));
  TerminatorTimer timerTerminator=new TerminatorTimer();
  timerTerminator.setThreshold(config.FSM_TIMER_THRESHOLD);
  behaviorModule.addTerminalCondition(timerTerminator);
}
 

Example 57

From project blueprint-namespaces, under directory /blueprint/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/comp/.

Source file: Listener.java

  17 
vote

public void bind(Object service){
  try {
    Thread.sleep(new Random().nextInt(20));
  }
 catch (  InterruptedException ie) {
  }
  System.out.println(Thread.currentThread().getId() + ": bind " + service);
}
 

Example 58

From project Bukkit-Plugin-Utilties, under directory /src/main/java/de/xzise/.

Source file: MinecraftUtil.java

  17 
vote

/** 
 * Returns a random value of the list. If the list is not set ( {@link #isSet(Object)}) it will return null.
 * @param list The given list.
 * @return a random element of the list.
 * @since 1.0
 */
public static <T>T getRandom(List<T> list){
  if (MinecraftUtil.isSet(list)) {
    return list.get(new Random().nextInt(list.size()));
  }
 else {
    return null;
  }
}
 

Example 59

From project buzzwords, under directory /src/com/buzzwords/.

Source file: Deck.java

  17 
vote

/** 
 * Constructor
 * @param context The Context within which to work, used to create the DB
 */
public Deck(Context context){
  mContext=context;
  mDatabaseOpenHelper=new DeckOpenHelper(context);
  mCache=new LinkedList<Card>();
  SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(context);
  Random r=new Random();
  mSeed=sp.getInt("deck_seed",r.nextInt());
  r=new Random(mSeed);
  Editor editor=sp.edit();
  editor.putInt("deck_seed",mSeed);
  editor.commit();
  mPosition=sp.getInt("deck_position",0);
  int sizeOfDeck=mDatabaseOpenHelper.countCards();
  mOrder=new ArrayList<Integer>(sizeOfDeck);
  for (int i=0; i < sizeOfDeck; ++i) {
    mOrder.add(i);
  }
  Collections.shuffle(mOrder,r);
  mCache=mDatabaseOpenHelper.loadCache();
  mDatabaseOpenHelper.close();
}
 

Example 60

From project C-Cat, under directory /core/src/main/java/gov/llnl/ontology/mains/.

Source file: SelectRandomTaggedNodes.java

  17 
vote

public static void main(String[] args) throws Exception {
  MRArgOptions options=new MRArgOptions();
  options.addOption('n',"numberOfPairs","Sets the number of pairs to create",true,"INT","Required");
  options.addOption('k',"keyList","Sets the key list of valid document keys.  Key " + "pairs will be selected at random from this list",true,"FILE","Required");
  options.parseOptions(args);
  options.validate("","<out>",SelectRandomTaggedNodes.class,1,'n','k');
  List<String> documentKeys=loadDocKeys(options.getStringOption('k'));
  int numPairs=options.getIntOption('n');
  Set<StringPair> keyPairs=Sets.newHashSet();
  Random random=new Random();
  while (keyPairs.size() < numPairs) {
    int i=random.nextInt(documentKeys.size());
    int j=random.nextInt(documentKeys.size());
    if (i == j)     continue;
    keyPairs.add(new StringPair(documentKeys.get(i),documentKeys.get(j)));
  }
  CorpusTable table=options.corpusTable();
  for (  StringPair pair : keyPairs) {
    StringBuilder builder=new StringBuilder();
    addCategories(builder,pair.x,table);
    builder.append("|");
    addCategories(builder,pair.y,table);
    System.out.println(builder.toString());
  }
}
 

Example 61

From project Carolina-Digital-Repository, under directory /solr-ingest/src/test/java/edu/unc/lib/dl/data/ingest/solr/.

Source file: UpdateNodeRequestTest.java

  17 
vote

@Test public void countChildrenByStatusTest(){
  Map<ProcessingStatus,Integer> randomCounts=new HashMap<ProcessingStatus,Integer>();
  for (  ProcessingStatus status : ProcessingStatus.values()) {
    randomCounts.put(status,0);
  }
  UpdateNodeRequest root=new UpdateNodeRequest("root",null);
  int depth=5;
  int totalChildren=0;
  Random random=new Random();
  List<UpdateNodeRequest> previousTier=new ArrayList<UpdateNodeRequest>();
  previousTier.add(root);
  for (int i=0; i < depth; i++) {
    int numChildren=3 + random.nextInt(5);
    List<UpdateNodeRequest> nextTier=new ArrayList<UpdateNodeRequest>(numChildren);
    for (int j=0; j < numChildren; j++) {
      int parentIndex=0;
      if (previousTier.size() > 1)       parentIndex=random.nextInt(previousTier.size() - 1);
      ProcessingStatus status=ProcessingStatus.values()[random.nextInt(ProcessingStatus.values().length)];
      UpdateNodeRequest newNode=new UpdateNodeRequest(i + "" + j,previousTier.get(parentIndex),status);
      randomCounts.put(status,randomCounts.get(status) + 1);
      nextTier.add(newNode);
      totalChildren++;
    }
    previousTier=nextTier;
  }
  assertEquals(totalChildren,root.countChildren());
  Map<ProcessingStatus,Integer> recursiveCounts=root.countChildrenByStatus();
  for (  ProcessingStatus status : ProcessingStatus.values()) {
    assertEquals(randomCounts.get(status),recursiveCounts.get(status));
  }
}
 

Example 62

From project Caronas, under directory /src/main/java/componentesdosistema/.

Source file: Usuario.java

  17 
vote

/** 
 * @param origem
 * @param destino
 * @param cidade
 * @param data
 * @param hora
 * @param vagas
 * @return
 * @throws Exception
 */
public String cadastrarCaronaMunicipal(String origem,String destino,String cidade,String data,String hora,String vagas) throws DadosCaronaException {
  Carona novaCarona=new Carona(origem,destino,cidade,data,hora,vagas);
  novaCarona.setDono(this);
  String caronaID=String.valueOf(Math.abs(new Random().nextInt()));
  novaCarona.setID(caronaID);
  caronas.add(novaCarona);
  perfil.adicionaCarona(caronaID);
  return novaCarona.getID();
}
 

Example 63

From project cascading, under directory /src/test/cascading/tuple/.

Source file: SpillableTupleHadoopTest.java

  17 
vote

private void performMapTest(int numKeys,int listSize,int mapThreshold,int listThreshold,JobConf jobConf){
  HadoopFlowProcess flowProcess=new HadoopFlowProcess(jobConf);
  HadoopSpillableTupleMap map=new HadoopSpillableTupleMap(SpillableProps.defaultMapInitialCapacity,SpillableProps.defaultMapLoadFactor,mapThreshold,listThreshold,flowProcess);
  Set<Integer> keySet=new HashSet<Integer>();
  Random gen=new Random(1);
  for (int i=0; i < listSize * numKeys; i++) {
    String aString="string number " + i;
    double random=Math.random();
    double keys=numKeys / 3.0;
    int key=(int)(gen.nextDouble() * keys + gen.nextDouble() * keys + gen.nextDouble() * keys);
    map.get(new Tuple(key)).add(new Tuple(i,aString,random,new Text(aString)));
    keySet.add(key);
  }
  assertEquals("not equal: map.size();",keySet.size(),map.size());
}
 

Example 64

From project cdh-mapreduce-ext, under directory /src/main/java/org/apache/hadoop/mapreduce/lib/partition/.

Source file: InputSampler.java

  17 
vote

/** 
 * Randomize the split order, then take the specified number of keys from each split sampled, where each key is selected with the specified probability and possibly replaced by a subsequently selected key when the quota of keys from that split is satisfied.
 */
@SuppressWarnings("unchecked") public K[] getSample(InputFormat<K,V> inf,Job job) throws IOException, InterruptedException {
  List<InputSplit> splits=inf.getSplits(job);
  ArrayList<K> samples=new ArrayList<K>(numSamples);
  int splitsToSample=Math.min(maxSplitsSampled,splits.size());
  Random r=new Random();
  long seed=r.nextLong();
  r.setSeed(seed);
  LOG.debug("seed: " + seed);
  for (int i=0; i < splits.size(); ++i) {
    InputSplit tmp=splits.get(i);
    int j=r.nextInt(splits.size());
    splits.set(i,splits.get(j));
    splits.set(j,tmp);
  }
  for (int i=0; i < splitsToSample || (i < splits.size() && samples.size() < numSamples); ++i) {
    TaskAttemptContext samplingContext=new TaskAttemptContext(job.getConfiguration(),new TaskAttemptID());
    RecordReader<K,V> reader=inf.createRecordReader(splits.get(i),samplingContext);
    reader.initialize(splits.get(i),samplingContext);
    while (reader.nextKeyValue()) {
      if (r.nextDouble() <= freq) {
        if (samples.size() < numSamples) {
          samples.add(ReflectionUtils.copy(job.getConfiguration(),reader.getCurrentKey(),null));
        }
 else {
          int ind=r.nextInt(numSamples);
          if (ind != numSamples) {
            samples.set(ind,ReflectionUtils.copy(job.getConfiguration(),reader.getCurrentKey(),null));
          }
          freq*=(numSamples - 1) / (double)numSamples;
        }
      }
    }
    reader.close();
  }
  return (K[])samples.toArray();
}
 

Example 65

From project Citizens, under directory /src/core/net/citizensnpcs/properties/properties/.

Source file: UtilityProperties.java

  17 
vote

public static ItemStack getRandomDrop(String drops){
  String[] split=drops.split(",");
  int id=Integer.parseInt(split[new Random().nextInt(split.length)]);
  int amount=new Random().nextInt(3);
  if (Material.getMaterial(id) != null) {
    if (amount != 0) {
      return new ItemStack(id,amount);
    }
  }
  return null;
}
 

Example 66

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/acewiki/.

Source file: Wiki.java

  16 
vote

/** 
 * Logs in the given user.
 * @param user The user to log in.
 * @param stayLoggedIn Defines whether the user should stay logged in or not.
 */
public void login(User user,boolean stayLoggedIn){
  log("syst","login");
  user.setUserData("stayloggedin",stayLoggedIn + "");
  setCookie("stayloggedin",stayLoggedIn + "");
  String stayloggedintoken;
  if (stayLoggedIn) {
    stayloggedintoken=(new Random()).nextLong() + "";
  }
 else {
    stayloggedintoken="";
  }
  user.setUserData("stayloggedintoken",stayloggedintoken);
  setCookie("stayloggedintoken",stayloggedintoken);
  setUser(user);
}
 

Example 67

From project agile, under directory /agile-web/src/main/java/org/headsupdev/agile/web/dialogs/.

Source file: LoginDialog.java

  16 
vote

protected void onSubmit(){
  ((WebResponse)getResponse()).clearCookie(new Cookie(HeadsUpPage.REMEMBER_COOKIE_NAME,""));
  org.headsupdev.agile.api.User user=owner.getSecurityManager().getUserByUsername(username);
  if (user == null) {
    info("Invalid username");
    return;
  }
  String encodedPass=HashUtil.getMD5Hex(password);
  if (!encodedPass.equals(user.getPassword())) {
    info("Incorrect password");
    return;
  }
  if (!user.canLogin()) {
    info("Account is not currently active");
    return;
  }
  if (remember) {
    String rememberKey=String.valueOf(new Random(System.currentTimeMillis()).nextInt());
    Cookie cookie=new Cookie(HeadsUpPage.REMEMBER_COOKIE_NAME,username + ":" + rememberKey);
    cookie.setMaxAge(60 * 60 * 24* 32);
    ((WebResponse)getResponse()).addCookie(cookie);
    owner.addRememberMe(username,rememberKey);
  }
 else   if (((HeadsUpSession)getSession()).getUser() != null) {
    ((WebResponse)getResponse()).clearCookie(new Cookie(HeadsUpPage.REMEMBER_COOKIE_NAME,""));
    owner.removeRememberMe(((HeadsUpSession)getSession()).getUser().getUsername());
  }
  ((StoredUser)user).setLastLogin(new Date());
  ((HeadsUpSession)getSession()).setUser(user);
  if (!continueToOriginalDestination()) {
    Class previous=((HeadsUpSession)getSession()).getPreviousPageClass();
    if (previous != null) {
      setResponsePage(previous,((HeadsUpSession)getSession()).getPreviousPageParameters());
    }
 else {
      setResponsePage(owner.getPageClass(""));
    }
  }
}
 

Example 68

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.

Source file: AStream.java

  16 
vote

private void reconnect2(){
  try {
    connect();
    return;
  }
 catch (  TwitterException.E40X e) {
    throw e;
  }
catch (  Exception e) {
    System.out.println(e);
  }
  int wait=20 + new Random().nextInt(40);
  int waited=0;
  while (waited < MAX_WAIT_SECONDS) {
    try {
      Thread.sleep(wait * 1000);
      waited+=wait;
      if (wait < 300) {
        wait=wait * 2;
      }
      connect();
      return;
    }
 catch (    TwitterException.E40X e) {
      throw e;
    }
catch (    Exception e) {
      System.out.println(e);
    }
  }
  throw new TwitterException.E50X("Could not connect to streaming server");
}
 

Example 69

From project AndroidLab, under directory /libs/unboundid/docs/examples/.

Source file: ModRateThread.java

  16 
vote

/** 
 * Creates a new mod rate thread with the provided information.
 * @param threadNumber  The thread number for this thread.
 * @param connection    The connection to use for the modifications.
 * @param entryDN       The value pattern to use for the entry DNs.
 * @param attributes    The names of the attributes to modify.
 * @param charSet       The set of characters to include in the generatedvalues.
 * @param valueLength   The length in bytes to use for the generated values.
 * @param authzID       The value pattern to use to generate authorizationidentities for use with the proxied authorization control.  It may be  {@code null} if proxiedauthorization should not be used.
 * @param randomSeed    The seed to use for the random number generator.
 * @param startBarrier  A barrier used to coordinate starting between all ofthe threads.
 * @param modCounter    A value that will be used to keep track of the totalnumber of modifications performed.
 * @param modDurations  A value that will be used to keep track of the totalduration for all modifications.
 * @param errorCounter  A value that will be used to keep track of the numberof errors encountered while processing.
 * @param rcCounter     The result code counter to use for keeping trackof the result codes for failed operations.
 * @param rateBarrier   The barrier to use for controlling the rate ofmodifies.   {@code null} if no rate-limitingshould be used.
 */
ModRateThread(final int threadNumber,final LDAPConnection connection,final ValuePattern entryDN,final String[] attributes,final byte[] charSet,final int valueLength,final ValuePattern authzID,final long randomSeed,final CyclicBarrier startBarrier,final AtomicLong modCounter,final AtomicLong modDurations,final AtomicLong errorCounter,final ResultCodeCounter rcCounter,final FixedRateBarrier rateBarrier){
  setName("ModRate Thread " + threadNumber);
  setDaemon(true);
  this.connection=connection;
  this.entryDN=entryDN;
  this.attributes=attributes;
  this.charSet=charSet;
  this.valueLength=valueLength;
  this.authzID=authzID;
  this.modCounter=modCounter;
  this.modDurations=modDurations;
  this.errorCounter=errorCounter;
  this.rcCounter=rcCounter;
  this.startBarrier=startBarrier;
  fixedRateBarrier=rateBarrier;
  connection.setConnectionName("mod-" + threadNumber);
  resultCode=new AtomicReference<ResultCode>(null);
  modThread=new AtomicReference<Thread>(null);
  stopRequested=new AtomicBoolean(false);
  random=new Random(randomSeed);
}
 

Example 70

From project asadmin, under directory /war-example/src/main/java/org/n0pe/mojo/examples/war/.

Source file: DumbServlet.java

  16 
vote

@Override protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out=response.getWriter();
  try {
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet DumbServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet DumbServlet at " + request.getContextPath() + "</h1>");
    out.println("<p>Random Integer: " + new Random().nextInt() + "</p>");
    out.println("</body>");
    out.println("</html>");
  }
  finally {
    out.close();
  }
}
 

Example 71

From project BoneJ, under directory /src/org/doube/util/.

Source file: ReporterOptions.java

  16 
vote

public void run(String arg){
  GenericDialog dialog=new GenericDialog("BoneJ");
  dialog.addMessage("Allow usage data collection?");
  dialog.addMessage("BoneJ would like to collect data on \n" + "which plugins are being used, to direct development\n" + "and promote BoneJ to funders.");
  dialog.addMessage("If you agree to participate please hit OK\n" + "otherwise, cancel. For more information click Help.");
  dialog.addHelp("http://bonej.org/stats");
  dialog.showDialog();
  if (dialog.wasCanceled()) {
    Prefs.set(OPTOUTKEY,false);
    Prefs.set(ReporterOptions.COOKIE,"");
    Prefs.set(ReporterOptions.COOKIE2,"");
    Prefs.set(ReporterOptions.FIRSTTIMEKEY,"");
    Prefs.set(ReporterOptions.SESSIONKEY,"");
  }
 else {
    Prefs.set(OPTOUTKEY,true);
    Prefs.set(ReporterOptions.COOKIE,new Random().nextInt(Integer.MAX_VALUE));
    Prefs.set(ReporterOptions.COOKIE2,new Random().nextInt(Integer.MAX_VALUE));
    long time=System.currentTimeMillis() / 1000;
    Prefs.set(ReporterOptions.FIRSTTIMEKEY,Long.toString(time));
    Prefs.set(SESSIONKEY,1);
  }
  Prefs.set(OPTOUTSET,true);
  Prefs.savePreferences();
  UsageReporter.reportEvent(this).send();
  return;
}
 

Example 72

From project behemoth, under directory /solr/src/main/java/com/digitalpebble/behemoth/solr/.

Source file: SOLRIndexerJob.java

  15 
vote

public int run(String[] args) throws Exception {
  final FileSystem fs=FileSystem.get(getConf());
  if (args.length != 2) {
    String syntax="com.digitalpebble.solr.SOLRIndexerJob in solrURL";
    System.err.println(syntax);
    return -1;
  }
  Path inputPath=new Path(args[0]);
  String solrURL=args[1];
  JobConf job=new JobConf(getConf());
  job.setJarByClass(this.getClass());
  job.setJobName("Indexing " + inputPath + " into SOLR");
  job.setInputFormat(SequenceFileInputFormat.class);
  job.setOutputFormat(SOLROutputFormat.class);
  job.setOutputKeyClass(Text.class);
  job.setOutputValueClass(BehemothDocument.class);
  job.setMapperClass(IdentityMapper.class);
  job.setNumReduceTasks(0);
  FileInputFormat.addInputPath(job,inputPath);
  final Path tmp=new Path("tmp_" + System.currentTimeMillis() + "-"+ new Random().nextInt());
  FileOutputFormat.setOutputPath(job,tmp);
  job.set("solr.server.url",solrURL);
  try {
    JobClient.runJob(job);
  }
 catch (  Exception e) {
    LOG.error(e);
  }
 finally {
    fs.delete(tmp,true);
  }
  return 0;
}
 

Example 73

From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/net/bioclipse/seneca/ga/.

Source file: MoleculeCandidateFactory.java

  15 
vote

public IMolecule generateRandomCandidate(Random arg0){
  SingleStructureRandomGenerator ssrg;
  try {
    ssrg=new SingleStructureRandomGenerator();
    ssrg.setAtomContainer(formula);
    IMolecule mol=ssrg.generate();
    rearangeAtoms(mol);
    if (detectAromaticity)     CDKHueckelAromaticityDetector.detectAromaticity(mol);
    return mol;
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 74

From project bson4jackson, under directory /src/test/java/de/undercouch/bson4jackson/.

Source file: BsonGeneratorTest.java

  15 
vote

@Test public void objectIds() throws Exception {
  Map<String,Object> data=new LinkedHashMap<String,Object>();
  ObjectId objectId=new ObjectId((int)(System.currentTimeMillis() / 1000),new Random().nextInt(),100);
  data.put("_id",objectId);
  BSONObject obj=generateAndParse(data);
  org.bson.types.ObjectId result=(org.bson.types.ObjectId)obj.get("_id");
  assertNotNull(result);
  assertEquals(objectId.getTime(),result.getTimeSecond());
  assertEquals(objectId.getMachine(),result.getMachine());
  assertEquals(objectId.getInc(),result.getInc());
}
 

Example 75

From project Catacombs, under directory /src/net/steeleyes/maps/.

Source file: PrePlanned.java

  15 
vote

public int getAccess(Random rnd,Direction oside,Direction dir){
  Direction side=oside;
switch (dir) {
case NORTH:
    break;
case EAST:
  side=side.turn270();
break;
case SOUTH:
side=side.turn180();
break;
case WEST:
side=side.turn90();
break;
}
List<Integer> tmp=access.get(side);
if (!tmp.isEmpty()) {
int offset=tmp.get(rnd.nextInt(tmp.size()));
int max=(side.vertical()) ? grid.getSize().x - 1 : grid.getSize().y - 1;
Boolean reflect=false;
switch (dir) {
case NORTH:
break;
case EAST:
reflect=(oside.horizontal());
break;
case SOUTH:
reflect=true;
break;
case WEST:
reflect=(oside.vertical());
break;
}
return (reflect) ? max - offset : offset;
}
return -1;
}