List of usage examples for java.util Stack Stack
public Stack()
From source file:com.frostwire.android.gui.activities.MainActivity.java
public MainActivity() { super(R.layout.activity_main); controller = new MainController(this); fragmentsStack = new Stack<>(); permissionsCheckers = initPermissionsCheckers(); localBroadcastReceiver = new LocalBroadcastReceiver(); }
From source file:gdt.data.entity.ArchiveHandler.java
private boolean append(Entigrator entigrator, String root$, String source$, TarArchiveOutputStream aos) { try {/*from www .j av a2 s. c o m*/ File[] fa = null; File source = new File(source$); if (source.exists()) if (source.isFile()) fa = new File[] { source }; else fa = source.listFiles(); if (fa == null) return true; File recordFile = null; Stack<TarArchiveEntry> s = new Stack<TarArchiveEntry>(); int cnt = 0; TarArchiveEntry entry = null; for (File aFa : fa) { recordFile = aFa; entry = new TarArchiveEntry(recordFile); entry.setSize(recordFile.length()); s.clear(); getTarEntries(entry, s, root$); cnt = s.size(); // System.out.println("EximpExpert:append:cnt=" + cnt); File nextFile = null; for (int j = 0; j < cnt; j++) { entry = (TarArchiveEntry) s.pop(); try { String nextFile$ = entigrator.getEntihome() + "/" + entry.getName(); // System.out.println("EximpExpert:append:try next file=" + nextFile$); nextFile = new File(nextFile$); if (!nextFile.exists() || nextFile.length() < 1) { System.out.println("ArchiveHandler:append:wrong next file=" + nextFile$); continue; } aos.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(nextFile$), aos); // System.out.println("EximpExpert:tar_write:j="+j); aos.closeArchiveEntry(); } catch (Exception ee) { // System.out.println("EximpExpert:append:" + ee.toString()); LOGGER.severe(":append:" + ee.toString()); } } } //System.out.println("EximpExpert:tar_write:finish"); return true; //System.out.println("EximpExpert:tar_write:exit"); } catch (Exception e) { LOGGER.severe(":append:" + e.toString()); return false; } }
From source file:com.marklogic.contentpump.AggregateXMLReader.java
protected void copyNameSpaceDecl() { if (recordDepth < currDepth) { return;/*from ww w.j a va 2 s. c om*/ } int stop = xmlSR.getNamespaceCount(); if (stop > 0) { String nsDeclPrefix, nsDeclUri; if (LOG.isTraceEnabled()) { LOG.trace("checking namespace declarations"); } for (int i = 0; i < stop; i++) { nsDeclPrefix = xmlSR.getNamespacePrefix(i); nsDeclUri = xmlSR.getNamespaceURI(i); if (LOG.isTraceEnabled()) { LOG.trace(nsDeclPrefix + ":" + nsDeclUri); } if (nameSpaces.containsKey(nsDeclPrefix)) { nameSpaces.get(nsDeclPrefix).push(nsDeclUri); } else { Stack<String> s = new Stack<String>(); s.push(nsDeclUri); nameSpaces.put(nsDeclPrefix, s); } } } }
From source file:com.feilong.commons.core.util.CollectionsUtilTest.java
/** * TestCollectionsUtilTest.// w w w.j av a 2 s . c o m */ @Test public void testCollectionsUtilTest2() { Stack<Object> stack = new Stack<Object>(); stack.add("1"); stack.add("2"); stack.add("3"); stack.add("4"); if (log.isDebugEnabled()) { log.debug("" + stack.firstElement()); log.debug("" + stack.peek()); log.debug("" + stack.pop()); log.debug(JsonUtil.format(stack)); } }
From source file:eu.crisis_economics.abm.markets.clearing.IncrementalLoanDistributionAlgorithm.java
private Pair<Double, Double> distributeLoans(final Map<String, Borrower> borrowers, final Map<String, Lender> lenders, final Map<String, Double> loanDemands, final Map<String, Double> loanSupplies, final Map<Pair<String, String>, Double> interestRates) { // collect amount demanded by each firm at the current interest rate Map<String, Double> updatedLoanDemand = new HashMap<String, Double>(); for (String key : loanDemands.keySet()) updatedLoanDemand.put(key, 0.);//from w w w . j a v a 2 s. co m Map<String, Double> updatedLoanSupply = new HashMap<String, Double>(); Map<String, Double> loanSuppliesCopy = new HashMap<String, Double>(); for (String key : loanSupplies.keySet()) { updatedLoanSupply.put(key, 0.); loanSuppliesCopy.put(key, loanSupplies.get(key)); } /** * Aggregation for loans. Loans between the same participant pair (the * same lender-borrower pair) will be combined, by extension of the loan * principal, until the cash aggreation threshold LOAN_AGGREGATION_THRESHOLD * is reached. At this point, a new loan contract will instead be created. */ class LoanAggregator { private static final double LOAN_AGGREGATION_THRESHOLD = 5.e7; private Map<MultiKey<String>, Stack<Loan>> newLoanContracts = new HashMap<MultiKey<String>, Stack<Loan>>(); // Establish a new effective loan, either (a) by creating a loan contract, or // (b) by extending the principal sum of an existing loan. void establishNew(String borrowerID, String lenderID, double principalValue) { MultiKey<String> contractKey = new MultiKey<String>(borrowerID, lenderID); Stack<Loan> existingLoans = newLoanContracts.get(contractKey); if (existingLoans == null) { existingLoans = new Stack<Loan>(); newLoanContracts.put(contractKey, existingLoans); existingLoans.push(createNewLoan(borrowerID, lenderID, principalValue)); } else if (existingLoans.peek().getLoanPrincipalValue() < LOAN_AGGREGATION_THRESHOLD) { extendExistingLoan(existingLoans.peek(), principalValue); } else existingLoans.push(createNewLoan(borrowerID, lenderID, principalValue)); } // Create a new loan contract. private Loan createNewLoan(String borrowerID, String lenderID, double principalValue) { return setupLoanContract(borrowers.get(borrowerID), lenders.get(lenderID), principalValue, interestRates.get(new Pair<String, String>(borrowerID, lenderID))); } } LoanAggregator loanAggregator = new LoanAggregator(); final Iterator<Entry<String, Double>> firmIter = loanDemands.entrySet().iterator(); while (firmIter.hasNext()) { Entry<String, Double> firm = firmIter.next(); final Iterator<Entry<String, Double>> bankIter = loanSuppliesCopy.entrySet().iterator(); while (bankIter.hasNext()) { Entry<String, Double> bank = bankIter.next(); // leverage circle in case lender == borrower's depositor - try same bank again while (updatedLoanDemand.get(firm.getKey()) < firm.getValue() && updatedLoanSupply.get(bank.getKey()) < bank.getValue()) { double reserves = ((Bank) lenders.get(bank.getKey())).getCashReserveValue(); if (reserves > 0.0) { double increment = Math.min(reserves, Math.min(firm.getValue() - updatedLoanDemand.get(firm.getKey()), bank.getValue() - updatedLoanSupply.get(bank.getKey()))); updatedLoanDemand.put(firm.getKey(), updatedLoanDemand.get(firm.getKey()) + increment); updatedLoanSupply.put(bank.getKey(), updatedLoanSupply.get(bank.getKey()) + increment); loanSupplies.put(bank.getKey(), loanSupplies.get(bank.getKey()) - increment); //legacy loanAggregator.establishNew(firm.getKey(), bank.getKey(), increment); } else { // leverage circle in case lender != borrower's depositor - try all (other) banks final Iterator<Entry<String, Double>> otherBankIter = loanSuppliesCopy.entrySet() .iterator(); while (otherBankIter.hasNext()) { Entry<String, Double> otherBank = otherBankIter.next(); while (updatedLoanDemand.get(firm.getKey()) < firm.getValue() && updatedLoanSupply.get(otherBank.getKey()) < otherBank.getValue()) { reserves = ((Bank) lenders.get(otherBank.getKey())).getCashReserveValue(); if (reserves > 0.0) { double increment = Math.min(reserves, Math.min( firm.getValue() - updatedLoanDemand.get(firm.getKey()), otherBank.getValue() - updatedLoanSupply.get(otherBank.getKey()))); updatedLoanDemand.put(firm.getKey(), updatedLoanDemand.get(firm.getKey()) + increment); updatedLoanSupply.put(otherBank.getKey(), updatedLoanSupply.get(otherBank.getKey()) + increment); loanSupplies.put(otherBank.getKey(), loanSupplies.get(otherBank.getKey()) - increment); //legacy loanAggregator.establishNew(firm.getKey(), otherBank.getKey(), increment); } else break; } if (updatedLoanDemand.get(firm.getKey()) >= firm.getValue()) break; // otherBank loop shortcut } // in case cash is not flowing back to any bank, bank has to handle cash flow exception double increment = firm.getValue() - updatedLoanDemand.get(firm.getKey()); if (increment > 0) { updatedLoanDemand.put(firm.getKey(), updatedLoanDemand.get(firm.getKey()) + increment); updatedLoanSupply.put(bank.getKey(), updatedLoanSupply.get(bank.getKey()) + increment); loanSupplies.put(bank.getKey(), loanSupplies.get(bank.getKey()) - increment); //legacy loanAggregator.establishNew(firm.getKey(), bank.getKey(), increment); } break; // no point of trying same bank again } } if (updatedLoanDemand.get(firm.getKey()) >= firm.getValue()) break; // bank loop shortcut } } double effectiveLoan = 0., tradeWeightedInterestRate = 0.; int numberOfLoansCreated = 0; for (Stack<Loan> loans : loanAggregator.newLoanContracts.values()) { for (Loan loan : loans) { effectiveLoan += loan.getLoanPrincipalValue(); tradeWeightedInterestRate += loan.getLoanPrincipalValue() * loan.getInterestRate(); } numberOfLoansCreated += loans.size(); } System.out.println("Number of loans created: " + numberOfLoansCreated + "."); loanAggregator.newLoanContracts.clear(); return new Pair<Double, Double>(effectiveLoan, tradeWeightedInterestRate / effectiveLoan); }
From source file:com.espertech.esper.epl.join.plan.NStreamOuterQueryPlanBuilder.java
private static QueryPlanNode buildPlanNode(int numStreams, int streamNo, String[] streamNames, QueryGraph queryGraph, OuterInnerDirectionalGraph outerInnerGraph, OuterJoinDesc[] outerJoinDescList, InnerJoinGraph innerJoinGraph, QueryPlanIndex[] indexSpecs, EventType[] typesPerStream, boolean[] ishistorical, DependencyGraph dependencyGraph, HistoricalStreamIndexList[] historicalStreamIndexLists, ExprEvaluatorContext exprEvaluatorContext) throws ExprValidationException { // For each stream build an array of substreams, considering required streams (inner joins) first // The order is relevant therefore preserving order via a LinkedHashMap. LinkedHashMap<Integer, int[]> substreamsPerStream = new LinkedHashMap<Integer, int[]>(); boolean[] requiredPerStream = new boolean[numStreams]; // Recursive populating the required (outer) and optional (inner) relationships // of this stream and the substream Set<Integer> completedStreams = new HashSet<Integer>(); // keep track of tree path as only those stream events are always available to historical streams Stack<Integer> streamCallStack = new Stack<Integer>(); streamCallStack.push(streamNo);/*from w ww.ja v a2 s . c o m*/ // For all inner-joins, the algorithm is slightly different if (innerJoinGraph.isAllInnerJoin()) { Arrays.fill(requiredPerStream, true); recursiveBuildInnerJoin(streamNo, streamCallStack, queryGraph, completedStreams, substreamsPerStream, dependencyGraph); // compute a best chain to see if all streams are handled and add the remaining NStreamQueryPlanBuilder.BestChainResult bestChain = NStreamQueryPlanBuilder.computeBestPath(streamNo, queryGraph, dependencyGraph); addNotYetNavigated(streamNo, numStreams, substreamsPerStream, bestChain); } else { recursiveBuild(streamNo, streamCallStack, queryGraph, outerInnerGraph, innerJoinGraph, completedStreams, substreamsPerStream, requiredPerStream, dependencyGraph); } // verify the substreamsPerStream, all streams must exists and be linked verifyJoinedPerStream(streamNo, substreamsPerStream); // build list of instructions for lookup List<LookupInstructionPlan> lookupInstructions = buildLookupInstructions(streamNo, substreamsPerStream, requiredPerStream, streamNames, queryGraph, indexSpecs, typesPerStream, outerJoinDescList, ishistorical, historicalStreamIndexLists, exprEvaluatorContext); // build strategy tree for putting the result back together BaseAssemblyNode assemblyTopNode = AssemblyStrategyTreeBuilder.build(streamNo, substreamsPerStream, requiredPerStream); List<BaseAssemblyNode> assemblyInstructions = BaseAssemblyNode.getDescendentNodesBottomUp(assemblyTopNode); return new LookupInstructionQueryPlanNode(streamNo, streamNames[streamNo], numStreams, requiredPerStream, lookupInstructions, assemblyInstructions); }
From source file:com.hubspot.jinjava.interpret.JinjavaInterpreter.java
private void resolveBlockStubs(OutputList output) { resolveBlockStubs(output, new Stack<>()); }
From source file:com.k42b3.aletheia.protocol.http.Util.java
public static String removeDotSegments(String relativePath) { // remove query or fragment part if any int pos = relativePath.indexOf('?'); if (pos != -1) { relativePath = relativePath.substring(0, pos); }/*from w w w .j av a 2 s. c om*/ pos = relativePath.indexOf('#'); if (pos != -1) { relativePath = relativePath.substring(0, pos); } // if the path contains no slash we have nothing to resolve if (relativePath.indexOf('/') == -1) { return relativePath; } String[] parts = relativePath.split("/"); Stack<String> path = new Stack<String>(); String part; for (int i = 0; i < parts.length; i++) { part = parts[i].trim(); if (part.isEmpty() || part.equals(".")) { } else if (part.equals("..")) { path.pop(); } else { path.add(part); } } // build absolute url String absoluteUrl = ""; if (path.size() > 0) { for (int i = 0; i < path.size(); i++) { if (i > 0 && path.get(i).indexOf('.') != -1 && path.get(i - 1).equals(path.get(i))) { // if the element before has the same name and it contains // an dot we have probably an file name continue; } absoluteUrl += "/" + path.get(i); } } else { absoluteUrl = "/"; } // add last slash if (relativePath.endsWith("/") && !absoluteUrl.endsWith("/")) { absoluteUrl = absoluteUrl + "/"; } return absoluteUrl; }
From source file:com.ctriposs.rest4j.tools.snapshot.check.Rest4JSnapshotCompatibilityChecker.java
private CompatibilityInfoMap checkCompatibility(String prevRestModelPath, String currRestModelPath, CompatibilityLevel compatLevel, boolean isAgainstRestSpec) { final CompatibilityInfoMap infoMap = new CompatibilityInfoMap(); if (compatLevel == CompatibilityLevel.OFF) { // skip check entirely. return infoMap; }// ww w . ja va 2 s .c o m final Stack<Object> path = new Stack<Object>(); path.push(""); FileInputStream prevSnapshotFile = null; FileInputStream currSnapshotFile = null; try { prevSnapshotFile = new FileInputStream(prevRestModelPath); } catch (FileNotFoundException e) { infoMap.addRestSpecInfo(CompatibilityInfo.Type.RESOURCE_NEW, path, currRestModelPath); } try { currSnapshotFile = new FileInputStream(currRestModelPath); } catch (FileNotFoundException e) { infoMap.addRestSpecInfo(CompatibilityInfo.Type.RESOURCE_MISSING, path, prevRestModelPath); } if (prevSnapshotFile == null || currSnapshotFile == null) { return infoMap; } AbstractSnapshot prevSnapshot = null; AbstractSnapshot currSnapshot = null; try { if (isAgainstRestSpec) { prevSnapshot = new RestSpec(prevSnapshotFile); } else { prevSnapshot = new Snapshot(prevSnapshotFile); } currSnapshot = new Snapshot(currSnapshotFile); } catch (IOException e) { infoMap.addRestSpecInfo(CompatibilityInfo.Type.OTHER_ERROR, path, e.getMessage()); } if (prevSnapshot == null || currSnapshot == null) { return infoMap; } final DataSchemaResolver currResolver = createResolverFromSnapshot(currSnapshot, _resolverPath); final DataSchemaResolver prevResolver; if (isAgainstRestSpec) { prevResolver = currResolver; } else { prevResolver = createResolverFromSnapshot(prevSnapshot, _resolverPath); } final ResourceCompatibilityChecker checker = new ResourceCompatibilityChecker( prevSnapshot.getResourceSchema(), prevResolver, currSnapshot.getResourceSchema(), currResolver); checker.check(compatLevel); infoMap.addAll(checker.getInfoMap()); return infoMap; }
From source file:edu.mit.lib.tools.Modernize.java
private void collectionManifest(Collection coll) throws IOException, SQLException { Stack<Community> parents = new Stack<>(); Community parent = (Community) coll.getParentObject(); while (parent != null) { parents.push(parent);/*from w w w . j a v a2 s . c o m*/ parent = parent.getParentCommunity(); } int level = manif.addParents(parents); manif.addCollection(coll, level); }