List of usage examples for java.util LinkedList isEmpty
boolean isEmpty();
From source file:tokyo.northside.jrst.JRSTReader.java
/** * @param title/* ww w . j a va2 s .c o m*/ * <Element> title, String num * @return Element */ private Element composeLineContent(LinkedList<Element> title, String num) { Element result = DocumentHelper.createElement(BULLET_LIST); if (sectnum) { result.addAttribute(CLASS, "auto-toc"); } Element item = null; int cnt = 0; while (!title.isEmpty()) { Element e = title.getFirst(); int level = Integer.parseInt(e.attributeValue(LEVEL)); LinkedList<Element> child = new LinkedList<Element>(); if (level <= 0) { cnt++; title.removeFirst(); item = result.addElement(LIST_ITEM); Element para = item.addElement(PARAGRAPH); Element reference = para.addElement(REFERENCE); String text = e.getText(); String id = e.attributeValue(ATTR_REFID); reference.addAttribute(ATTR_IDS, id); reference.addAttribute(ATTR_REFID, text.replaceAll("\\W+", " ").trim().toLowerCase().replaceAll("\\W+", "-")); // si l'on doit les numeroter if (sectnum) { Element generated = reference.addElement(GENERATED).addAttribute(CLASS, SECTNUM); generated.setText(num + cnt + " "); for (int i = 0; i < eTitle.size(); i++) { if (eTitle.get(i).attributeValue(ATTR_REFID).equals(id)) { Element generatedTitle = eTitle.get(i).addElement(GENERATED); generatedTitle.addAttribute(CLASS, SECTNUM); generatedTitle.setText(num + cnt + " "); } } } text = text.trim(); text = text.replaceAll("_", ""); text = REGEX_STRONG.matcher(text).replaceAll("<" + STRONG + ">$1</" + STRONG + ">"); text = REGEX_EMPHASIS.matcher(text).replaceAll("<" + EMPHASIS + ">$1</" + EMPHASIS + ">"); try { Element textElement = DocumentHelper.parseText("<TMP>" + text + "</TMP>").getRootElement(); reference.appendContent(textElement); } catch (DocumentException eee) { if (log.isWarnEnabled()) { log.warn("Can't inline text for " + e, eee); } } } else { do { e.addAttribute(LEVEL, "" + (level - 1)); child.add(e); title.removeFirst(); if (!title.isEmpty()) { e = title.getFirst(); level = Integer.parseInt(e.attributeValue(LEVEL)); } } while (!title.isEmpty() && level > 0); String numTmp = ""; // numerotation if (sectnum) { numTmp = num + cnt + "."; } if (item != null) { item.add(composeLineContent(child, numTmp)); // Appel // recursif } else { result.add(composeLineContent(child, numTmp)); // Appel // recursif } } } return result; }
From source file:com.zimbra.cs.service.FileUploadServlet.java
@SuppressWarnings("unchecked") List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete) throws IOException, ServiceException { List<FileItem> items = null; String reqId = null;/*from w ww . j ava2s . co m*/ ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize); try { items = upload.parseRequest(req); if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) { drainRequestStream(req); mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled", acct.getName()); sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items); return Collections.emptyList(); } } catch (FileUploadBase.SizeLimitExceededException e) { // at least one file was over max allowed size mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items); return Collections.emptyList(); } catch (FileUploadBase.InvalidContentTypeException e) { // at least one file was of a type not allowed mLog.info("File upload failed", e); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items); return Collections.emptyList(); } catch (FileUploadException e) { // parse of request failed for some other reason mLog.info("File upload failed", e); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items); return Collections.emptyList(); } String charset = "utf-8"; LinkedList<String> names = new LinkedList<String>(); HashMap<FileItem, String> filenames = new HashMap<FileItem, String>(); if (items != null) { for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem fi = it.next(); if (fi == null) continue; if (fi.isFormField()) { if (fi.getFieldName().equals("requestId")) { // correlate this file upload session's request and response reqId = fi.getString(); } else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) { // get the form value charset, if specified charset = fi.getString(); } else if (fi.getFieldName().startsWith("filename")) { // allow a client to explicitly provide filenames for the uploads names.clear(); String value = fi.getString(charset); if (!Strings.isNullOrEmpty(value)) { for (String name : value.split("\n")) { names.add(name.trim()); } } } // strip form fields out of the list of uploads it.remove(); } else { if (fi.getName() == null || fi.getName().trim().equals("")) { it.remove(); } else { filenames.put(fi, names.isEmpty() ? null : names.remove()); } } } } // restrict requestId value for safety due to later use in javascript if (reqId != null && reqId.length() != 0) { if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) { mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId); sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items); return Collections.emptyList(); } } // empty upload is not a "success" if (items == null || items.isEmpty()) { mLog.info("No data in upload for reqId: %s", reqId); sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items); return Collections.emptyList(); } // cache the uploaded files in the hash and construct the list of upload IDs List<Upload> uploads = new ArrayList<Upload>(items.size()); for (FileItem fi : items) { String name = filenames.get(fi); if (name == null || name.trim().equals("")) name = fi.getName(); Upload up = new Upload(acct.getId(), fi, name); mLog.info("Received multipart: %s", up); synchronized (mPending) { mPending.put(up.uuid, up); } uploads.add(up); } sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items); return uploads; }
From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java
protected void refreshFolderPaths(RepoFolder folder) { // refreshing recursively using a queue LinkedList<RepoFolder> folders = new LinkedList<RepoFolder>(); folders.addLast(folder);/*from w w w . j a v a 2 s . com*/ while (!folders.isEmpty()) { RepoFolder aFolder = folders.removeFirst(); aFolder.refreshURI(this); Set resources = aFolder.getChildren(); if (resources != null && !resources.isEmpty()) { for (Iterator it = resources.iterator(); it.hasNext();) { RepoResource child = (RepoResource) it.next(); RepoFolder grandChildrenFolder = child.getChildrenFolder(); if (grandChildrenFolder != null) { folders.addLast(grandChildrenFolder); } } } } }
From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java
/** * Parse the timeranges parameter and generate a list of TimeSpans. * @param resp/* www . j a v a2s .c om*/ * @param pvName * @param requestTimes - list of timespans that we add the valid times to. * @param timeRangesStr * @return * @throws IOException */ private boolean parseTimeRanges(HttpServletResponse resp, String pvName, LinkedList<TimeSpan> requestTimes, String timeRangesStr) throws IOException { String[] timeRangesStrList = timeRangesStr.split(","); if (timeRangesStrList.length % 2 != 0) { String msg = "Need to specify an even number of times in timeranges for pv " + pvName + ". We have " + timeRangesStrList.length + " times"; logger.error(msg); resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return false; } LinkedList<Timestamp> timeRangesList = new LinkedList<Timestamp>(); for (String timeRangesStrItem : timeRangesStrList) { try { Timestamp ts = TimeUtils.convertFromISO8601String(timeRangesStrItem); timeRangesList.add(ts); } catch (IllegalArgumentException ex) { try { Timestamp ts = TimeUtils.convertFromDateTimeStringWithOffset(timeRangesStrItem); timeRangesList.add(ts); } catch (IllegalArgumentException ex2) { String msg = "Cannot parse time " + timeRangesStrItem; logger.warn(msg, ex2); resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return false; } } } assert (timeRangesList.size() % 2 == 0); Timestamp prevEnd = null; while (!timeRangesList.isEmpty()) { Timestamp t0 = timeRangesList.pop(); Timestamp t1 = timeRangesList.pop(); if (t1.before(t0)) { String msg = "For request, end " + t1.toString() + " is before start " + t0.toString() + " for pv " + pvName; logger.error(msg); resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return false; } if (prevEnd != null) { if (t0.before(prevEnd)) { String msg = "For request, start time " + t0.toString() + " is before previous end time " + prevEnd.toString() + " for pv " + pvName; logger.error(msg); resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return false; } } prevEnd = t1; requestTimes.add(new TimeSpan(t0, t1)); } return true; }
From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java
/** * Building a ContentElement, this funciton is calles by all the other * parseContentElement(..) functions// w w w . ja v a 2 s .co m */ private ContentElement parseContentElement(SpanManager sm, ContentElementParsingParameters cepp, LinkedList<Span> lineSpans, ContentElement result) { List<Link> localLinks = new ArrayList<Link>(); List<Template> localTemplates = new ArrayList<Template>(); List<Span> boldSpans = new ArrayList<Span>(); List<Span> italicSpans = new ArrayList<Span>(); sm.manageList(boldSpans); sm.manageList(italicSpans); List<Span> managedSpans = new ArrayList<Span>(); sm.manageList(managedSpans); Span contentElementRange = new Span(lineSpans.getFirst().getStart(), lineSpans.getLast().getEnd()).trim(sm); managedSpans.add(contentElementRange); // set the SrcSpan if (calculateSrcSpans) { result.setSrcSpan(new SrcSpan(sm.getSrcPos(contentElementRange.getStart()), sm.getSrcPos(contentElementRange.getEnd()))); } sm.manageList(lineSpans); while (!lineSpans.isEmpty()) { Span line = lineSpans.getFirst(); parseBoldAndItalicSpans(sm, line, boldSpans, italicSpans); // External links parseExternalLinks(sm, line, "http://", managedSpans, localLinks, result); parseExternalLinks(sm, line, "https://", managedSpans, localLinks, result); parseExternalLinks(sm, line, "ftp://", managedSpans, localLinks, result); parseExternalLinks(sm, line, "mailto:", managedSpans, localLinks, result); // end of linewhise opperations lineSpans.removeFirst(); } sm.removeManagedList(lineSpans); // Links int i; i = 0; while (i < cepp.linkSpans.size()) { if (contentElementRange.hits(cepp.linkSpans.get(i))) { Span linkSpan = cepp.linkSpans.remove(i); managedSpans.add(linkSpan); Link l = cepp.links.remove(i).setHomeElement(result); localLinks.add(l); if (!showImageText && l.getType() == Link.type.IMAGE) { // deletes the Image Text from the ContentElement Text. sm.delete(linkSpan); } } else { i++; } } // Templates i = 0; while (i < cepp.templateSpans.size()) { Span ts = cepp.templateSpans.get(i); if (contentElementRange.hits(ts)) { ResolvedTemplate rt = cepp.templates.remove(i); if (rt.getPostParseReplacement() != null) { sm.replace(ts, rt.getPostParseReplacement()); } cepp.templateSpans.remove(i); Object parsedObject = rt.getParsedObject(); if (parsedObject != null) { managedSpans.add(ts); Class parsedObjectClass = parsedObject.getClass(); if (parsedObjectClass == Template.class) { localTemplates.add((Template) parsedObject); } else if (parsedObjectClass == Link.class) { localLinks.add(((Link) parsedObject).setHomeElement(result)); } else { localTemplates.add(rt.getTemplate()); } } } else { i++; } } // HTML/XML Tags i = 0; List<Span> tags = new ArrayList<Span>(); while (i < cepp.tagSpans.size()) { Span s = cepp.tagSpans.get(i); if (contentElementRange.hits(s)) { cepp.tagSpans.remove(i); if (deleteTags) { sm.delete(s); } else { tags.add(s); managedSpans.add(s); } } else { i++; } } // noWiki i = 0; List<Span> localNoWikiSpans = new ArrayList<Span>(); while (i < cepp.noWikiSpans.size()) { Span s = cepp.noWikiSpans.get(i); if (contentElementRange.hits(s)) { cepp.noWikiSpans.remove(i); sm.replace(s, cepp.noWikiStrings.remove(i)); localNoWikiSpans.add(s); managedSpans.add(s); } else { i++; } } // MATH Tags i = 0; List<Span> mathSpans = new ArrayList<Span>(); while (i < cepp.mathSpans.size()) { Span s = cepp.mathSpans.get(i); if (contentElementRange.hits(s)) { cepp.mathSpans.remove(i); if (showMathTagContent) { mathSpans.add(s); managedSpans.add(s); sm.replace(s, cepp.mathStrings.remove(i)); } else { sm.delete(s); } } else { i++; } } result.setText(sm.substring(contentElementRange)); // managed spans must be removed here and not earlier, because every // change in the SpanManager affects the Spans! sm.removeManagedList(boldSpans); sm.removeManagedList(italicSpans); sm.removeManagedList(managedSpans); // contentElementRange ist auch noch in managedSpans !!! deswegen: final int adjust = -contentElementRange.getStart(); for (Span s : boldSpans) { s.adjust(adjust); } for (Span s : italicSpans) { s.adjust(adjust); } for (Span s : managedSpans) { s.adjust(adjust); } result.setFormatSpans(FormatType.BOLD, boldSpans); result.setFormatSpans(FormatType.ITALIC, italicSpans); result.setFormatSpans(FormatType.TAG, tags); result.setFormatSpans(FormatType.MATH, mathSpans); result.setFormatSpans(FormatType.NOWIKI, localNoWikiSpans); result.setLinks(sortLinks(localLinks)); result.setTemplates(sortTemplates(localTemplates)); return result; }
From source file:io.apptik.widget.MultiSlider.java
/** * Get closest thumb to play with,/*from w w w . ja v a 2 s .co m*/ * incase more than one get the last one * * @param x X coordinate of the touch * @return */ private LinkedList<Thumb> getClosestThumb(int x) { LinkedList<Thumb> exact = new LinkedList<Thumb>(); Thumb closest = null; int currDistance = getAvailable() + 1; for (Thumb thumb : mThumbs) { if (thumb.getThumb() == null || thumb.isInvisibleThumb()) continue; int minV = x - thumb.getThumb().getIntrinsicWidth(); int maxV = x + thumb.getThumb().getIntrinsicWidth(); if (thumb.getThumb().getBounds().centerX() >= minV && thumb.getThumb().getBounds().centerX() <= maxV) { //we have exact match // we add them all so we can choose later which one to move exact.add(thumb); } else if (Math.abs(thumb.getThumb().getBounds().centerX() - x) <= currDistance) { if (Math.abs(thumb.getThumb().getBounds().centerX() - x) == currDistance) { if (x > getWidth() / 2) { //left one(s) has more place to move closest = thumb; } else { //right one(s) has more place to move } } else { if (thumb.getThumb() != null) { currDistance = Math.abs(thumb.getThumb().getBounds().centerX() - x); closest = thumb; } } } } if (exact.isEmpty() && closest != null) { exact.add(closest); } return exact; }
From source file:org.dbpedia.spotlight.mediawiki.ModularParser.java
/** * Building a ContentElement, this funciton is calles by all the other * parseContentElement(..) functions//from ww w . j a v a2s.co m */ private ContentElement parseContentElement(SpanManager sm, ContentElementParsingParameters cepp, LinkedList<Span> lineSpans, ContentElement result) { List<Link> localLinks = new ArrayList<Link>(); List<Template> localTemplates = new ArrayList<Template>(); List<Span> boldSpans = new ArrayList<Span>(); List<Span> italicSpans = new ArrayList<Span>(); sm.manageList(boldSpans); sm.manageList(italicSpans); List<Span> managedSpans = new ArrayList<Span>(); sm.manageList(managedSpans); Span contentElementRange = new Span(lineSpans.getFirst().getStart(), lineSpans.getLast().getEnd()).trim(sm); managedSpans.add(contentElementRange); // set the SrcSpan if (calculateSrcSpans) { result.setSrcSpan(new SrcSpan(sm.getSrcPos(contentElementRange.getStart()), sm.getSrcPos(contentElementRange.getEnd()))); } sm.manageList(lineSpans); while (!lineSpans.isEmpty()) { Span line = lineSpans.getFirst(); parseBoldAndItalicSpans(sm, line, boldSpans, italicSpans); // External links parseExternalLinks(sm, line, "http://", managedSpans, localLinks, result); parseExternalLinks(sm, line, "https://", managedSpans, localLinks, result); parseExternalLinks(sm, line, "ftp://", managedSpans, localLinks, result); parseExternalLinks(sm, line, "mailto:", managedSpans, localLinks, result); // end of linewhise opperations lineSpans.removeFirst(); } sm.removeManagedList(lineSpans); // Links int i; i = 0; while (i < cepp.linkSpans.size()) { if (contentElementRange.hits(cepp.linkSpans.get(i))) { Span linkSpan = cepp.linkSpans.remove(i); managedSpans.add(linkSpan); Link l = cepp.links.remove(i).setHomeElement(result); localLinks.add(l); if (!showImageText && l.getType() == Link.type.IMAGE) { // deletes the Image Text from the ContentElement Text. sm.delete(linkSpan); } } else { i++; } } // Templates //DBPedia - Spotlight. Removing the boiler plate logic from the wikitext //Commenting the Templates Logic /* i = 0; while (i < cepp.templateSpans.size()) { Span ts = cepp.templateSpans.get(i); if (contentElementRange.hits(ts)) { ResolvedTemplate rt = cepp.templates.remove(i); if (rt.getPostParseReplacement() != null) { sm.replace(ts, rt.getPostParseReplacement()); } cepp.templateSpans.remove(i); Object parsedObject = rt.getParsedObject(); if (parsedObject != null) { managedSpans.add(ts); Class parsedObjectClass = parsedObject.getClass(); if (parsedObjectClass == Template.class) { localTemplates.add((Template) parsedObject); } else if (parsedObjectClass == Link.class) { localLinks.add(((Link) parsedObject) .setHomeElement(result)); } else { localTemplates.add(rt.getTemplate()); } } } else { i++; } } */ // HTML/XML Tags i = 0; List<Span> tags = new ArrayList<Span>(); while (i < cepp.tagSpans.size()) { Span s = cepp.tagSpans.get(i); if (contentElementRange.hits(s)) { cepp.tagSpans.remove(i); if (deleteTags) { sm.delete(s); } else { tags.add(s); managedSpans.add(s); } } else { i++; } } // noWiki i = 0; List<Span> localNoWikiSpans = new ArrayList<Span>(); while (i < cepp.noWikiSpans.size()) { Span s = cepp.noWikiSpans.get(i); if (contentElementRange.hits(s)) { cepp.noWikiSpans.remove(i); sm.replace(s, cepp.noWikiStrings.remove(i)); localNoWikiSpans.add(s); managedSpans.add(s); } else { i++; } } // MATH Tags i = 0; List<Span> mathSpans = new ArrayList<Span>(); while (i < cepp.mathSpans.size()) { Span s = cepp.mathSpans.get(i); if (contentElementRange.hits(s)) { cepp.mathSpans.remove(i); if (showMathTagContent) { mathSpans.add(s); managedSpans.add(s); sm.replace(s, cepp.mathStrings.remove(i)); } else { sm.delete(s); } } else { i++; } } result.setText(sm.substring(contentElementRange)); // managed spans must be removed here and not earlier, because every // change in the SpanManager affects the Spans! sm.removeManagedList(boldSpans); sm.removeManagedList(italicSpans); sm.removeManagedList(managedSpans); // contentElementRange ist auch noch in managedSpans !!! deswegen: final int adjust = -contentElementRange.getStart(); for (Span s : boldSpans) { s.adjust(adjust); } for (Span s : italicSpans) { s.adjust(adjust); } for (Span s : managedSpans) { s.adjust(adjust); } result.setFormatSpans(FormatType.BOLD, boldSpans); result.setFormatSpans(FormatType.ITALIC, italicSpans); result.setFormatSpans(FormatType.TAG, tags); result.setFormatSpans(FormatType.MATH, mathSpans); result.setFormatSpans(FormatType.NOWIKI, localNoWikiSpans); result.setLinks(sortLinks(localLinks)); result.setTemplates(sortTemplates(localTemplates)); return result; }
From source file:org.deeplearning4j.nn.graph.ComputationGraph.java
/** * Calculate a topological sort order for the vertices in the graph. * Note that this is used for// www . j a va 2 s . c o m * (a) working out what order to do forward pass, * (b) what order to do backprop (i.e., reverse of this) * (c) order to flatten parameters (and gradients) */ public int[] topologicalSortOrder() { if (topologicalOrder != null) return topologicalOrder; //https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm Map<String, org.deeplearning4j.nn.conf.graph.GraphVertex> nodeMap = configuration.getVertices(); List<String> networkInputNames = configuration.getNetworkInputs(); int numVertices = networkInputNames.size() + configuration.getVertices().size(); int[] out = new int[numVertices]; int outCounter = 0; //First: represent the graph more usefully as a Map<Integer,Set<Integer>>, where map represents edges i -> j // key represents j, set is set of i (inputs) for vertices j Map<Integer, String> vertexNamesMap = new HashMap<>(); Map<String, Integer> vertexNamesMap2 = new HashMap<>(); int i = 0; for (String inputName : configuration.getNetworkInputs()) { vertexNamesMap.put(i, inputName); vertexNamesMap2.put(inputName, i); i++; } for (Map.Entry<String, org.deeplearning4j.nn.conf.graph.GraphVertex> entry : nodeMap.entrySet()) { String name = entry.getKey(); vertexNamesMap.put(i, name); vertexNamesMap2.put(name, i); i++; } Map<Integer, Set<Integer>> inputEdges = new HashMap<>(); //key: vertex. Values: vertices that the key vertex receives input from Map<Integer, Set<Integer>> outputEdges = new HashMap<>(); //key: vertex. Values: vertices that the key vertex outputs to for (String s : configuration.getNetworkInputs()) { int idx = vertexNamesMap2.get(s); inputEdges.put(idx, null); } for (Map.Entry<String, org.deeplearning4j.nn.conf.graph.GraphVertex> entry : nodeMap.entrySet()) { String thisVertexName = entry.getKey(); int idx = vertexNamesMap2.get(thisVertexName); List<String> inputsToThisVertex = configuration.getVertexInputs().get(thisVertexName); if (inputsToThisVertex == null || inputsToThisVertex.isEmpty()) { inputEdges.put(idx, null); continue; } Set<Integer> inputSet = new HashSet<>(); for (String s : inputsToThisVertex) { Integer inputIdx = vertexNamesMap2.get(s); if (inputIdx == null) { System.out.println(); } inputSet.add(inputIdx); Set<Integer> outputSetForInputIdx = outputEdges.get(inputIdx); if (outputSetForInputIdx == null) { outputSetForInputIdx = new HashSet<>(); outputEdges.put(inputIdx, outputSetForInputIdx); } outputSetForInputIdx.add(idx); //input vertex outputs to the current vertex } inputEdges.put(idx, inputSet); } //Now: do topological sort //Set of all nodes with no incoming edges: (this would be: input vertices) LinkedList<Integer> noIncomingEdges = new LinkedList<>(); for (Map.Entry<Integer, Set<Integer>> entry : inputEdges.entrySet()) { Set<Integer> inputsFrom = entry.getValue(); if (inputsFrom == null || inputsFrom.isEmpty()) { noIncomingEdges.add(entry.getKey()); } } while (!noIncomingEdges.isEmpty()) { int next = noIncomingEdges.removeFirst(); out[outCounter++] = next; //Add to sorted list Set<Integer> vertexOutputsTo = outputEdges.get(next); //Remove edges next -> vertexOuputsTo[...] from graph; if (vertexOutputsTo != null) { for (Integer v : vertexOutputsTo) { Set<Integer> set = inputEdges.get(v); set.remove(next); if (set.isEmpty()) { noIncomingEdges.add(v); //No remaining edges for vertex i -> add to list for processing } } } } //If any edges remain in the graph: graph has cycles: for (Map.Entry<Integer, Set<Integer>> entry : inputEdges.entrySet()) { Set<Integer> set = entry.getValue(); if (set == null) continue; if (!set.isEmpty()) throw new IllegalStateException( "Invalid configuration: cycle detected in graph. Cannot calculate topological ordering with graph cycle (" + "cycle includes vertex \"" + vertexNamesMap.get(entry.getKey()) + "\")"); } return out; }
From source file:com.zimbra.cs.service.mail.ToXML.java
private static void addParts(Element root, MPartInfo mpiRoot, Set<MPartInfo> bodies, String prefix, int maxSize, boolean neuter, boolean excludeCalendarParts, String defaultCharset, boolean swallowContentExceptions, MsgContent wantContent) throws ServiceException { MPartInfo mpi = mpiRoot;//from ww w .j ava2s .c o m LinkedList<Pair<Element, LinkedList<MPartInfo>>> queue = new LinkedList<Pair<Element, LinkedList<MPartInfo>>>(); Pair<Element, LinkedList<MPartInfo>> level = new Pair<Element, LinkedList<MPartInfo>>(root, new LinkedList<MPartInfo>()); level.getSecond().add(mpi); queue.add(level); VisitPhase phase = VisitPhase.PREVISIT; while (!queue.isEmpty()) { level = queue.getLast(); LinkedList<MPartInfo> parts = level.getSecond(); if (parts.isEmpty()) { queue.removeLast(); phase = VisitPhase.POSTVISIT; continue; } mpi = parts.getFirst(); Element child = addPart(phase, level.getFirst(), root, mpi, bodies, prefix, maxSize, neuter, excludeCalendarParts, defaultCharset, swallowContentExceptions, wantContent); if (phase == VisitPhase.PREVISIT && child != null && mpi.hasChildren()) { queue.addLast(new Pair<Element, LinkedList<MPartInfo>>(child, new LinkedList<MPartInfo>(mpi.getChildren()))); } else { parts.removeFirst(); phase = VisitPhase.PREVISIT; } } }
From source file:elh.eus.absa.Features.java
/** * Given a window check if the ngrams inside (all of them) are present in the feature set, and if so, * update the feature vector accordingly * /*from ww w . j a v a 2s .c o m*/ * @param ngrams * @param prefix String : possible prefix used to differentiate ngram groups in the attribute set. * @param double[] fVector : feature vector for the corresponding instance * @param int tokens : number of tokens in the sentence (in case we want to add not a frequency value * but a normalized value) * */ private void checkNgramFeatures(LinkedList<String> ngrams, double[] fVector, String prefix, int tokens, boolean empty) { //System.err.println("features::checkNgramFeatures ->"+Arrays.asList(ngrams).toString()); // if empty is active means that we are checking the end of the sentence and // the ngram list must be emptied if (empty) { while (!ngrams.isEmpty()) { String ng = featureFromArray(ngrams, prefix); //add occurrence to feature vector (the functions checks if the given ngram feature exists). addNumericToFeatureVector(ng, fVector, tokens); //tokNum ngrams.removeFirst(); } } // if empty is false search for all ngrams in the window else { // add ngrams to the feature list for (int i = 0; i < ngrams.size(); i++) { String ng = featureFromArray(ngrams.subList(0, i + 1), prefix); // add occurrence to feature vector (the functions checks if the given ngram feature exists). addNumericToFeatureVector(ng, fVector, tokens);//tokNum } } }