List of usage examples for java.util Random setSeed
public synchronized void setSeed(long seed)
From source file:com.samanamp.algorithms.RandomSelectionAlgorithm.java
public void runAlgoAndSimulation(int maxCost, int maxTime, int runs) { this.maxCost = maxCost; this.maxTime = maxTime; this.runs = runs; Random randomGen = new Random(); randomGen.setSeed(System.currentTimeMillis()); Node[] nodes = graph.vertexSet().toArray(new Node[graph.vertexSet().size()]); LinkedList<Node> selectedNodes = new LinkedList<Node>(); Node tmpNode;/*w w w . j a va 2s . c o m*/ int arraySize = nodes.length; for (int currentCost = 0; currentCost < maxCost;) { tmpNode = nodes[((int) (randomGen.nextFloat() * arraySize))]; if (tmpNode.cost + currentCost <= maxCost) { selectedNodes.add(tmpNode); currentCost += tmpNode.cost; } } System.out.println("#nodes selected: " + selectedNodes.size()); runSimulation(selectedNodes); }
From source file:gov.nih.nci.cabig.caaers.web.filters.CsrfPreventionFilter.java
private String generateCsrfToken() { long seed = System.currentTimeMillis(); Random r = new Random(); r.setSeed(seed); return Long.toString(seed) + Long.toString(Math.abs(r.nextLong())); }
From source file:ca.rmen.android.poetassistant.wotd.WotdLoader.java
@Override public ResultListData<WotdEntry> loadInBackground() { Log.d(TAG, "loadInBackground()"); List<WotdEntry> data = new ArrayList<>(100); Cursor cursor = mDictionary.getRandomWordCursor(); if (cursor == null || cursor.getCount() == 0) return emptyResult(); try {//w ww . ja v a 2s . c om Set<String> favorites = mFavorites.getFavorites(); Calendar calendar = Wotd.getTodayUTC(); Calendar calendarDisplay = Wotd.getTodayUTC(); calendarDisplay.setTimeZone(TimeZone.getDefault()); Settings.Layout layout = Settings.getLayout(mPrefs); for (int i = 0; i < 100; i++) { Random random = new Random(); random.setSeed(calendar.getTimeInMillis()); String date = DateUtils.formatDateTime(getContext(), calendarDisplay.getTimeInMillis(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL); int position = random.nextInt(cursor.getCount()); if (cursor.moveToPosition(position)) { String word = cursor.getString(0); @ColorRes int color = (i % 2 == 0) ? R.color.row_background_color_even : R.color.row_background_color_odd; data.add(new WotdEntry(word, date, ContextCompat.getColor(getContext(), color), favorites.contains(word), layout == Settings.Layout.EFFICIENT)); } calendar.add(Calendar.DAY_OF_YEAR, -1); calendarDisplay.add(Calendar.DAY_OF_YEAR, -1); } } finally { cursor.close(); } return new ResultListData<>(getContext().getString(R.string.wotd_list_header), false, data); }
From source file:org.apache.hadoop.hdfs.server.namenode.NNStorage.java
/** * Generate new namespaceID.//from w ww .j av a 2 s . com * * namespaceID is a persistent attribute of the namespace. * It is generated when the namenode is formatted and remains the same * during the life cycle of the namenode. * When a datanodes register they receive it as the registrationID, * which is checked every time the datanode is communicating with the * namenode. Datanodes that do not 'know' the namespaceID are rejected. * * @return new namespaceID */ static int newNamespaceID() { Random r = new Random(); r.setSeed(FSNamesystem.now()); int newID = 0; while (newID == 0) newID = r.nextInt(0x7FFFFFFF); // use 31 bits only return newID; }
From source file:org.standard.bestpratice.security.Secure.java
public void encodeRampartNonce() { Random random = null; try {//w w w . ja v a 2s.c o m random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(System.currentTimeMillis()); } catch (final NoSuchAlgorithmException ex) { LOG.error("Sha 1 not find", ex); } final byte[] r = new byte[16]; random.nextBytes(r); String nonceBase64 = Base64.encodeBase64String(r); LOG.debug(r.toString()); nonceBase64 = nonceBase64.replaceAll("[\r\n]+", ""); LOG.debug(nonceBase64); LOG.debug("saut de ligne"); //dHxHn8NcEjzaQ4KQX6j27Q== //ZlMIni/fEyY4qpBCJXAIxQ== //tAzmLb8dbvHtHARq1EF5OQ== //0BoFd08zqh1z8htR9WqtrUCayXY= }
From source file:org.apache.hadoop.mapred.TestSequenceFileAsBinaryInputFormat.java
public void testBinary() throws IOException { JobConf job = new JobConf(); FileSystem fs = FileSystem.getLocal(job); Path dir = new Path(System.getProperty("test.build.data", ".") + "/mapred"); Path file = new Path(dir, "testbinary.seq"); Random r = new Random(); long seed = r.nextLong(); r.setSeed(seed); fs.delete(dir, true);// w w w .j a v a2 s .c o m FileInputFormat.setInputPaths(job, dir); Text tkey = new Text(); Text tval = new Text(); SequenceFile.Writer writer = new SequenceFile.Writer(fs, job, file, Text.class, Text.class); try { for (int i = 0; i < RECORDS; ++i) { tkey.set(Integer.toString(r.nextInt(), 36)); tval.set(Long.toString(r.nextLong(), 36)); writer.append(tkey, tval); } } finally { writer.close(); } InputFormat<BytesWritable, BytesWritable> bformat = new SequenceFileAsBinaryInputFormat(); int count = 0; r.setSeed(seed); BytesWritable bkey = new BytesWritable(); BytesWritable bval = new BytesWritable(); Text cmpkey = new Text(); Text cmpval = new Text(); DataInputBuffer buf = new DataInputBuffer(); final int NUM_SPLITS = 3; FileInputFormat.setInputPaths(job, file); for (InputSplit split : bformat.getSplits(job, NUM_SPLITS)) { RecordReader<BytesWritable, BytesWritable> reader = bformat.getRecordReader(split, job, Reporter.NULL); try { while (reader.next(bkey, bval)) { tkey.set(Integer.toString(r.nextInt(), 36)); tval.set(Long.toString(r.nextLong(), 36)); buf.reset(bkey.getBytes(), bkey.getLength()); cmpkey.readFields(buf); buf.reset(bval.getBytes(), bval.getLength()); cmpval.readFields(buf); assertTrue("Keys don't match: " + "*" + cmpkey.toString() + ":" + tkey.toString() + "*", cmpkey.toString().equals(tkey.toString())); assertTrue("Vals don't match: " + "*" + cmpval.toString() + ":" + tval.toString() + "*", cmpval.toString().equals(tval.toString())); ++count; } } finally { reader.close(); } } assertEquals("Some records not found", RECORDS, count); }
From source file:org.apache.sysml.runtime.matrix.data.LibMatrixDatagen.java
public static long[] computeNNZperBlock(long nrow, long ncol, int brlen, int bclen, double sparsity) throws DMLRuntimeException { long lnumBlocks = (long) (Math.ceil((double) nrow / brlen) * Math.ceil((double) ncol / bclen)); //sanity check max number of blocks (before cast to avoid overflow) if (lnumBlocks > Integer.MAX_VALUE) { throw new DMLRuntimeException("A random matrix of size [" + nrow + "," + ncol + "] can not be created. " + "Number of blocks (" + lnumBlocks + ") exceeds the maximum integer size. Try to increase the block size."); }//from w w w . ja v a 2 s .co m // NOTE: Total #of NNZ is set to the expected value (nrow*ncol*sparsity). // TODO: Instead of using the expected value, NNZ should be random variable int numBlocks = (int) lnumBlocks; long nnz = (long) Math.ceil(nrow * (ncol * sparsity)); // Compute block-level NNZ long[] ret = new long[numBlocks]; if (nnz < numBlocks) { // Ultra-sparse matrix // generate the number of blocks with at least one non-zero // = a random number between [1,nnz] Random runif = new Random(System.nanoTime()); int numNZBlocks = 1; if (nnz - 1 > 0) numNZBlocks += runif.nextInt((int) (nnz - 1)); // To avoid exception from random.nextInt(0) // distribute non-zeros across numNZBlocks // compute proportions for each nzblock // - divide (0,1] interval into numNZBlocks portions of random size double[] blockNNZproportions = new double[numNZBlocks]; runif.setSeed(System.nanoTime()); for (int i = 0; i < numNZBlocks - 1; i++) { blockNNZproportions[i] = runif.nextDouble(); } blockNNZproportions[numNZBlocks - 1] = 1; // sort the values in ascending order Arrays.sort(blockNNZproportions); // compute actual number of non zeros per block according to proportions long actualnnz = 0; int bid; runif.setSeed(System.nanoTime()); for (int i = 0; i < numNZBlocks; i++) { bid = -1; do { bid = runif.nextInt(numBlocks); } while (ret[bid] != 0); double prop = (i == 0 ? blockNNZproportions[i] : (blockNNZproportions[i] - blockNNZproportions[i - 1])); ret[bid] = (long) Math.floor(prop * nnz); actualnnz += ret[bid]; } // Code to make sure exact number of non-zeros are generated while (actualnnz < nnz) { bid = runif.nextInt(numBlocks); ret[bid]++; actualnnz++; } } else { int bid = 0; for (long r = 0; r < nrow; r += brlen) { long curBlockRowSize = Math.min(brlen, (nrow - r)); for (long c = 0; c < ncol; c += bclen) { long curBlockColSize = Math.min(bclen, (ncol - c)); ret[bid] = (long) (curBlockRowSize * curBlockColSize * sparsity); bid++; } } } return ret; }
From source file:com.codefollower.lealone.omid.tso.TestLongCache.java
@Test public void testEntriesAge() { Cache cache = new LongCache(entries, 16); Random random = new Random(); long seed = random.nextLong(); LOG.info("Random seed: " + seed); random.setSeed(seed); int removals = 0; long totalAge = 0; double tempStdDev = 0; double tempAvg = 0; int i = 0;//from ww w . ja va 2s . c o m int largestDeletedTimestamp = 0; for (; i < entries * 10; ++i) { long removed = cache.set(random.nextLong(), i); if (removed > largestDeletedTimestamp) { largestDeletedTimestamp = (int) removed; } } long time = System.nanoTime(); for (; i < entries * 100; ++i) { long removed = cache.set(random.nextLong(), i); if (removed > largestDeletedTimestamp) { largestDeletedTimestamp = (int) removed; } int gap = i - ((int) largestDeletedTimestamp); removals++; totalAge += gap; double oldAvg = tempAvg; tempAvg += (gap - tempAvg) / removals; tempStdDev += (gap - oldAvg) * (gap - tempAvg); hist.add(gap); } long elapsed = System.nanoTime() - time; LOG.info("Elapsed (ms): " + (elapsed / (double) 1000)); double avgGap = totalAge / (double) removals; LOG.info("Avg gap: " + (tempAvg)); LOG.info("Std dev gap: " + Math.sqrt((tempStdDev / entries))); assertThat(avgGap, is(greaterThan(entries * .6))); }
From source file:org.alfresco.textgen.TextGenerator.java
public void generateQueries(String field, int min_fpmw, int max_fpmw, int min_words, int max_words, int count) { Random random = new Random(); random.setSeed(0); for (int j = 0; j < count; j++) { int words = min_words + random.nextInt(max_words - min_words); StringBuilder builder = new StringBuilder(); if (field != null) { builder.append(field).append(":\""); }//from ww w .j ava2s .com for (int i = 0; i < words; i++) { int fpmw = min_fpmw + random.nextInt(max_fpmw - min_fpmw); ArrayList<String> choice = wordGenerator.getWordsLessFrequent(fpmw); if (builder.length() > 0) { builder.append(" "); } builder.append(getSingleWord(choice, random)); } if (field != null) { builder.append("\""); } System.out.println(builder.toString()); } }
From source file:org.alfresco.textgen.TextGenerator.java
public String generateQueryString(long seed, int words, int wordLimit) { if (wordLimit < words) { throw new IllegalStateException(); }// ww w .jav a 2 s. c o m Random random = new Random(); random.setSeed(seed); int start = 0; if (wordLimit > words) { start = random.nextInt(wordLimit - words); } random.setSeed(seed); for (int i = 0; i < start; i++) { random.nextDouble(); } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < words; i++) { String word = wordGenerator.getWord(random.nextDouble()); if (buffer.length() > 0) { buffer.append(" "); } buffer.append(word); } return buffer.toString(); }