List of usage examples for java.util Queue add
boolean add(E e);
From source file:test.jamocha.languages.clips.BindTest.java
private static Pair<Queue<Object>, Queue<Warning>> run(final Network network, final String parserInput) throws ParseException { final SFPParser parser = new SFPParser(new StringReader(parserInput + LINE_SEPARATOR)); final SFPToCETranslator visitor = new SFPToCETranslator(network, network); final Queue<Object> values = new LinkedList<>(); while (true) { final SFPStart n = parser.Start(); if (n == null) return Pair.of(values, visitor.getWarnings()); final Object value = n.jjtAccept(visitor, null); if (null != value) { values.add(value); }// www . ja v a 2s . c o m } }
From source file:com.mohawk.webcrawler.ScriptCompiler.java
/** * * @param tokens//from w w w . j a v a2s . c o m * @param parentScope */ private static void addScope(Queue<String> tokens, Queue<? super BaseToken> parentScope) throws CompilationException { while (!tokens.isEmpty()) { String token = tokens.poll(); if ("end".equals(token) || "else".equals(token) || "elseif".equals(token)) { parentScope.add(new BaseEndScope(token)); break; } else if ("if".equals(token)) { String expression = tokens.poll(); If_Verb ifVerb = new If_Verb(); ifVerb.setExpression(expression); parentScope.add(ifVerb); addScope(tokens, ifVerb.createScope()); // check if elseif or else is defined LinkedList<BaseToken> ifScope = ifVerb.getScope(); Object elseToken = ifScope.peekLast(); if (elseToken instanceof BaseEndScope) { // remove elseif or else from if scope ifScope.pollLast(); while (elseToken instanceof BaseEndScope) { String elseStr = ((BaseEndScope) elseToken).getName(); if ("end".equals(elseStr)) break; else if ("elseif".equals(elseStr)) { String exp = tokens.poll(); ElseIf_Verb elseIfVerb = new ElseIf_Verb(); elseIfVerb.setExpression(exp); ifVerb.addElseIf(elseIfVerb); addScope(tokens, elseIfVerb.createScope()); elseToken = elseIfVerb.getScope().pollLast(); } else if ("else".equals(elseStr)) { Else_Verb elseVerb = new Else_Verb(); ifVerb.setElse(elseVerb); addScope(tokens, elseVerb.createScope()); elseToken = elseVerb.getScope().pollLast(); } } } } else if ("while".equals(token)) { String evaluation = tokens.poll(); While_Verb whileVerb = new While_Verb(); whileVerb.setExpression(evaluation); parentScope.add(whileVerb); addScope(tokens, whileVerb.createScope()); } else if (LangCore.isVerb(token)) { // verb try { parentScope.add(LangCore.createVerbToken((String) token)); } catch (Exception e) { e.printStackTrace(); throw new CompilationException(e.getLocalizedMessage()); } } else if (LangCore.isLiteral(token)) { // literal try { parentScope.add(new BaseLiteral(LangCore.createLiteralObject(token))); } catch (LanguageException e) { throw new CompilationException(e.getLocalizedMessage()); } } else if (LangCore.isOperator(token)) { // operator try { parentScope.add(LangCore.createOperatorToken(token)); } catch (LanguageException e) { throw new CompilationException(e.getLocalizedMessage()); } } else // default to variable parentScope.add(new BaseVariable(token)); } }
From source file:com.foudroyantfactotum.mod.fousarchive.utility.midi.FileSupporter.java
private static void recFile(File file, Queue<File> list) { if (file.isDirectory()) { final File[] fileList = file.listFiles(); if (fileList != null) { for (final File sfile : fileList) { recFile(sfile, list);//from w w w . j a va2s. c om } } } else { if (file.getName().toLowerCase().endsWith(".mid")) { list.add(file); ++fileCount; } } }
From source file:org.xwiki.tool.xar.XARMojo.java
/** * Adds the contents of a specific directory to a queue of files. * //from w ww . j a v a 2 s . c o m * @param fileQueue the queue of files * @param sourceDir the directory to be scanned */ private static void addContentsToQueue(Queue<File> fileQueue, File sourceDir) { for (File currentFile : sourceDir.listFiles()) { fileQueue.add(currentFile); } }
From source file:com.cloudera.oryx.rdf.common.pmml.DecisionForestPMML.java
private static Segment buildTreeModel(DecisionForest forest, Map<Integer, BiMap<String, Integer>> columnToCategoryNameToIDMapping, MiningFunctionType miningFunctionType, MiningSchema miningSchema, int treeID, DecisionTree tree, InboundSettings settings) {/*from www . j av a 2s. co m*/ List<String> columnNames = settings.getColumnNames(); int targetColumn = settings.getTargetColumn(); Node root = new Node(); root.setId("r"); // Queue<Node> modelNodes = Queues.newArrayDeque(); Queue<Node> modelNodes = new ArrayDeque<Node>(); modelNodes.add(root); Queue<Pair<TreeNode, Decision>> treeNodes = new ArrayDeque<Pair<TreeNode, Decision>>(); treeNodes.add(new Pair<TreeNode, Decision>(tree.getRoot(), null)); while (!treeNodes.isEmpty()) { Pair<TreeNode, Decision> treeNodePredicate = treeNodes.remove(); Node modelNode = modelNodes.remove(); // This is the decision that got us here from the parent, if any; not the predicate at this node Predicate predicate = buildPredicate(treeNodePredicate.getSecond(), columnNames, columnToCategoryNameToIDMapping); modelNode.setPredicate(predicate); TreeNode treeNode = treeNodePredicate.getFirst(); if (treeNode.isTerminal()) { TerminalNode terminalNode = (TerminalNode) treeNode; modelNode.setRecordCount((double) terminalNode.getCount()); Prediction prediction = terminalNode.getPrediction(); if (prediction.getFeatureType() == FeatureType.CATEGORICAL) { Map<Integer, String> categoryIDToName = columnToCategoryNameToIDMapping.get(targetColumn) .inverse(); CategoricalPrediction categoricalPrediction = (CategoricalPrediction) prediction; int[] categoryCounts = categoricalPrediction.getCategoryCounts(); float[] categoryProbabilities = categoricalPrediction.getCategoryProbabilities(); for (int categoryID = 0; categoryID < categoryProbabilities.length; categoryID++) { int categoryCount = categoryCounts[categoryID]; float probability = categoryProbabilities[categoryID]; if (categoryCount > 0 && probability > 0.0f) { String categoryName = categoryIDToName.get(categoryID); ScoreDistribution distribution = new ScoreDistribution(categoryName, categoryCount); distribution.setProbability((double) probability); modelNode.getScoreDistributions().add(distribution); } } } else { NumericPrediction numericPrediction = (NumericPrediction) prediction; modelNode.setScore(Float.toString(numericPrediction.getPrediction())); } } else { DecisionNode decisionNode = (DecisionNode) treeNode; Decision decision = decisionNode.getDecision(); Node positiveModelNode = new Node(); positiveModelNode.setId(modelNode.getId() + '+'); modelNode.getNodes().add(positiveModelNode); Node negativeModelNode = new Node(); negativeModelNode.setId(modelNode.getId() + '-'); modelNode.getNodes().add(negativeModelNode); modelNode.setDefaultChild( decision.getDefaultDecision() ? positiveModelNode.getId() : negativeModelNode.getId()); modelNodes.add(positiveModelNode); modelNodes.add(negativeModelNode); treeNodes.add(new Pair<TreeNode, Decision>(decisionNode.getRight(), decision)); treeNodes.add(new Pair<TreeNode, Decision>(decisionNode.getLeft(), null)); } } TreeModel treeModel = new TreeModel(miningSchema, root, miningFunctionType); treeModel.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT); treeModel.setMissingValueStrategy(MissingValueStrategyType.DEFAULT_CHILD); Segment segment = new Segment(); segment.setId(Integer.toString(treeID)); segment.setPredicate(new True()); segment.setModel(treeModel); segment.setWeight(forest.getWeights()[treeID]); return segment; }
From source file:org.wyona.yanel.core.util.ConfigurationUtil.java
/** * Filter elements by target environment * @param configElement The config element. * @param targetEnvironment The target environment. * @return filtered configuration//from ww w .jav a 2 s. com */ public static Configuration filterEnvironment(MutableConfiguration configElement, String targetEnvironment) throws ConfigurationException { if (targetEnvironment == null) { log.debug( "No target environment configured, hence remove all elements which have a target environment attribute..."); targetEnvironment = ""; // INFO: Assuming that there are no empty target environment attributes (!), we set it to empty, such that the attribute values won't match, and hence those elements will be removed... } Configuration[] children = configElement.getChildren(); // INFO: Generate map of children with same name Map<String, Queue<Configuration>> elementsMap = new HashMap<String, Queue<Configuration>>(); for (int i = 0; i < children.length; i++) { String name = children[i].getName(); Queue<Configuration> elements; if (elementsMap.containsKey(name)) { elements = elementsMap.get(name); } else { elements = new LinkedList<Configuration>(); elementsMap.put(name, elements); } elements.add(children[i]); } for (Map.Entry<String, Queue<Configuration>> entry : elementsMap.entrySet()) { log.debug("Look at every element with the same name '" + entry.getKey() + "' we found..."); Queue<Configuration> elements = entry.getValue(); boolean targetEnvMatched = false; // INFO: Check first whether there are elements with the same that have an attribute named target-environment, because otherwise we might remove too much for (Configuration child : elements) { try { String env = child.getAttribute("target-environment"); log.debug("Element '" + child.getName() + "' has target environment attribute set: " + child.getAttribute("target-environment")); if (targetEnvironment.equals(env)) { log.debug("The target environment of the element '" + child.getName() + "' did match: " + env); if (targetEnvMatched) { log.warn("There are two elements with the same name '" + child.getName() + "' which matched the target environment: " + env); } targetEnvMatched = true; } else { log.debug("Remove element '" + child.getName() + "' with target environment attribute '" + env + "' but which did not match target environment '" + targetEnvironment + "' of system."); configElement.removeChild(child); } } catch (ConfigurationException e) { // No target-environment attribute: Exception is thrown if attribute is not set. log.debug("Element '" + child.getName() + "' has no target environment attribute set."); } } if (targetEnvMatched) { for (Configuration child : elements) { try { String env = child.getAttribute("target-environment"); if (!targetEnvironment.equals(env)) { log.warn("There should be no more element '" + child.getName() + "' where target environment attribute does not match: " + child.getAttribute("target-environment")); } } catch (ConfigurationException e) { log.debug("Remove element '" + child.getName() + "' without target environment attribute."); configElement.removeChild(child); } } } } // INFO: Filter elements recursively for (int i = 0; i < children.length; i++) { children[i] = filterEnvironment((MutableConfiguration) children[i], targetEnvironment); } return configElement; }
From source file:com.wrmsr.wava.basic.BasicLoopInfo.java
public static Set<Name> getLoopContents(Name loop, Multimap<Name, Name> inputs, Multimap<Name, Name> backEdges) { Set<Name> seen = new HashSet<>(); seen.add(loop);// w w w .j ava 2 s .c o m Queue<Name> queue = new LinkedList<>(); inputs.get(loop).stream().filter(n -> !n.equals(loop) && backEdges.containsEntry(loop, n)) .forEach(queue::add); queue.forEach(seen::add); while (!queue.isEmpty()) { Name cur = queue.poll(); inputs.get(cur).stream().filter(input -> !seen.contains(input)).forEach(input -> { seen.add(input); queue.add(input); }); } return seen; }
From source file:com.linkedin.pinot.core.startree.StarTreeSerDe.java
/** * Helper method to write the star tree nodes for Star Tree off-heap format * * @param starTree/*from w w w . ja v a 2 s.c om*/ * @param mappedByteBuffer * @param offset */ private static void writeNodesOffHeap(StarTree starTree, MMapBuffer mappedByteBuffer, long offset) { int index = 0; Queue<StarTreeIndexNode> queue = new LinkedList<>(); StarTreeIndexNode root = (StarTreeIndexNode) starTree.getRoot(); queue.add(root); while (!queue.isEmpty()) { StarTreeIndexNode node = queue.poll(); List<StarTreeIndexNode> children = getSortedChildren(node); // Returns empty list instead of null. int numChildren = children.size(); int startChildrenIndex = (numChildren != 0) ? (index + queue.size() + 1) : StarTreeIndexNodeOffHeap.INVALID_INDEX; int endChildrenIndex = (numChildren != 0) ? (startChildrenIndex + numChildren - 1) : StarTreeIndexNodeOffHeap.INVALID_INDEX; offset = writeOneOffHeapNode(mappedByteBuffer, offset, node, startChildrenIndex, endChildrenIndex); for (StarTreeIndexNode child : children) { queue.add(child); } index++; } }
From source file:edu.abreksa.BeanTest.components.Test.java
public static Test testLoader(String filepath) throws IOException { Log.debug("Loading test \"" + filepath + "\""); File testFile = new File(filepath); if (!testFile.exists()) { throw new FileNotFoundException("The test definition file \"" + filepath + "\" does not exist."); }/*from w w w .ja v a2 s.c om*/ Test test = Main.gson.fromJson(Main.Utils.readFile(testFile.getAbsolutePath()), Test.class); StringBuilder stringBuilder = new StringBuilder(); Queue<Object> queue = new LinkedList<Object>(); if (!Main.config.disableHelperMethods) { queue.add("imports(){import *;}\r\nimports();\r\n"); //Add log methods queue.add("debug(string){com.esotericsoftware.minlog.Log.debug(testHandle.getName(), string);}"); queue.add("error(string){com.esotericsoftware.minlog.Log.error(testHandle.getName(), string);}"); queue.add("warn(string){com.esotericsoftware.minlog.Log.warn(testHandle.getName(), string);}"); queue.add("info(string){com.esotericsoftware.minlog.Log.info(testHandle.getName(), string);}"); queue.add("trace(string){com.esotericsoftware.minlog.Log.trace(testHandle.getName(), string);}"); //Add (webDriver/selenium)/webClient variables queue.add( "if(testHandle.getDriver().equals(\"WebDriver\")){webDriver = testHandle.getWebDriver();} else if(testHandle.getDriver().equals(\"HTMLUnit\")){webClient = testHandle.getWebClient();}"); } //The before scripts for (String string : Main.config.before) { queue.add(new File(string)); } //The test before for (String string : test.before) { queue.add(new File(string)); } if (test.scriptCode != null) { queue.add(test.scriptCode); } //The test File scriptFile = new File(test.script); if (!scriptFile.exists()) { throw new FileNotFoundException("The script file \"" + test.script + "\" does not exist."); } else { queue.add(new File(scriptFile.getAbsolutePath())); } //The test after for (String string : test.after) { queue.add(new File(string)); } //The after for (String string : Main.config.after) { queue.add(new File(string)); } Log.debug("Queued " + Main.gson.toJson(queue)); Log.debug("Loading " + queue.size() + " external scripts"); for (Object object : queue) { if (object instanceof File) { if (((File) object).exists()) { Log.debug("Loading external script file \"" + object + "\""); stringBuilder.append("\r\n" + Main.Utils.readFile(((File) object).getAbsolutePath())); } else { Log.warn("External script file \"" + object + "\" does not exist."); } } else if (object instanceof String) { stringBuilder.append("\r\n" + object); } } test.scriptCode = stringBuilder.toString().replace("\r\n\r\n", "\r\n"); Log.debug("Final script \"" + test.scriptCode + "\""); return test; }
From source file:org.apache.hadoop.hbase.replication.regionserver.DumpReplicationQueues.java
static DumpOptions parseOpts(Queue<String> args) { DumpOptions opts = new DumpOptions(); String cmd = null;/* w w w . j a va 2 s. c o m*/ while ((cmd = args.poll()) != null) { if (cmd.equals("-h") || cmd.equals("--h") || cmd.equals("--help")) { // place item back onto queue so that caller knows parsing was incomplete args.add(cmd); break; } final String hdfs = "--hdfs"; if (cmd.equals(hdfs)) { opts.setHdfs(true); continue; } final String distributed = "--distributed"; if (cmd.equals(distributed)) { opts.setDistributed(true); continue; } else { printUsageAndExit("ERROR: Unrecognized option/command: " + cmd, -1); } // check that --distributed is present when --hdfs is in the arguments if (!opts.isDistributed() && opts.isHdfs()) { printUsageAndExit("ERROR: --hdfs option can only be used with --distributed: " + cmd, -1); } } return opts; }