List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:edu.cmu.tetrad.search.IndTestMultiFisherZ2.java
private int countGreater4(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; int numPermutations = perm; double[] k_ = new double[numPermutations]; for (int c = 0; c < numPermutations; c++) { List<Integer> indices = new ArrayList<Integer>(); int numVars = aa.size() + bb.size() + cc.size(); for (int j = 0; j < numVars; j++) { indices.add(j);//from w w w. j a v a 2s. c o m } 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++; } } double mean = StatUtils.mean(k_); double sd = StatUtils.sd(k_); List<Double> ret = new ArrayList<Double>(); ret.add(mean); ret.add(sd); return count; }
From source file:com.evolveum.midpoint.model.common.stringpolicy.ValuePolicyProcessor.java
private String generateAttempt(ValuePolicyType policy, int defaultLength, boolean generateMinimalSize, Context ctx, OperationResult result) { StringPolicyType stringPolicy = policy.getStringPolicy(); // if (policy.getLimitations() != null && // policy.getLimitations().getMinLength() != null){ // generateMinimalSize = true; // }//from ww w . j a va2 s . c o m // setup default values where missing // PasswordPolicyUtils.normalize(pp); // Optimize usage of limits ass hashmap of limitas and key is set of // valid chars for each limitation Map<StringLimitType, List<String>> lims = new HashMap<>(); int minLen = defaultLength; int maxLen = defaultLength; int unique = defaultLength / 2; if (stringPolicy != null) { for (StringLimitType l : stringPolicy.getLimitations().getLimit()) { if (null != l.getCharacterClass().getValue()) { lims.put(l, StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue())); } else { lims.put(l, StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass( stringPolicy.getCharacterClass(), l.getCharacterClass().getRef()))); } } // Get global limitations minLen = defaultIfNull(stringPolicy.getLimitations().getMinLength(), 0); if (minLen != 0 && minLen > defaultLength) { defaultLength = minLen; } maxLen = defaultIfNull(stringPolicy.getLimitations().getMaxLength(), 0); unique = defaultIfNull(stringPolicy.getLimitations().getMinUniqueChars(), minLen); } // test correctness of definition if (unique > minLen) { minLen = unique; OperationResult reportBug = new OperationResult("Global limitation check"); reportBug.recordWarning( "There is more required unique characters then defined minimum. Raise minimum to number of required unique chars."); } if (minLen == 0 && maxLen == 0) { minLen = defaultLength; maxLen = defaultLength; generateMinimalSize = true; } if (maxLen == 0) { if (minLen > defaultLength) { maxLen = minLen; } else { maxLen = defaultLength; } } // Initialize generator StringBuilder password = new StringBuilder(); /* * ********************************** Try to find best characters to be * first in password */ Map<StringLimitType, List<String>> mustBeFirst = new HashMap<>(); for (Map.Entry<StringLimitType, List<String>> entry : lims.entrySet()) { final StringLimitType key = entry.getKey(); if (key.isMustBeFirst() != null && key.isMustBeFirst()) { mustBeFirst.put(key, entry.getValue()); } } // If any limitation was found to be first if (!mustBeFirst.isEmpty()) { Map<Integer, List<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false, false, result); int intersectionCardinality = mustBeFirst.keySet().size(); List<String> intersectionCharacters = posibleFirstChars.get(intersectionCardinality); // If no intersection was found then raise error if (null == intersectionCharacters || intersectionCharacters.size() == 0) { result.recordFatalError("No intersection for required first character sets in value policy:" + stringPolicy.getDescription()); // Log error if (LOGGER.isErrorEnabled()) { LOGGER.error("Unable to generate value for " + ctx.path + ": No intersection for required first character sets in value policy: [" + stringPolicy.getDescription() + "] following character limitation and sets are used:"); for (StringLimitType l : mustBeFirst.keySet()) { StrBuilder tmp = new StrBuilder(); tmp.appendSeparator(", "); tmp.appendAll(mustBeFirst.get(l)); LOGGER.error("L:" + l.getDescription() + " -> [" + tmp + "]"); } } // No more processing unrecoverable conflict return null; // EXIT } else { if (LOGGER.isDebugEnabled()) { StrBuilder tmp = new StrBuilder(); tmp.appendSeparator(", "); tmp.appendAll(intersectionCharacters); LOGGER.trace( "Generate first character intersection items [" + tmp + "] into " + ctx.path + "."); } // Generate random char into password from intersection password.append(intersectionCharacters.get(RAND.nextInt(intersectionCharacters.size()))); } } /* * ************************************** Generate rest to fulfill * minimal criteria */ boolean uniquenessReached = false; // Count cardinality of elements Map<Integer, List<String>> chars; for (int i = 0; i < minLen; i++) { // Check if still unique chars are needed if (password.length() >= unique) { uniquenessReached = true; } // Find all usable characters chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), false, uniquenessReached, result); // If something goes badly then go out if (null == chars) { return null; } if (chars.isEmpty()) { LOGGER.trace("Minimal criterias was met. No more characters"); break; } // Find lowest possible cardinality and then generate char for (int card = 1; card < lims.keySet().size(); card++) { if (chars.containsKey(card)) { List<String> validChars = chars.get(card); password.append(validChars.get(RAND.nextInt(validChars.size()))); break; } } } // test if maximum is not exceeded if (password.length() > maxLen) { result.recordFatalError( "Unable to meet minimal criteria and not exceed maximal size of " + ctx.path + "."); return null; } /* * *************************************** Generate chars to not exceed * maximal */ for (int i = 0; i < minLen; i++) { // test if max is reached if (password.length() == maxLen) { // no more characters maximal size is reached break; } if (password.length() >= minLen && generateMinimalSize) { // no more characters are needed break; } // Check if still unique chars are needed if (password.length() >= unique) { uniquenessReached = true; } // find all usable characters chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), true, uniquenessReached, result); // If something goes badly then go out if (null == chars) { // we hope this never happend. result.recordFatalError("No valid characters to generate, but no all limitation are reached"); return null; } // if selection is empty then no more characters and we can close // our work if (chars.isEmpty()) { if (i == 0) { password.append(RandomStringUtils.randomAlphanumeric(minLen)); } break; // if (!StringUtils.isBlank(password.toString()) && // password.length() >= minLen) { // break; // } // check uf this is a firs cycle and if we need to user some // default (alphanum) character class. } // Find lowest possible cardinality and then generate char for (int card = 1; card <= lims.keySet().size(); card++) { if (chars.containsKey(card)) { List<String> validChars = chars.get(card); password.append(validChars.get(RAND.nextInt(validChars.size()))); break; } } } if (password.length() < minLen) { result.recordFatalError("Unable to generate value for " + ctx.path + " and meet minimal size of " + ctx.path + ". Actual length: " + password.length() + ", required: " + minLen); LOGGER.trace("Unable to generate value for " + ctx.path + " and meet minimal size of " + ctx.path + ". Actual length: {}, required: {}", password.length(), minLen); return null; } result.recordSuccess(); // Shuffle output to solve pattern like output StrBuilder sb = new StrBuilder(password.substring(0, 1)); List<String> shuffleBuffer = StringPolicyUtils.stringTokenizer(password.substring(1)); Collections.shuffle(shuffleBuffer); sb.appendAll(shuffleBuffer); return sb.toString(); }
From source file:TPPDekuBot.BattleBot.java
@Override public void onMessage(Channel channel, User sender, String message) { append(sender.getNick() + ": " + message); if (sender.getNick().equalsIgnoreCase("the_chef1337") && message.toLowerCase().startsWith("!sendrawline ")) { String line = message.split(" ", 2)[1]; this.sendRawLine(line); return;/* w w w. j ava 2 s .c o m*/ } //banlist goes here for simplicity if (sender.getNick().equalsIgnoreCase("trainertimmy") || sender.getNick().equalsIgnoreCase("trainertimmybot") || sender.getNick().equalsIgnoreCase("pikabowser2082") || sender.getNick().equalsIgnoreCase("wallbot303")) { return; } if (sender.getNick().equalsIgnoreCase("minhs2") || sender.getNick().equalsIgnoreCase("minhs3")) { return; } //end banlist //System.out.println(DekuBot.getDateTime() + " " + sender + ": " + message); while (Character.isWhitespace(message.charAt(0)) && message.length() > 2) { message = message.substring(1); } if (message.length() < 2) { return; } if (sender.getNick().equalsIgnoreCase("Minhs2") && message.toLowerCase().startsWith("!battle bigbrother")) { this.sendMessage(channel.getChannelName(), longMessage("FUNgineer")); return; } if ((message.toLowerCase().startsWith("!accept")) && (waitingPlayer || waitingPWT) && sender.getNick().equalsIgnoreCase(waitingOn)) { try { player.put(sender.getNick()); } catch (Exception ex) { } } if ((message.toLowerCase().startsWith("!changeclass ") || message.toLowerCase().startsWith("!switchclass ")) && !isInBattle()) { if (isForcedClass(sender.getNick())) { this.sendMessage(channel, "@" + sender.getNick() + " You cannot change your Trainer Class."); return; } String newClass = message.split(" ", 2)[1]; if (newClass.length() > 19) { newClass = newClass.substring(0, 19); } if (newClass.isEmpty()) { this.sendMessage(channel.getChannelName(), "@" + sender.getNick() + " Invalid Trainer Class FUNgineer"); return; } while (Character.isWhitespace(newClass.charAt(0))) { newClass = newClass.substring(1); } while (newClass.contains(" ")) { newClass = newClass.replace(" ", " "); newClass = newClass.trim(); } if (!isPureAscii(newClass)) { this.sendMessage(channel.getChannelName(), "@" + sender.getNick() + " Invalid Trainer Class FUNgineer"); return; } if (newClass.toLowerCase().contains("gym leader") || newClass.toLowerCase().contains("leader") || newClass.toLowerCase().contains("champion") || newClass.toLowerCase().contains("elite four") || (newClass.toLowerCase().charAt(0) == '/' || newClass.toLowerCase().charAt(0) == '.' || !Character.isLetter(newClass.toLowerCase().charAt(0))) || containsBannedChar(newClass)) { this.sendMessage(channel.getChannelName(), "@" + sender.getNick() + " Invalid Trainer Class FUNgineer"); return; } //if (Trainer.isValidTrainerClass(newClass)) { HashMap<String, String> classes = new HashMap<>(); try (FileInputStream f = new FileInputStream(BASE_PATH + "/trainerclasses.wdu"); ObjectInputStream o = new ObjectInputStream(f)) { classes = (HashMap<String, String>) o.readObject(); } catch (Exception ex) { System.err.println("[ERROR] Error reading classes file! " + ex); return; } classes.put(sender.getNick().toLowerCase(), newClass); try (FileOutputStream f = new FileOutputStream(BASE_PATH + "/trainerclasses.wdu"); ObjectOutputStream o = new ObjectOutputStream(f)) { o.writeObject(classes); } catch (Exception ex) { System.err.println("[ERROR] Error writing new classes file! " + ex); return; } this.sendMessage(channel.getChannelName(), "@" + sender.getNick() + " updated your Trainer Class to " + newClass + "!"); //} else { // this.sendMessage(channel.getChannelName(), "@" + sender + " Invalid Trainer Class. FUNgineer For a list of valid classes, go here: http://pastebin.com/raw.php?i=rhA55Dd0"); //} return; } if (isInBattle() && battle instanceof MultiplayerBattle) { MultiplayerBattle mpB = (MultiplayerBattle) battle; if (message.toLowerCase().startsWith("!run") || (message.toLowerCase().startsWith("!switch") && message.length() >= 8 && Character.isDigit(message.charAt(7))) || Move.isValidMove(message)) { if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) { try { mpB.p1msg.put(message); } catch (Exception ex) { } } if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) { try { mpB.p2msg.put(message); } catch (Exception ex) { } } } if (message.toLowerCase().startsWith("!list")) { if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) { try { String pokemon = mpB.player1.getPokemonList(); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Your pokemon are: " + pokemon); } catch (Exception ex) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " You have no other Pokemon in your party!"); } } else if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) { try { String pokemon = mpB.player2.getPokemonList(); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Your pokemon are: " + pokemon); } catch (Exception ex) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " You have no other Pokemon in your party!"); } } return; } if (message.toLowerCase().startsWith("!check") && message.length() >= 7 && Character.isDigit(message.charAt(6))) { int check = Integer.parseInt(message.charAt(6) + ""); if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) { Pokemon p = mpB.player1.getPokemon(check); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1() + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): " + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: " + p.getMove1().getName() + ", " + p.getMove2().getName() + ", " + p.getMove3().getName() + ", " + p.getMove4().getName()); } else if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) { Pokemon p = mpB.player2.getPokemon(check); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1() + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): " + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: " + p.getMove1().getName() + ", " + p.getMove2().getName() + ", " + p.getMove3().getName() + ", " + p.getMove4().getName()); } } if (message.toLowerCase().startsWith("!help") && (isInBattle() && battle instanceof MultiplayerBattle) && (sender.getNick().equalsIgnoreCase(mpB.getPlayer1()) || sender.getNick().equalsIgnoreCase(mpB.getPlayer2()))) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Type !list to see a list of your Pokemon. Type !checkx where x is the number of the Pokemon from !list to see it's moves. Type !switchx where x is number of the Pokemon from !list to switch to a Pokemon."); } } if (isInBattle() && battle instanceof PWTBattle) { PWTBattle mpB = (PWTBattle) battle; if (message.toLowerCase().startsWith("!run") || (message.toLowerCase().startsWith("!switch") && message.length() >= 8 && Character.isDigit(message.charAt(7))) || Move.isValidMove(message)) { if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) { try { mpB.p1msg.put(message); } catch (Exception ex) { } } if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) { try { mpB.p2msg.put(message); } catch (Exception ex) { } } } if (message.toLowerCase().startsWith("!list")) { if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) { try { String pokemon = mpB.player1.getPokemonList(); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Your pokemon are: " + pokemon); } catch (Exception ex) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " You have no other Pokemon in your party!"); } } else if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) { try { String pokemon = mpB.player2.getPokemonList(); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Your pokemon are: " + pokemon); } catch (Exception ex) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " You have no other Pokemon in your party!"); } } return; } if (message.toLowerCase().startsWith("!check") && message.length() >= 7 && Character.isDigit(message.charAt(6))) { int check = Integer.parseInt(message.charAt(6) + ""); if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) { Pokemon p = mpB.player1.getPokemon(check); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1() + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): " + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: " + p.getMove1().getName() + ", " + p.getMove2().getName() + ", " + p.getMove3().getName() + ", " + p.getMove4().getName()); } else if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) { Pokemon p = mpB.player2.getPokemon(check); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1() + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): " + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: " + p.getMove1().getName() + ", " + p.getMove2().getName() + ", " + p.getMove3().getName() + ", " + p.getMove4().getName()); } } if (message.toLowerCase().startsWith("!help") && (isInBattle() && battle instanceof PWTBattle) && (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) || sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Type !list to see a list of your Pokemon. Type !checkx where x is the number of the Pokemon from !list to see it's moves. Type !switchx where x is number of the Pokemon from !list to switch to a Pokemon."); } } if (isInBattle() && battle instanceof SafariBattle) { SafariBattle sB = (SafariBattle) battle; if (sender.getNick().equalsIgnoreCase(sB.user.getTrainerName())) { if (message.toLowerCase().startsWith("!rock") || message.toLowerCase().startsWith("!bait") || message.toLowerCase().startsWith("!ball") || message.toLowerCase().startsWith("!run")) { if (this.getOutgoingQueueSize() == 0) { sB.msg.add(message.split(" ", 2)[0].toLowerCase()); } } } } if (!isInBattle() && !waitingPlayer && !waitingPWT) { if (message.startsWith("!safari")) { Thread t = new Thread(() -> { int level = new SecureRandom().nextInt(100 - 20 + 1) + 20; int id = new SecureRandom().nextInt(718 - 1 + 1) + 1; System.err.println("Attempting Pokemon ID " + id + " level " + level); SafariBattle sB = new SafariBattle(this, sender.getNick(), new Pokemon(id, level)); battle = sB; sB.doBattle(this, channel.getChannelName()); System.err.println("Now out of Safari Battle"); battle = null; }); t.start(); } } if (!isInBattle() && !waitingPlayer && !waitingPWT) { if (message.startsWith("!pwt")) { this.sendMessage(channel, sender.getNick() + " has started a new Random Pokemon World Tournament! Type !join to join. The PWT will start in 60 seconds."); //this.sendMessage(channel,"Debug mode for PWT activated, wait 60 sec"); pwtQueue.add(sender.getNick().toLowerCase()); music.play(new File(ROOT_PATH + "\\pwt\\pwt-lobby.mp3")); waitingPWT = true; Thread t = new Thread(() -> { try { ArrayList<Trainer> randoms = new ArrayList<>(); Thread tet = new Thread(() -> { outer: while (waitingPWT) { Trainer rand = PWTournament.generateTrainer(PWTType.RANDOM, PWTClass.NORMAL); if (randoms.isEmpty()) { randoms.add(rand); System.err.println("Added " + rand + " " + rand.getPokemon()); continue; } for (Trainer el : randoms) { if (el.getTrainerName().equalsIgnoreCase(rand.getTrainerName())) { continue outer; } } randoms.add(rand); System.err.println("Added " + rand + " " + rand.getPokemon()); } }); tet.start(); Thread.sleep(60000); // while (randoms.size() < 7) { // outer: // while (waitingPWT) { // Trainer rand = PWTournament.generateTrainer(PWTType.RANDOM, PWTClass.NORMAL); // if (randoms.isEmpty()) { // randoms.add(rand); // System.err.println("Added " + rand + " " + rand.getPokemon()); // continue; // } // for (Trainer el : randoms) { // if (el.getTrainerName().equalsIgnoreCase(rand.getTrainerName())) { // continue outer; // } // } // randoms.add(rand); // System.err.println("Added " + rand + " " + rand.getPokemon()); // } // } waitingPWT = false; inPWT = true; this.sendMessage(channel, "The " + PWTType.RANDOM + " Pokemon World Tournament is starting! Stand by while I generate Pokemon... the first match will begin soon!"); ArrayList<Trainer> pwtList = new ArrayList<>(); for (String el : pwtQueue) { ArrayList<Pokemon> p = Trainer.generatePokemon(3, 50); Trainer te = new Trainer(el, Trainer.getTrainerClass(el), Region.getRandomRegion(), p, false); pwtList.add(te); } Collections.shuffle(pwtList); PWTournament pwt = new PWTournament(PWTType.RANDOM, PWTClass.NORMAL, pwtList, randoms); pwt.arrangeBracket(); pwt.doTourney(this, channel.getChannelName()); pwtQueue = new ArrayList<>(); waitingPWT = false; inPWT = false; } catch (Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```An error occurred in the PWT!!\n" + sw.toString() + "```"); pwtQueue = new ArrayList<>(); waitingPWT = false; inPWT = false; } }); t.start(); } } if (!isInBattle() && waitingPWT) { if (message.toLowerCase().startsWith("!join") && pwtQueue.size() < 4) { if (!pwtQueue.contains(sender.getNick().toLowerCase())) { pwtQueue.add(sender.getNick().toLowerCase()); this.sendMessage(channel, sender.getNick() + " has been added to the PWT! Type !join to join."); return; } } } if (message.toLowerCase().startsWith("!help") && !isInBattle()) { this.sendMessage(channel.getChannelName(), "https://github.com/robomaeyhem/WowBattleBot (scroll down to see the Readme)"); } if (message.toLowerCase().startsWith("!randbat @") || message.toLowerCase().startsWith("!randombattle @")) { if (isInBattle() || waitingPlayer || waitingPWT) { return; } //if ((message.toLowerCase().startsWith("!challenge @") || message.toLowerCase().startsWith("!multibattle @")) && !inMultiBattle && !inPokemonBattle && !inSafariBattle) { final String messageFinal = message; Thread t = new Thread(() -> { try { String target = messageFinal.split("@", 2)[1].split(" ", 2)[0]; if (target.isEmpty() || target.contains("/") || target.contains(".")) { this.sendMessage(channel, "FUNgineer"); return; } int pkmAmt = 1; try { pkmAmt = Integer.parseInt(messageFinal.split("@", 2)[1].split(" ", 2)[1].split(" ", 2)[0]); } catch (Exception ex2) { pkmAmt = 1; } if (pkmAmt < 1) { pkmAmt = 1; } if (pkmAmt > 6) { pkmAmt = 6; } if (target.equalsIgnoreCase(sender.getNick())) { this.sendMessage(channel.getChannelName(), "You cannot challenge yourself FUNgineer"); return; } if (target.equalsIgnoreCase("frunky5") || target.equalsIgnoreCase("23forces") || target.equalsIgnoreCase("groudonger")) { } else if (target.equalsIgnoreCase("wow_deku_onehand") || target.equalsIgnoreCase("wow_battlebot_onehand") || User.isBot(target) || target.equalsIgnoreCase("killermapper")) { this.sendMessage(channel.getChannelName(), "FUNgineer"); return; } if (!waitingPlayer) { waitingPlayer = true; waitingOn = target; this.sendMessage(channel.getChannelName(), "Challenging " + target + "..."); int level = new SecureRandom().nextInt(100 - 20 + 1) + 20; while (level < 20) { level = new SecureRandom().nextInt(100 - 20 + 1) + 20; } boolean isHere = false; for (User el : this.getUsers(channel.getChannelName())) { if (target.equalsIgnoreCase(el.getNick())) { isHere = true; break; } } if (!isHere) { append(sender.getNick() + " SENDING INVITE"); BattleBot.sendAnInvite(target, "_keredau_1423645868201", oAuth); } this.sendWhisper(target, "You have been challenged to a Pokemon Battle by " + sender.getNick() + "! To accept, go to the Battle Dungeon and type !accept. You have one minute."); String player2 = player.poll(60, TimeUnit.SECONDS); if (player2 == null) { this.sendMessage(channel.getChannelName(), target + " did not respond to the challenge BibleThump"); waitingPlayer = false; waitingOn = ""; return; } waitingPlayer = false; waitingOn = ""; this.sendMessage(channel.getChannelName(), "Generating Pokemon, give me a minute..."); System.err.println("Going into Multiplayer Battle"); MultiplayerBattle mpB = new MultiplayerBattle(this, sender.getNick(), target, level, pkmAmt); battle = mpB; mpB.doBattle(channel.getChannelName()); battle = null; System.err.println("Now out of Multiplayer Battle"); } } catch (Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```" + sw.toString() + "\n```"); waitingPlayer = false; battle = null; } }); t.start(); } if (message.toLowerCase().startsWith("!test ") && sender.getNick().equalsIgnoreCase("the_chef1337")) { String test = message.toLowerCase().split("!test ", 2)[1].split(" ", 2)[0]; if (!test.equalsIgnoreCase("pwt") && !Character.isDigit(message.charAt(6))) { final String senderFinal = "the_chef1337"; Thread t = new Thread(() -> { try { pokemonMessages = new LinkedBlockingQueue<>(); personInBattle = senderFinal; System.err.println("Going into Pokemon Battle"); PokemonBattle a = new PokemonBattle(this, channel.getChannelName(), false, false, sender.getNick(), true); System.err.println("Now out of Pokemon Battle"); pokemonMessages = new LinkedBlockingQueue<>(); personInBattle = ""; battle = null; } catch (Exception ex) { personInBattle = ""; pokemonMessages = new LinkedBlockingQueue<>(); this.sendMessage(channel.getChannelName(), "Something fucked up OneHand this battle is now over both Pokemon exploded violently KAPOW"); System.err.println("[POKEMON] Uh oh " + ex); ex.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```" + sw.toString() + "```"); battle = null; } }); t.start(); } else if (message.toLowerCase().split("!test ", 2)[1].split(" ", 2)[0].equalsIgnoreCase("pwt")) { Trainer t = new Trainer("Cynthia", "Sinnoh Champion", Region.SINNOH, Trainer.generatePokemon(3, 50), true); Trainer m = new Trainer("23forces", "Elite Four", Region.getRandomRegion(), Trainer.generatePokemon(3, 50), true); //String name, String trnClass, Region region, ArrayList<Pokemon> pokemon, boolean ai this.sendMessage(channel, PWTRound.FIRST_ROUND.getText() + "match of the " + PWTType.RANDOM + " tournament! This match is between " + t + " and " + m + "!"); PWTBattle b = new PWTBattle(this, m, t, PWTType.RANDOM, PWTClass.NORMAL, PWTRound.FIRST_ROUND); battle = b; Thread th = new Thread(() -> { try { this.music.play(PWTBattle.determineMusic(b)); b.doBattle(channel.getChannelName()); battle = null; } catch (Exception ex) { ex.printStackTrace(); } }); th.start(); } else { final int finalId = Integer.parseInt(message.split("!test ", 2)[1].split(" ", 2)[0]); Thread t = new Thread(() -> { int level = new SecureRandom().nextInt(100 - 20 + 1) + 20; int id = finalId; System.err.println("Attempting Pokemon ID " + id + " level " + level); SafariBattle sB = new SafariBattle(this, sender.getNick(), new Pokemon(id, level)); battle = sB; sB.doBattle(this, channel.getChannelName()); System.err.println("Now out of Safari Battle"); battle = null; }); t.start(); } } if (message.toLowerCase().startsWith("!battle") && !waitingPlayer && !waitingPWT && !isInBattle()) { boolean bigbrother = false, fromChef = false; if (message.contains("BigBrother") || sender.getNick().equalsIgnoreCase("dewgong98") || sender.getNick().equalsIgnoreCase("mad_king98") || sender.getNick().equalsIgnoreCase("Starmiewaifu")) { bigbrother = true; if (sender.getNick().equalsIgnoreCase("the_chef1337")) { fromChef = true; } } final boolean bbrother = bigbrother; final boolean fChef = fromChef; if (sender.getNick().equalsIgnoreCase("twitchplaysleaderboard")) { return; } else { final String senderFinal = sender.getNick(); if (!isInBattle() && !waitingPlayer && !waitingPWT) { Thread t = new Thread(() -> { try { pokemonMessages = new LinkedBlockingQueue<>(); personInBattle = senderFinal; System.err.println("Going into Pokemon Battle"); PokemonBattle a = new PokemonBattle(this, channel.getChannelName(), bbrother, fChef, sender.getNick(), false); System.err.println("Now out of Pokemon Battle"); pokemonMessages = new LinkedBlockingQueue<>(); personInBattle = ""; battle = null; } catch (Exception ex) { personInBattle = ""; pokemonMessages = new LinkedBlockingQueue<>(); this.sendMessage(channel.getChannelName(), "Something fucked up OneHand this battle is now over both Pokemon exploded violently KAPOW"); System.err.println("[POKEMON] Uh oh " + ex); ex.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```" + sw.toString() + "```"); battle = null; } }); t.start(); } } } if (message.toLowerCase().startsWith("!run")) { if (!channel.getChannelName().equals("#_keredau_1423645868201")) { return; } if (isInBattle() && battle instanceof PokemonBattle) { if (sender.getNick().equalsIgnoreCase(personInBattle)) { // if (DekuBot.containsOtherChar(message)) { // this.sendMessage(channel.getChannelName(), sender + "... TriHard"); // return; // } personInBattle = ""; pokemonMessages.add("run"); } } } if (message.toLowerCase().startsWith("!move1") || message.toLowerCase().startsWith("!move2") || message.toLowerCase().startsWith("!move3") || message.toLowerCase().startsWith("!move4")) { if (sender.getNick().equalsIgnoreCase("wow_deku_onehand")) { return; } if (!channel.getChannelName().equals("#_keredau_1423645868201")) { return; } if (isInBattle() && battle instanceof PokemonBattle) { if (sender.getNick().equalsIgnoreCase(personInBattle)) { pokemonMessages.add("" + message.charAt(5)); } } } }
From source file:com.google.example.eightbitartist.DrawingActivity.java
/** * Pick a random set of words from the master word list. * @param numWords the number of words to choose. * @return a list of randomly chosen words. *//* w ww . j a v a 2s . c om*/ private List<String> getRandomWordSubset(int numWords) { List<String> result = new ArrayList<>(); Collections.addAll(result, mAllWords); Collections.shuffle(result); result = result.subList(0, numWords); return result; }
From source file:com.emc.storageos.coordinator.client.service.impl.CoordinatorClientImpl.java
@Override public List<Service> locateAllServices(String siteId, String name, String version, String tag, String endpointKey) throws CoordinatorException { String serviceRoot = String.format("%1$s/%2$s", name, version); List<String> servicePaths = lookupServicePath(siteId, serviceRoot); if (servicePaths.isEmpty()) { throw CoordinatorException.retryables .cannotLocateService(String.format("%1$s/%2$s", getServicePath(siteId), serviceRoot)); }/* w w w . j a v a 2s . co m*/ // poor man's load balancing Collections.shuffle(servicePaths); List<Service> filtered = new ArrayList<Service>(servicePaths.size()); for (int i = 0; i < servicePaths.size(); i++) { String spath = servicePaths.get(i); byte[] data = getServiceData(siteId, serviceRoot, spath); if (data == null) { continue; } Service service = ServiceImpl.parse(data); if (tag != null && !service.isTagged(tag)) { continue; } if (endpointKey != null && service.getEndpoint(endpointKey) == null) { continue; } if (endpointKey == null) { // default endpoint URI endpoint = expandEndpointURI(service.getEndpoint(), siteId); ((ServiceImpl) service).setEndpoint(endpoint); } else { // swap the ip for the entry with the endpointkey in the map URI endpoint = expandEndpointURI(service.getEndpoint(endpointKey), siteId); ((ServiceImpl) service).setEndpoint(endpointKey, endpoint); } log.debug("locateAllServices->service endpoint: " + service.getEndpoint()); filtered.add(service); } return Collections.unmodifiableList(filtered); }
From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java
/** * Creates a full spatio-temporal hierarchy for a source folder * @throws ParseException /*from w w w. jav a 2 s .c o m*/ * @throws InterruptedException */ public static void directoryIndexer(final OperationsParams params) throws IOException, ParseException, InterruptedException { Path inputDir = params.getInputPath(); FileSystem sourceFs = inputDir.getFileSystem(params); final Path sourceDir = inputDir.makeQualified(sourceFs); Path destDir = params.getOutputPath(); final FileSystem destFs = destDir.getFileSystem(params); TimeRange timeRange = params.get("time") != null ? new TimeRange(params.get("time")) : null; // Create daily indexes that do not exist final Path dailyIndexDir = new Path(destDir, "daily"); FileStatus[] mathcingDays = timeRange == null ? sourceFs.listStatus(inputDir) : sourceFs.listStatus(inputDir, timeRange); final Vector<Path> sourceFiles = new Vector<Path>(); for (FileStatus matchingDay : mathcingDays) { for (FileStatus matchingTile : sourceFs.listStatus(matchingDay.getPath())) { sourceFiles.add(matchingTile.getPath()); } } // Shuffle the array for better load balancing across threads Collections.shuffle(sourceFiles); final String datasetName = params.get("dataset"); Parallel.forEach(sourceFiles.size(), new RunnableRange<Object>() { @Override public Object run(int i1, int i2) { LOG.info("Worker [" + i1 + "," + i2 + ") started"); for (int i = i1; i < i2; i++) { Path sourceFile = sourceFiles.get(i); try { Path relativeSourceFile = makeRelative(sourceDir, sourceFile); Path destFilePath = new Path(dailyIndexDir, relativeSourceFile); if (!destFs.exists(destFilePath)) { LOG.info("Worker [" + i1 + "," + i2 + ") indexing: " + sourceFile.getName()); Path tmpFile; do { tmpFile = new Path((int) (Math.random() * 1000000) + ".tmp"); } while (destFs.exists(tmpFile)); tmpFile = tmpFile.makeQualified(destFs); if (datasetName == null) throw new RuntimeException( "Please provide the name of dataset you would like to index"); AggregateQuadTree.build(params, sourceFile, datasetName, tmpFile); synchronized (destFs) { Path destDir = destFilePath.getParent(); if (!destFs.exists(destDir)) destFs.mkdirs(destDir); } destFs.rename(tmpFile, destFilePath); } } catch (IOException e) { throw new RuntimeException("Error building an index for " + sourceFile, e); } } LOG.info("Worker [" + i1 + "," + i2 + ") finished"); return null; } }); LOG.info("Done generating daily indexes"); // Merge daily indexes into monthly indexes Path monthlyIndexDir = new Path(destDir, "monthly"); final SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy.MM.dd"); final SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy.MM"); mergeIndexes(destFs, dailyIndexDir, monthlyIndexDir, dayFormat, monthFormat, params); LOG.info("Done generating monthly indexes"); // Merge daily indexes into monthly indexes Path yearlyIndexDir = new Path(destDir, "yearly"); final SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); mergeIndexes(destFs, monthlyIndexDir, yearlyIndexDir, monthFormat, yearFormat, params); LOG.info("Done generating yearly indexes"); }
From source file:de.tum.bgu.msm.syntheticPopulationGenerator.kagawa.SyntheticPopJP.java
private void assignJobs() { //Method to allocate workers at workplaces //todo. Things to consider: //If there are no more workplaces of the specific job type, the worker is sent outside the area (workplace = -2; distance = 1000 km) //Workers that also attend school are considered only as workers (educational place is not selected for them) logger.info(" Starting to assign jobs"); //Calculate distance impedance alphaJob = ResourceUtil.getDoubleProperty(rb, PROPERTIES_JOB_ALPHA); gammaJob = ResourceUtil.getDoubleProperty(rb, PROPERTIES_JOB_GAMMA); distanceImpedance = new Matrix(distanceMatrix.getRowCount(), distanceMatrix.getColumnCount()); for (int i = 1; i <= distanceMatrix.getRowCount(); i++) { for (int j = 1; j <= distanceMatrix.getColumnCount(); j++) { distanceImpedance.setValueAt(i, j, (float) Math.exp(alphaJob * Math.exp(distanceMatrix.getValueAt(i, j) * gammaJob))); }//from ww w.j a va 2s .c o m } //Identify vacant jobs and schools by zone and type identifyVacantJobsByZoneType(); //For validation - obtain the trip length distribution /* Frequency commuteDistance = new Frequency(); validationCommutersFlow(); //Generates the validation tabledatasets int[] flow = SiloUtil.createArrayWithValue(odMunicipalityFlow.getRowCount(),0); int[] flowR = SiloUtil.createArrayWithValue(odCountyFlow.getRowCount(),0); int count = 0; odMunicipalityFlow.appendColumn(flow,Integer.toString(count)); odCountyFlow.appendColumn(flowR,Integer.toString(count));*/ //Produce one array list with workers' ID Collection<Person> persons = dataContainer.getHouseholdData().getPersons(); ArrayList<Person> workerArrayList = new ArrayList<>(); for (Person person : persons) { if (person.getOccupation() == Occupation.EMPLOYED) { workerArrayList.add(person); } } //Randomize the order of the worker array list Collections.shuffle(workerArrayList); //Start the selection of the jobs in random order to avoid geographical bias logger.info(" Started assigning workplaces"); RealEstateDataManager realEstate = dataContainer.getRealEstateData(); JobDataManager jobDataManager = dataContainer.getJobData(); int assignedJobs = 0; for (Person pp : workerArrayList) { //Select the zones with vacant jobs for that person, given the job type int selectedJobType = jobTypeByWorker.get(pp) - 1; //1 Agr, 2 Ind; 3 Srv int[] keys = idZonesVacantJobsByType.get(selectedJobType); int lengthKeys = numberZonesByType.get(selectedJobType); // if there are still TAZ with vacant jobs in the region, select one of them. If not, assign them outside the area if (lengthKeys > 0) { //Select the workplace location (TAZ) for that person given his/her job type Household hh = pp.getHousehold(); int origin = realEstate.getDwelling(hh.getDwellingId()).getZoneId(); int[] workplace = selectWorkplace(origin, numberVacantJobsByZoneByType, keys, lengthKeys, distanceImpedance); //Assign last vacant jobID from the TAZ int jobID = idVacantJobsByZoneType.get(workplace[0])[numberVacantJobsByZoneByType.get(workplace[0]) - 1]; //Assign values to job and person jobDataManager.getJobFromId(jobID).setWorkerID(pp.getId()); pp.setJobTAZ(jobDataManager.getJobFromId(jobID).getZoneId()); pp.setWorkplace(jobID); //pp.setTravelTime(distanceMatrix.getValueAt(pp.getZone(), Job.getJobFromId(jobID).getZone())); //For validation OD TableDataSet /* commuteDistance.addValue((int) distanceMatrix.getValueAt(pp.getZone(), Job.getJobFromId(jobID).getZone())); int homeMun = (int) cellsMatrix.getIndexedValueAt(pp.getZone(), "smallID"); int workMun = (int) cellsMatrix.getIndexedValueAt(pp.getWorkplace(), "smallID"); int odPair = homeMun * 1000 + workMun; odMunicipalityFlow.setIndexedValueAt(odPair,Integer.toString(count),odMunicipalityFlow.getIndexedValueAt(odPair,Integer.toString(count))+ 1); homeMun = (int) cellsMatrix.getIndexedValueAt(pp.getZone(), "smallCenter"); workMun = (int) cellsMatrix.getIndexedValueAt(pp.getWorkplace(), "smallCenter"); odPair = homeMun * 1000 + workMun; odCountyFlow.setIndexedValueAt(odPair,Integer.toString(count),odCountyFlow.getIndexedValueAt(odPair,Integer.toString(count))+ 1); */ //Update counts of vacant jobs numberVacantJobsByZoneByType.put(workplace[0], numberVacantJobsByZoneByType.get(workplace[0]) - 1); numberVacantJobsByType.put(selectedJobType, numberVacantJobsByType.get(selectedJobType) - 1); if (numberVacantJobsByZoneByType.get(workplace[0]) < 1) { keys[workplace[1]] = keys[numberZonesByType.get(selectedJobType) - 1]; idZonesVacantJobsByType.put(selectedJobType, keys); numberZonesByType.put(selectedJobType, numberZonesByType.get(selectedJobType) - 1); if (numberZonesByType.get(selectedJobType) < 1) { int w = 0; while (w < jobStringTypes.length & selectedJobType > jobIntTypes.get(jobStringTypes[w])) { w++; } jobIntTypes.remove(jobStringTypes[w]); jobStringTypes[w] = jobStringTypes[jobStringTypes.length - 1]; jobStringTypes = SiloUtil.removeOneElementFromZeroBasedArray(jobStringTypes, jobStringTypes.length - 1); } } //logger.info(" Job " + assignedJobs + " assigned at " + workplace[0]); assignedJobs++; } else { //No more vacant jobs in the study area. This person will work outside the study area pp.setWorkplace(-2); //pp.setTravelTime(1000); logger.info(" No more jobs available of " + selectedJobType + " class. Person " + pp.getId() + " has workplace outside the study area."); } } //For validation - trip length distribution //checkTripLengthDistribution(commuteDistance, alphaJob, gammaJob, "microData/interimFiles/tripLengthDistributionWork.csv", 1); //Trip length frequency distribution //checkodMatrix(odMunicipalityFlow, alphaJob, gammaJob, count,"microData/interimFiles/odMunicipalityDifference.csv"); //SiloUtil.writeTableDataSet(odMunicipalityFlow,"microData/interimFiles/odMunicipalityFlow.csv"); //SiloUtil.writeTableDataSet(odCountyFlow,"microData/interimFiles/odRegionFlow.csv"); //count++; }
From source file:de.tor.tribes.io.DataHolder.java
/** * Should not be used to often because it is not optimized therefor * @return random Village with owner/* w w w .j a v a 2 s. c om*/ */ public Village getRandomVillageWithOwner() { List<Tribe> tribeList = new ArrayList<>(mTribes.values()); Collections.shuffle(tribeList); for (Tribe t : tribeList) { if (t.getVillages() > 0) { int rnd = (int) (Math.random() * t.getVillages()); return t.getVillageList()[rnd]; } } return null; }
From source file:fr.ritaly.dungeonmaster.ai.Creature.java
private void patrol() { if (!getType().canMove()) { // The creature can't move return;/*from w w w. j a va 2 s.c o m*/ } // The creature can move. Where will it go ? // What are the candidate targets ? final List<Element> surroundingElements = getElement().getSurroundingElements(); // Filter out the position already occupied for (Iterator<Element> it = surroundingElements.iterator(); it.hasNext();) { final Element element = it.next(); if (!element.isTraversable(this)) { // The creature can't traverse this position, skip it it.remove(); continue; } if (element.hasParty()) { // There are champions on this position, skip it it.remove(); continue; } if (!element.canHost(this)) { // There's not enough room left on this element, skip it it.remove(); continue; } if (Element.Type.STAIRS.equals(element.getType())) { if (!canTakeStairs()) { // This creature can't use stairs, skip this element it.remove(); continue; } } else if (Element.Type.TELEPORTER.equals(element.getType())) { if (!canTeleport()) { // This creature can't use teleports, skip this element it.remove(); continue; } } else if (Element.Type.PIT.equals(element.getType())) { // It's a pit, can the creature jump into it (if open) ? // FIXME Implement this use case throw new UnsupportedOperationException("Use case not yet implemented"); } } if (surroundingElements.isEmpty()) { // The creature can't move as there are no more candidate positions left // FIXME Teleport the creature ? return; } // FIXME Randomly change the creature's direction. Prefer the direction pointing towards the party // FIXME Can the creature physically move to the identified target ? It could be blocked by another creature in front if (State.IDLE.equals(getState())) { // Switch to the PATROLLING state setState(State.PATROLLING); } // Toss a random position Collections.shuffle(surroundingElements); final Element startElement = getElement(); final Element endElement = surroundingElements.iterator().next(); // Identify the direction when moving from the start to the end element final Direction directionTowardsTarget = getElement().getPosition() .getDirectionTowards(endElement.getPosition()); // The creature leaves the current position (event fired) startElement.removeCreature(this); if (!getDirection().equals(directionTowardsTarget)) { // Change the creature's direction consistently with the move setDirection(directionTowardsTarget); } // The creature arrives on the end position endElement.addCreature(this); // The creature can't move for a given number of clock ticks resetMoveTimer(); }
From source file:de.tum.bgu.msm.syntheticPopulationGenerator.kagawa.SyntheticPopJP.java
private void assignSchools() { //method to assign the school location for students. They should be registered on the microdata as students //todo. Things to consider: //The location of the school is stored under "schoolplace location" //Students from Berufschule are considered to be working full-time and therefore they don't attend class //If there are no more school places for the student, they are sent outside the area (schoolplace = -2) //For the following years, we school transition should be accomplished int count = 0; //Calculate distance impedance for students double alphaUniversity = ResourceUtil.getDoubleProperty(rb, PROPERTIES_UNIVERSITY_ALPHA); double gammaUniversity = ResourceUtil.getDoubleProperty(rb, PROPERTIES_UNIVERSITY_GAMMA); Matrix universityDistanceImpedance = new Matrix(distanceMatrix.getRowCount(), distanceMatrix.getColumnCount()); Matrix schoolDistanceImpedance = new Matrix(distanceMatrix.getRowCount(), distanceMatrix.getColumnCount()); for (int i = 1; i <= distanceMatrix.getRowCount(); i++) { for (int j = 1; j <= distanceMatrix.getColumnCount(); j++) { universityDistanceImpedance.setValueAt(i, j, (float) Math .exp(alphaUniversity * Math.exp(distanceMatrix.getValueAt(i, j) * gammaUniversity))); schoolDistanceImpedance.setValueAt(i, j, distanceMatrix.getValueAt(i, j)); }//from w w w . j a va 2 s .c o m } //Identify vacant schools by zone and type identifyVacantSchoolsByZoneByType(); /*//For validation - obtain the trip length distribution Frequency travelSecondary = new Frequency(); Frequency travelUniversity = new Frequency(); Frequency travelPrimary = new Frequency(); validationCommutersFlow(); //Generates the validation tabledatasets int[] flow = SiloUtil.createArrayWithValue(odMunicipalityFlow.getRowCount(),0); odMunicipalityFlow.appendColumn(flow,Integer.toString(count)); */ //Produce one array list with students' ID Collection<Person> persons = dataContainer.getHouseholdData().getPersons(); ArrayList<Person> studentArrayList = new ArrayList<>(); int[] studentsByType2 = new int[schoolTypes.length]; for (Person person : persons) { if (person.getSchoolType() > 0) { //They are studying studentArrayList.add(person); studentsByType2[person.getSchoolType() - 1] = studentsByType2[person.getSchoolType() - 1] + 1; } } //Randomize the order of the students Collections.shuffle(studentArrayList); //Start the selection of schools in random order to avoid geographical bias logger.info(" Started assigning schools"); RealEstateDataManager realEstate = dataContainer.getRealEstateData(); int assignedSchools = 0; int[] studentsOutside = new int[schoolTypes.length]; int[] studentsByType = new int[schoolTypes.length]; for (Person pp : studentArrayList) { //Select the zones with vacant schools for that person, given the school type int schoolType = pp.getSchoolType(); studentsByType[schoolType - 1] = studentsByType[schoolType - 1] + 1; int[] keys = idZonesVacantSchoolsByType.get(schoolType); int lengthKeys = numberZonesWithVacantSchoolsByType.get(schoolType); if (lengthKeys > 0) {//if there are still TAZ with school capacity in the region, select one of them. If not, assign them outside the area //Select the school location (which raster cell) for that person given his/her job type int[] schoolPlace = new int[2]; Household hh = pp.getHousehold(); int origin = realEstate.getDwelling(hh.getDwellingId()).getZoneId(); if (schoolType == 3) { schoolPlace = selectWorkplace(origin, numberVacantSchoolsByZoneByType, keys, lengthKeys, universityDistanceImpedance); //travelUniversity.addValue((int) distanceMatrix.getValueAt(origin, schoolPlace[0] / 100)); } else { schoolPlace = selectClosestSchool(origin, numberVacantSchoolsByZoneByType, keys, lengthKeys, schoolDistanceImpedance); if (schoolType == 1) { //travelPrimary.addValue((int) distanceMatrix.getValueAt(origin,schoolPlace[0] / 100)); } else if (schoolType == 2) { //travelSecondary.addValue((int) distanceMatrix.getValueAt(origin, schoolPlace[0] / 100)); } } //Assign values to job and person pp.setSchoolPlace(schoolPlace[0] / 100); //pp.setTravelTime(distanceMatrix.getValueAt(pp.getZone(), pp.getSchoolPlace())); /* //For validation OD TableDataSet int homeMun = (int) cellsMatrix.getIndexedValueAt(origin, "smallID"); int workMun = (int) cellsMatrix.getIndexedValueAt(pp.getSchoolPlace(), "smallID"); int odPair = homeMun * 1000 + workMun; odMunicipalityFlow.setIndexedValueAt(odPair,Integer.toString(count),odMunicipalityFlow.getIndexedValueAt(odPair,Integer.toString(count))+ 1); */ //Update counts of vacant school places numberVacantSchoolsByZoneByType.put(schoolPlace[0], numberVacantSchoolsByZoneByType.get(schoolPlace[0]) - 1); if (numberVacantSchoolsByZoneByType.get(schoolPlace[0]) < 1) { numberVacantSchoolsByZoneByType.put(schoolPlace[0], 0); keys[schoolPlace[1]] = keys[numberZonesWithVacantSchoolsByType.get(schoolType) - 1]; idZonesVacantSchoolsByType.put(schoolType, keys); numberZonesWithVacantSchoolsByType.put(schoolType, numberZonesWithVacantSchoolsByType.get(schoolType) - 1); if (numberZonesWithVacantSchoolsByType.get(schoolType) < 1) { numberZonesWithVacantSchoolsByType.put(schoolType, 0); } } assignedSchools++; } else {//No more school capacity in the study area. This person will study outside the area pp.setSchoolPlace(-2); //they attend one school out of the area studentsOutside[schoolType - 1] = studentsOutside[schoolType - 1] + 1; } } //For validation - trip length distribution /*checkTripLengthDistribution(travelPrimary, 0, 0, "microData/interimFiles/tripLengthDistributionPrimary.csv", 1); checkTripLengthDistribution(travelSecondary, 0, 0, "microData/interimFiles/tripLengthDistributionSecondary.csv", 1); //Trip length frequency distribution checkTripLengthDistribution(travelUniversity, alphaJob, gammaJob, "microData/interimFiles/tripLengthDistributionUniversity.csv", 1);*/ //SiloUtil.writeTableDataSet(odMunicipalityFlow,"microData/interimFiles/odMunicipalityFlow.csv"); for (int i = 0; i < schoolTypes.length; i++) { logger.info(" School type: " + schoolTypes[i] + ". " + studentsOutside[schoolTypes[i] - 1] + " students out of " + studentsByType[schoolTypes[i] - 1] + " study outside the area"); } }