/** * Randomly picks the location of a new window, such that it fits completely on the screen. * * @param desktopPane the desktop pane that the frame is being added to. * @param frame the JInternalFrame which is being added. * @param desiredSize the desired dimensions of the frame. */ private static void setGoodBounds( JInternalFrame frame, JDesktopPane desktopPane, Dimension desiredSize) { RandomUtil randomUtil = RandomUtil.getInstance(); Dimension desktopSize = desktopPane.getSize(); Dimension d = new Dimension(desiredSize); int tx = desktopSize.width - d.width; int ty = desktopSize.height - d.height; if (tx < 0) { tx = 0; d.width = desktopSize.width; } else { tx = (int) (randomUtil.nextDouble() * tx); } if (ty < 0) { ty = 0; d.height = desktopSize.height; } else { ty = (int) (randomUtil.nextDouble() * ty); } frame.setBounds(tx, ty, d.width, d.height); }
public BenchmarkState() { final int max = 1 << 16; final int howmanywords = (1 << 16) / 64; int[] values1 = RandomUtil.negate(RandomUtil.generateUniformHash(rand, offvalues, max), max); int[] values2 = RandomUtil.generateUniformHash(rand, bitsetperword2 * howmanywords, max); ac1 = new BitmapContainer(); ac1 = (BitmapContainer) RandomUtil.fillMeUp(ac1, values1); ac2 = new BitmapContainer(); ac2 = (BitmapContainer) RandomUtil.fillMeUp(ac2, values2); }
/** @return the probability associated with the most recently computed independence test. */ public double getPValue() { if (!Double.isNaN(this.pValue)) { return Double.NaN; } else { return 2.0 * (1.0 - RandomUtil.getInstance().normalCdf(0, 1, Math.abs(fisherZ))); } }
public long getRandomTimeStamp() { // subtract 1 so that 0 is allowed lastTimeStamp += RandomUtil.gaussianAsPositiveInt( random, AVERAGE_MILLIS_INCREMENT, STD_DEV_FOR_MILLIS_INCREMENT) - 1; return lastTimeStamp; }
/** * It validates a Bean (POJO) using simple setters and getters with random values. You can pass a * list of properties to be ignored, as some properties will have a pre-defined domain (not being * possible to use random-values on them) */ protected void validateGettersAndSetters(final Object pojo, final String... ignoredProperties) throws Exception { HashSet<String> ignoreSet = new HashSet<String>(); for (String ignore : ignoredProperties) { ignoreSet.add(ignore); } BeanInfo info = Introspector.getBeanInfo(pojo.getClass()); PropertyDescriptor properties[] = info.getPropertyDescriptors(); for (PropertyDescriptor prop : properties) { Object value; if (prop.getPropertyType() == String.class) { value = RandomUtil.randomString(); } else if (prop.getPropertyType() == Integer.class || prop.getPropertyType() == Integer.TYPE) { value = RandomUtil.randomInt(); } else if (prop.getPropertyType() == Long.class || prop.getPropertyType() == Long.TYPE) { value = RandomUtil.randomLong(); } else if (prop.getPropertyType() == Boolean.class || prop.getPropertyType() == Boolean.TYPE) { value = RandomUtil.randomBoolean(); } else if (prop.getPropertyType() == Double.class || prop.getPropertyType() == Double.TYPE) { value = RandomUtil.randomDouble(); } else { System.out.println( "Can't validate property of type " + prop.getPropertyType() + " on " + prop.getName()); value = null; } if (value != null && prop.getWriteMethod() != null && prop.getReadMethod() == null) { System.out.println("WriteOnly property " + prop.getName() + " on " + pojo.getClass()); } else if (value != null & prop.getWriteMethod() != null && prop.getReadMethod() != null && !ignoreSet.contains(prop.getName())) { System.out.println("Validating " + prop.getName() + " type = " + prop.getPropertyType()); prop.getWriteMethod().invoke(pojo, value); Assert.assertEquals("Property " + prop.getName(), value, prop.getReadMethod().invoke(pojo)); } } }
/* * Demonstraton and self test of class */ public static void main(String args[]) { /*for (int i=0; i< 2; i++) { RandomGUID myGUID = new RandomGUID(false); System.out.println("Seeding String=" + myGUID.valueBeforeMD5); System.out.println("rawGUID=" + myGUID.valueAfterMD5); System.out.println("RandomGUID=" + myGUID.toString()); }*/ System.out.println(RandomUtil.generateNumString(10)); }
private String makeRandomLoggerName() { int parts = RandomUtil.gaussianAsPositiveInt( random, AVERAGE_LOGGER_NAME_PARTS, STD_DEV_FOR_LOGGER_NAME_PARTS); StringBuilder sb = new StringBuilder(); for (int i = 1; i < parts; i++) { sb.append(getRandomJavaIdentifier()).append('.'); } sb.append(getRandomJavaIdentifier()); return sb.toString(); }
/** * Generates a pseudorandom country. * * @return Half the time, USA; otherwise, a random string. */ public String country() { String country = "USA"; int toggle = this._random.random(0, 1); if (toggle == 0) { StringBuilder buffer = new StringBuilder(255); country = RandomUtil.randomName(this._random, buffer, 6, 16).toString(); } return country; }
/** * Generates the first line of a pseudorandom street address. * * @return A random street address. */ public String street1() { StringBuilder buffer = new StringBuilder(255); buffer.append(this._random.makeNString(1, 5)).append(' '); // Number RandomUtil.randomName(this._random, buffer, 1, 11); // Street Name String[] STREETEXTS = {"Blvd", "Ave", "St", "Ln", ""}; String streetExt = STREETEXTS[this._random.random(0, STREETEXTS.length - 1)]; if (streetExt.length() > 0) { buffer.append(' ').append(streetExt); } return buffer.toString(); }
/** * @param connectorConfigs * @return */ protected ArrayList<String> registerConnectors( final HornetQServer server, final List<TransportConfiguration> connectorConfigs) { // The connectors need to be pre-configured at main config object but this method is taking // TransportConfigurations directly // So this will first register them at the config and then generate a list of objects ArrayList<String> connectors = new ArrayList<String>(); for (TransportConfiguration tnsp : connectorConfigs) { String name = RandomUtil.randomString(); server.getConfiguration().getConnectorConfigurations().put(name, tnsp); connectors.add(name); } return connectors; }
/** * 对xml消息加密 * * @param appId 应用ID * @param encodingAesKey 加密密钥 * @param xmlContent 原始消息体 * @return aes加密后的消息体 * @throws WeixinException */ public static String aesEncrypt(String appId, String encodingAesKey, String xmlContent) throws WeixinException { byte[] randomBytes = StringUtil.getBytesUtf8(RandomUtil.generateString(32)); byte[] xmlBytes = StringUtil.getBytesUtf8(xmlContent); int xmlLength = xmlBytes.length; byte[] orderBytes = new byte[4]; orderBytes[3] = (byte) (xmlLength & 0xFF); orderBytes[2] = (byte) (xmlLength >> 8 & 0xFF); orderBytes[1] = (byte) (xmlLength >> 16 & 0xFF); orderBytes[0] = (byte) (xmlLength >> 24 & 0xFF); byte[] appidBytes = StringUtil.getBytesUtf8(appId); int byteLength = randomBytes.length + xmlLength + orderBytes.length + appidBytes.length; // ... + pad: 使用自定义的填充方式对明文进行补位填充 byte[] padBytes = PKCS7Encoder.encode(byteLength); // random + endian + xml + appid + pad 获得最终的字节流 byte[] unencrypted = new byte[byteLength + padBytes.length]; byteLength = 0; // src:源数组;srcPos:源数组要复制的起始位置;dest:目的数组;destPos:目的数组放置的起始位置;length:复制的长度 System.arraycopy(randomBytes, 0, unencrypted, byteLength, randomBytes.length); byteLength += randomBytes.length; System.arraycopy(orderBytes, 0, unencrypted, byteLength, orderBytes.length); byteLength += orderBytes.length; System.arraycopy(xmlBytes, 0, unencrypted, byteLength, xmlBytes.length); byteLength += xmlBytes.length; System.arraycopy(appidBytes, 0, unencrypted, byteLength, appidBytes.length); byteLength += appidBytes.length; System.arraycopy(padBytes, 0, unencrypted, byteLength, padBytes.length); try { byte[] aesKey = Base64.decodeBase64(encodingAesKey + "="); // 设置加密模式为AES的CBC模式 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, Consts.AES); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); // 加密 byte[] encrypted = cipher.doFinal(unencrypted); // 使用BASE64对加密后的字符串进行编码 return Base64.encodeBase64String(encrypted); } catch (Exception e) { throw new WeixinException("-40006", "AES加密失败:" + e.getMessage()); } }
private MessageArgumentTuple makeRandomMessageArgumentTuple() { int numOfArguments = getNumberOfMessageArguments(); int wordCount = RandomUtil.gaussianAsPositiveInt(random, AVERAGE_MESSAGE_WORDS, STD_DEV_FOR_MESSAGE_WORDS); String[] wordArray = getRandomWords(wordCount); int[] anchorPositions = getRandomAnchorPositions(wordCount, numOfArguments); for (int anchorIndex : anchorPositions) { wordArray[anchorIndex] = "{}"; } StringBuilder sb = new StringBuilder(); for (int i = 1; i < wordCount; i++) { sb.append(wordArray[i]).append(' '); } sb.append(getRandomWord()); return new MessageArgumentTuple(sb.toString(), numOfArguments); }
/** * Takes a Cholesky decomposition from the Cholesky.cholesky method and a set of data simulated * using the information in that matrix. Written by Don Crimbchin. Modified June 8, Matt * Easterday: added a random # seed so that data can be recalculated with the same result in * Causality lab * * @param cholesky the result from cholesky above. * @param randomUtil a random number generator, if null the method will make a new generator for * each random number needed * @return an array the same length as the width or length (cholesky should have the same width * and length) containing a randomly generate data set. */ private double[] exogenousData(TetradMatrix cholesky, RandomUtil randomUtil) { // Step 1. Generate normal samples. double exoData[] = new double[cholesky.rows()]; for (int i = 0; i < exoData.length; i++) { exoData[i] = randomUtil.nextNormal(0, 1); } // Step 2. Multiply by cholesky to get correct covariance. double point[] = new double[exoData.length]; for (int i = 0; i < exoData.length; i++) { double sum = 0.0; for (int j = 0; j <= i; j++) { sum += cholesky.get(i, j) * exoData[j]; } point[i] = sum; } return point; }
/** * @param sampleSize The sample size of the desired data set. * @param latentDataSaved True if latent variables should be included in the data set. * @return This returns a standardized data set simulated from the model, using the reduced form * method. */ public DataSet simulateDataReducedForm(int sampleSize, boolean latentDataSaved) { int numVars = getVariableNodes().size(); // Calculate inv(I - edgeCoef) TetradMatrix edgeCoef = edgeCoef().copy().transpose(); // TetradMatrix iMinusB = TetradAlgebra.identity(edgeCoef.rows()); // iMinusB.assign(edgeCoef, Functions.minus); TetradMatrix iMinusB = TetradAlgebra.identity(edgeCoef.rows()).minus(edgeCoef); TetradMatrix inv = iMinusB.inverse(); // Pick error values e, for each calculate inv * e. TetradMatrix sim = new TetradMatrix(sampleSize, numVars); // Generate error data with the right variances and covariances, then override this // with error data for varaibles that have special distributions defined. Not ideal, // but not sure what else to do at the moment. It's better than not taking covariances // into account! TetradMatrix cholesky = MatrixUtils.choleskyC(errCovar(errorVariances())); for (int i = 0; i < sampleSize; i++) { TetradVector e = new TetradVector(exogenousData(cholesky, RandomUtil.getInstance())); TetradVector ePrime = inv.times(e); sim.assignRow(i, ePrime); // sim.viewRow(i).assign(ePrime); } DataSet fullDataSet = ColtDataSet.makeContinuousData(getVariableNodes(), sim); if (latentDataSaved) { return fullDataSet; } else { return DataUtils.restrictToMeasured(fullDataSet); } }
private void resolveOneEdgeMax(Graph graph, Node x, Node y, boolean strong, Graph oldGraph) { if (RandomUtil.getInstance().nextDouble() > 0.5) { Node temp = x; x = y; y = temp; } TetradLogger.getInstance().log("info", "\nEDGE " + x + " --- " + y); SortedMap<Double, String> scoreReports = new TreeMap<Double, String>(); List<Node> neighborsx = graph.getAdjacentNodes(x); neighborsx.remove(y); double max = Double.NEGATIVE_INFINITY; boolean left = false; boolean right = false; DepthChoiceGenerator genx = new DepthChoiceGenerator(neighborsx.size(), neighborsx.size()); int[] choicex; while ((choicex = genx.next()) != null) { List<Node> condxMinus = GraphUtils.asList(choicex, neighborsx); List<Node> condxPlus = new ArrayList<Node>(condxMinus); condxPlus.add(y); double xPlus = score(x, condxPlus); double xMinus = score(x, condxMinus); List<Node> neighborsy = graph.getAdjacentNodes(y); neighborsy.remove(x); DepthChoiceGenerator geny = new DepthChoiceGenerator(neighborsy.size(), neighborsy.size()); int[] choicey; while ((choicey = geny.next()) != null) { List<Node> condyMinus = GraphUtils.asList(choicey, neighborsy); // List<Node> parentsY = oldGraph.getParents(y); // parentsY.remove(x); // if (!condyMinus.containsAll(parentsY)) { // continue; // } List<Node> condyPlus = new ArrayList<Node>(condyMinus); condyPlus.add(x); double yPlus = score(y, condyPlus); double yMinus = score(y, condyMinus); // Checking them all at once is expensive but avoids lexical ordering problems in the // algorithm. if (normal(y, condyPlus) || normal(x, condxMinus) || normal(x, condxPlus) || normal(y, condyMinus)) { continue; } double delta = 0.0; if (strong) { if (yPlus <= xPlus + delta && xMinus <= yMinus + delta) { double score = combinedScore(xPlus, yMinus); if (yPlus <= yMinus + delta && xMinus <= xPlus + delta) { StringBuilder builder = new StringBuilder(); builder.append("\nStrong " + y + "->" + x + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); if (score > max) { max = score; left = true; right = false; } } else { StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge " + x + "--" + y + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); } } else if (xPlus <= yPlus + delta && yMinus <= xMinus + delta) { double score = combinedScore(yPlus, xMinus); if (yMinus <= yPlus + delta && xPlus <= xMinus + delta) { StringBuilder builder = new StringBuilder(); builder.append("\nStrong " + x + "->" + y + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); if (score > max) { max = score; left = false; right = true; } } else { StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge " + x + "--" + y + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); } } else if (yPlus <= xPlus + delta && yMinus <= xMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge " + x + "--" + y + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); } else if (xPlus <= yPlus + delta && xMinus <= yMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge " + x + "--" + y + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); } } else { if (yPlus <= xPlus + delta && xMinus <= yMinus + delta) { double score = combinedScore(xPlus, yMinus); StringBuilder builder = new StringBuilder(); builder.append("\nWeak " + y + "->" + x + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); if (score > max) { max = score; left = true; right = false; } } else if (xPlus <= yPlus + delta && yMinus <= xMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nWeak " + x + "->" + y + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); if (score > max) { max = score; left = false; right = true; } } else if (yPlus <= xPlus + delta && yMinus <= xMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge " + x + "--" + y + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); } else if (xPlus <= yPlus + delta && xMinus <= yMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge " + x + "--" + y + " " + score); builder.append("\n Parents(" + x + ") = " + condxMinus); builder.append("\n Parents(" + y + ") = " + condyMinus); scoreReports.put(-score, builder.toString()); } } } } for (double score : scoreReports.keySet()) { TetradLogger.getInstance().log("info", scoreReports.get(score)); } graph.removeEdges(x, y); if (left) { graph.addDirectedEdge(y, x); } if (right) { graph.addDirectedEdge(x, y); } if (!graph.isAdjacentTo(x, y)) { graph.addUndirectedEdge(x, y); } }
public static void main(String[] args) { RandomUtil ru = new RandomUtil(); for (int i = 0; i < 10; i++) { System.out.println(ru.getRandomString(6)); } }
@Override public String nextValue() { return Integer.toString(RandomUtil.getInstance().getUnsignedInt(Short.MAX_VALUE)); }