List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:com.oltpbenchmark.benchmarks.seats.SEATSWorker.java
/** * Execute the FindOpenSeat procedure// ww w . j a v a 2 s . co m * @throws SQLException */ private boolean executeFindOpenSeats(FindOpenSeats proc) throws SQLException { final FlightId search_flight = this.profile.getRandomFlightId(); assert (search_flight != null); Long airport_depart_id = search_flight.getDepartAirportId(); if (LOG.isTraceEnabled()) LOG.trace("Calling " + proc); Object[][] results = proc.run(conn, search_flight.encode()); conn.commit(); int rowCount = results.length; assert (rowCount <= SEATSConstants.FLIGHTS_NUM_SEATS) : String .format("Unexpected %d open seats returned for %s", rowCount, search_flight); // there is some tiny probability of an empty flight .. maybe 1/(20**150) // if you hit this assert (with valid code), play the lottery! if (rowCount == 0) return (true); LinkedList<Reservation> cache = CACHE_RESERVATIONS.get(CacheType.PENDING_INSERTS); assert (cache != null) : "Unexpected " + CacheType.PENDING_INSERTS; // Store pending reservations in our queue for a later transaction BitSet seats = getSeatsBitSet(search_flight); tmp_reservations.clear(); for (Object row[] : results) { if (row == null) continue; // || rng.nextInt(100) < 75) continue; // HACK Integer seatnum = (Integer) row[1]; // We first try to get a CustomerId based at this departure airport if (LOG.isTraceEnabled()) LOG.trace("Looking for a random customer to fly on " + search_flight); CustomerId customer_id = profile.getRandomCustomerId(airport_depart_id); // We will go for a random one if: // (1) The Customer is already booked on this Flight // (2) We already made a new Reservation just now for this Customer int tries = SEATSConstants.FLIGHTS_NUM_SEATS; while (tries-- > 0 && (customer_id == null)) { // || isCustomerBookedOnFlight(customer_id, flight_id))) { customer_id = profile.getRandomCustomerId(); if (LOG.isTraceEnabled()) LOG.trace("RANDOM CUSTOMER: " + customer_id); } // WHILE assert (customer_id != null) : String.format( "Failed to find a unique Customer to reserve for seat #%d on %s", seatnum, search_flight); Reservation r = new Reservation(profile.getNextReservationId(getId()), search_flight, customer_id, seatnum.intValue()); seats.set(seatnum); tmp_reservations.add(r); if (LOG.isTraceEnabled()) LOG.trace( "QUEUED INSERT: " + search_flight + " / " + search_flight.encode() + " -> " + customer_id); } // WHILE if (tmp_reservations.isEmpty() == false) { Collections.shuffle(tmp_reservations); cache.addAll(tmp_reservations); while (cache.size() > SEATSConstants.CACHE_LIMIT_PENDING_INSERTS) { cache.remove(); } // WHILE if (LOG.isDebugEnabled()) LOG.debug(String.format("Stored %d pending inserts for %s [totalPendingInserts=%d]", tmp_reservations.size(), search_flight, cache.size())); } return (true); }
From source file:com.pinterest.teletraan.worker.HealthChecker.java
public void processBatch() throws Exception { List<HealthCheckBean> healthCheckBeans = healthCheckDAO.getOngoingHealthChecks(); if (healthCheckBeans.isEmpty()) { return;//w ww .ja v a 2 s . c o m } Collections.shuffle(healthCheckBeans); for (HealthCheckBean bean : healthCheckBeans) { LOG.info("Start to process health check {} ", bean.toString()); String lockName = String.format("HEALTHCHECK-%s", bean.getId()); Connection connection = utilDAO.getLock(lockName); if (connection != null) { try { processHealthCheck(bean); } catch (Exception ex) { LOG.error("Failed to process health check {}", bean.toString(), ex); } finally { utilDAO.releaseLock(lockName, connection); } } else { LOG.warn(String.format("Failed to get lock: %s", lockName)); } } }
From source file:net.semanticmetadata.lire.solr.FastLireRequestHandler.java
private BooleanQuery createQuery(int[] hashes, String paramField, double size) { List<Integer> hList = new ArrayList<Integer>(hashes.length); for (int i = 0; i < hashes.length; i++) { hList.add(hashes[i]);/*from ww w . j av a2s .co m*/ } Collections.shuffle(hList); BooleanQuery query = new BooleanQuery(); int numHashes = (int) Math.min(hashes.length, Math.floor(hashes.length * size)); // a minimum of 3 hashes ... if (numHashes < 3) numHashes = 3; for (int i = 0; i < numHashes; i++) { // be aware that the hashFunctionsFileName of the field must match the one you put the hashes in before. query.add(new BooleanClause(new TermQuery(new Term(paramField, Integer.toHexString(hashes[i]))), BooleanClause.Occur.SHOULD)); } // this query is just for boosting the results with more matching hashes. We'd need to match it to all docs. // query.add(new BooleanClause(new MatchAllDocsQuery(), BooleanClause.Occur.SHOULD)); return query; }
From source file:edu.cmu.tetrad.search.IndTestMultiFisherZ2.java
private int countGreater2(List<Node> aa, List<Node> bb, List<Node> cc, int perm, double obs) { Node x = new ContinuousVariable("X"); Node y = new ContinuousVariable("Y"); Node z = new ContinuousVariable("Z"); int count = 0; List<Node> all = new ArrayList<Node>(); for (int i = 0; i < aa.size() + bb.size() + cc.size(); i++) { all.add(new ContinuousVariable("X" + i)); }//from ww w. ja v a 2 s . com Graph graph = new EdgeListGraph(all); SemPm pm = new SemPm(graph); SemIm im = new SemIm(pm); for (int i = 0; i < aa.size() + bb.size() + cc.size(); i++) { double var = this.cov.getValue(i, i); Node semNode = all.get(i); im.setErrCovar(semNode, var); } DataSet data = im.simulateData(cov.getSampleSize(), false); CovarianceMatrix cov = new CovarianceMatrix(data); double[] k_ = new double[perm]; for (int c = 0; c < perm; c++) { List<Integer> indices = new ArrayList<Integer>(); for (int j = 0; j < cov.getDimension(); j++) { indices.add(j); } Collections.shuffle(indices); Map<Node, List<Node>> nodeMap = new HashMap<Node, List<Node>>(); List<Node> _nodes = cov.getVariables(); int _count = 0; List<Node> nx = new ArrayList<Node>(); for (int k = 0; k < aa.size(); k++) { nx.add(_nodes.get(indices.get(_count++))); } nodeMap.put(x, nx); List<Node> ny = new ArrayList<Node>(); for (int k = 0; k < bb.size(); k++) { ny.add(_nodes.get(indices.get(_count++))); } nodeMap.put(y, ny); List<Node> nz = new ArrayList<Node>(); for (int k = 0; k < cc.size(); k++) { nz.add(_nodes.get(indices.get(_count++))); } nodeMap.put(z, nz); TetradMatrix submatrix = subMatrix(cov, nx, ny, nz); TetradMatrix inverse; int rank; try { inverse = submatrix.inverse(); rank = inverse.columns(); } catch (Exception e) { System.out.println("Couldn't invert " + submatrix.columns()); throw new IllegalArgumentException(); } List<Double> pValues = new ArrayList<Double>(); for (int i = 0; i < nx.size(); i++) { for (int m = 0; m < ny.size(); m++) { int j = nx.size() + m; double a = -1.0 * inverse.get(i, j); double v0 = inverse.get(i, i); double v1 = inverse.get(j, j); double b = Math.sqrt(v0 * v1); double r = a / b; int dof = cov.getSampleSize() - 1 - rank; if (dof < 0) { System.out.println("Negative dof: " + dof + " n = " + cov.getSampleSize() + " cols = " + inverse.columns()); dof = 0; } double _z = Math.sqrt(dof) * 0.5 * (Math.log(1.0 + r) - Math.log(1.0 - r)); double p = 2.0 * (1.0 - RandomUtil.getInstance().normalCdf(0, 1, abs(_z))); pValues.add(p); } } int k = 0; for (double p : pValues) { if (p < alpha) k++; } k_[c] = k; // System.out.println(k + " " + obs); if (k_[c] > obs) { count++; } } return count; }
From source file:edu.cmu.tetrad.bayes.MlBayesIm.java
private void randomizeTable2(int nodeIndex) { boolean existsIncomplete = true; for (int rowIndex = 0; rowIndex < getNumRows(nodeIndex); rowIndex++) { if (isIncomplete(nodeIndex, rowIndex)) { existsIncomplete = true;// w w w . j a v a2 s. com break; } } if (!existsIncomplete) return; // Trying for some more power ..jdramsey 5/7/10 List<Integer> rowIndices = new ArrayList<Integer>(); for (int i = 0; i < getNumRows(nodeIndex); i++) { rowIndices.add(i); } Collections.shuffle(rowIndices); randomizeRow(nodeIndex, rowIndices.get(0)); double[][] values = new double[getNumRows(nodeIndex)][getNumColumns(nodeIndex)]; for (int row = 0; row < getNumRows(nodeIndex); row++) { double bestNorm = 0.0; for (int trial = 0; trial < 100; trial++) { randomizeRow(nodeIndex, rowIndices.get(row)); double totalNorm = 0.0; for (int _row = row - 1; _row < row; _row++) { double norm = norm(nodeIndex, rowIndices.get(row), rowIndices.get(_row)); totalNorm += norm; } if (totalNorm > bestNorm) { bestNorm = totalNorm; for (int _row = 0; _row < getNumRows(nodeIndex); _row++) { for (int col = 0; col < getNumColumns(nodeIndex); col++) { values[_row][col] = getProbability(nodeIndex, _row, col); } } } } for (int _row = 0; _row < getNumRows(nodeIndex); _row++) { for (int col = 0; col < getNumColumns(nodeIndex); col++) { setProbability(nodeIndex, _row, col, values[_row][col]); } } } }
From source file:edu.cornell.med.icb.goby.modes.TestDiscoverSequenceVariantsMode.java
private String[] shuffle(String[] strings) { final ObjectArrayList<String> list = ObjectArrayList.wrap(strings); Collections.shuffle(list); return list.toArray(new String[list.size()]); }
From source file:com.rovemonteux.silvertunnel.netlib.layer.tor.directory.Directory.java
private AuthorityKeyCertificates getAuthorityKeyCertificates() { // get now+1 day final Date now = new Date(); final Date minValidUntil = new Date(now.getTime() + ONE_DAY_IN_MS); if (authorityKeyCertificates == null) { // loading is needed - try to load authority key certificates from // cache first LOG.debug("getAuthorityKeyCertificates(): try to load from local cache ..."); final String authorityKeyCertificatesStr = stringStorage.get(STORAGEKEY_AUTHORITY_KEY_CERTIFICATES_TXT); if (authorityKeyCertificatesStr != null && authorityKeyCertificatesStr.length() > MIN_LENGTH_OF_AUTHORITY_KEY_CERTS_STR) { // parse loaded result try { final AuthorityKeyCertificates newAuthorityKeyCertificates = new AuthorityKeyCertificates( authorityKeyCertificatesStr, minValidUntil); // no exception thrown: certificates are OK if (newAuthorityKeyCertificates.isValid(minValidUntil)) { LOG.debug("getAuthorityKeyCertificates(): successfully loaded from local cache"); authorityKeyCertificates = newAuthorityKeyCertificates; return authorityKeyCertificates; } else { // do not use outdated or invalid certificates from // local cache LOG.debug(//from w w w .j av a2 s. c o m "getAuthorityKeyCertificates(): loaded from local cache - but not valid: try (re)load from remote site now"); } } catch (final TorException e) { LOG.warn( "getAuthorityKeyCertificates(): could not parse from local cache: try (re)load from remote site now", e); } } else { LOG.debug("getAuthorityKeyCertificates(): no data in cache: try (re)load from remote site now"); } } if (authorityKeyCertificates == null || !authorityKeyCertificates.isValid(minValidUntil)) { // (re)load is needed LOG.debug("getAuthorityKeyCertificates(): load and parse authorityKeyCertificates..."); final List<String> authServerIpAndPorts = new ArrayList<String>( AuthorityServers.getAuthorityIpAndPorts()); Collections.shuffle(authServerIpAndPorts); String httpResponse = null; for (final String authServerIpAndPort : authServerIpAndPorts) { // download authority key certificates try { final TcpipNetAddress hostAndPort = new TcpipNetAddress(authServerIpAndPort); final String path = "/tor/keys/all"; try { httpResponse = SimpleHttpClientCompressed.getInstance().get(lowerDirConnectionNetLayer, hostAndPort, path); } catch (ZipException e) { LOG.debug("got ZipException trying to get data uncompressed"); httpResponse = SimpleHttpClient.getInstance().get(lowerDirConnectionNetLayer, hostAndPort, path); } // parse loaded result final AuthorityKeyCertificates newAuthorityKeyCertificates = new AuthorityKeyCertificates( httpResponse, minValidUntil); // no exception thrown: certificates are OK if (newAuthorityKeyCertificates.isValid(minValidUntil)) { LOG.debug("getAuthorityKeyCertificates(): successfully loaded from {}", authServerIpAndPort); // save in cache stringStorage.put(STORAGEKEY_AUTHORITY_KEY_CERTIFICATES_TXT, httpResponse); // use as result authorityKeyCertificates = newAuthorityKeyCertificates; return authorityKeyCertificates; } else { LOG.debug("getAuthorityKeyCertificates(): loaded from {} - but not valid: try next", authServerIpAndPort); } } catch (final TorException e) { LOG.warn("getAuthorityKeyCertificates(): could not parse from " + authServerIpAndPort + " result=" + httpResponse + ", try next", e); } catch (final Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("getAuthorityKeyCertificates(): error while loading from {}, try next", authServerIpAndPort, e); } } } LOG.error("getAuthorityKeyCertificates(): could NOT load and parse authorityKeyCertificates"); // use outdated certificates if no newer could be retrieved } return authorityKeyCertificates; }
From source file:com.opengamma.masterdb.security.SecurityTestCase.java
protected static <T> List<T> getTestObjects(final Class<T> clazz, final Class<?> parent) { final List<T> objects = new ArrayList<T>(); if (clazz.isEnum()) { for (final T value : clazz.getEnumConstants()) { objects.add(value);//from w ww .jav a 2 s .c o m } } else { final Object key; if (Collection.class.equals(clazz)) { key = Pair.of(parent, clazz); } else if (List.class.equals(clazz)) { key = Pair.of(parent, clazz); } else { key = clazz; } final TestDataProvider<T> provider = (TestDataProvider<T>) s_dataProviders.get(key); if (provider == null) { throw new IllegalArgumentException("No random provider for " + clazz); } provider.getValues(objects); } Collections.shuffle(objects); return objects; }
From source file:edu.cmu.tetrad.search.IndTestMultiFisherZ2.java
private int countGreater3(List<Node> aa, List<Node> bb, List<Node> cc, int perm, int obs, TetradMatrix submatrix, TetradMatrix inverse) { List<Integer> nx2 = new ArrayList<Integer>(); int count2 = 0; for (int k = 0; k < aa.size(); k++) { nx2.add(count2++);//from w w w . j av a 2s. c o m } List<Integer> ny2 = new ArrayList<Integer>(); for (int k = 0; k < bb.size(); k++) { ny2.add(count2++); } List<Double> p2 = new ArrayList<Double>(); for (int i : nx2) { for (int j : ny2) { double a = -1.0 * inverse.get(i, j); double v0 = inverse.get(i, i); double v1 = inverse.get(j, j); double b = Math.sqrt(v0 * v1); double r = a / b; int dof = cov.getSampleSize() - 1 - submatrix.columns(); if (dof < 0) { throw new IllegalArgumentException("Negative dof: " + dof + " n = " + cov.getSampleSize() + " cols = " + inverse.columns()); } double _z = Math.sqrt(dof) * 0.5 * (Math.log(1.0 + r) - Math.log(1.0 - r)); double p = 2.0 * (1.0 - RandomUtil.getInstance().normalCdf(0, 1, abs(_z))); p2.add(p); } } int obs2 = 0; for (double p : p2) { if (p < alpha) obs2++; } int count = 0; double[] K = new double[perm]; for (int c = 0; c < perm; c++) { List<Integer> indices = new ArrayList<Integer>(); for (int j = 0; j < submatrix.columns(); j++) { indices.add(j); } Collections.shuffle(indices); int _count = 0; List<Integer> nx = new ArrayList<Integer>(); for (int k = 0; k < aa.size(); k++) { nx.add(indices.get(_count++)); } List<Integer> ny = new ArrayList<Integer>(); for (int k = 0; k < bb.size(); k++) { ny.add(indices.get(_count++)); } List<Double> pValues = new ArrayList<Double>(); for (int i : nx) { for (int j : ny) { double a = -1.0 * inverse.get(i, j); double v0 = inverse.get(i, i); double v1 = inverse.get(j, j); double b = Math.sqrt(v0 * v1); double r = a / b; int dof = cov.getSampleSize() - 1 - submatrix.columns(); if (dof < 0) { throw new IllegalArgumentException("Negative dof: " + dof + " n = " + cov.getSampleSize() + " cols = " + inverse.columns()); } double _z = Math.sqrt(dof) * 0.5 * (Math.log(1.0 + r) - Math.log(1.0 - r)); double p = 2.0 * (1.0 - RandomUtil.getInstance().normalCdf(0, 1, abs(_z))); pValues.add(p); } } int k = 0; for (double p : pValues) { if (p < alpha) k++; } K[c] = k; System.out.println(k + " >? " + obs2); if (K[c] > obs2) { count++; } } return count; }
From source file:com.yougou.api.service.impl.ApiKeyServiceImpl.java
@Override @Transactional/* w w w . ja v a2 s. co m*/ public ApiKey saveGenerateKey(String userName, String merchantCode) { // ? String appKey = new java.rmi.server.UID().toString().replaceAll("(:|-)", "_"); // ?? List<String> appSecretSections = Arrays.asList(appKey.split("")); Collections.shuffle(appSecretSections); String appSecret = MD5Encryptor.encrypt(appSecretSections.toString()); ApiKey apiKey = new ApiKey(); apiKey.setId(UUIDUtil.getUUID()); apiKey.setAppKey(appKey); apiKey.setAppSecret(appSecret); apiKey.setStatus(ApiKeyStatus.DISABLE); apiKey.setUpdateTime(DateUtil.format(new Date(), "yyyy-MM-dd hh:mm:ss")); apiKey.setUpdateUser(StringUtils.isEmpty(merchantCode) ? userName : merchantCode); Map<String, List<Object[]>> sqlBatchs = new LinkedHashMap<String, List<Object[]>>(); String sql = "insert into tbl_merchant_api_key(id, app_key, app_secret,status,update_user,update_time)" + " values(?, ?, ?,?, ?, ?)"; List<Object[]> sqlParams = new ArrayList<Object[]>(); sqlParams.add(new Object[] { apiKey.getId(), appKey, appSecret, 1, StringUtils.isEmpty(merchantCode) ? userName : merchantCode, DateUtil.format(new Date(), "yyyy-MM-dd hh:mm:ss") }); sqlBatchs.put(sql, sqlParams); boolean result = JDBCUtils.getInstance().executeBatch(sqlBatchs); if (result) { logger.info(" app key ? appkeyId:" + apiKey.getAppKey()); MerchantOperationLog operationLog = new MerchantOperationLog(); operationLog.setId(UUIDUtil.getUUID()); operationLog.setMerchantCode(appKey); operationLog.setOperated(new Date()); operationLog.setOperationNotes("appkey"); operationLog.setOperationType(OperationType.AppKey_ADD); operationLog.setOperator(userName); merchantOperationLogService.saveMerchantOperationLog(operationLog); } // try { // //saveApiKey(new ApiKey[]{apiKey}); // //apiKeyDao.save(apiKey); // //System.out.println(a); // } catch (Exception e) { // logger.error(e); // // } return apiKey; }