List of usage examples for java.util LinkedList isEmpty
boolean isEmpty();
From source file:elh.eus.absa.Features.java
/** * Check if the given word/lemma/ngram exists both in the ngram list and in the general or domain polarity * lexicons, and if yes updates the corresponding attributes in the feature vector * /*from www .j av a 2 s .co m*/ * @param ngrams * @param fVector * @param prefix * @param toknumNgram * @param toknumPol * @param empty * @param ngram */ private void checkNgramsAndPolarLexicons(LinkedList<String> ngrams, double[] fVector, String prefix, int toknumNgram, int toknumPol, boolean empty, boolean ngram) { //System.err.println(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) { // add ngrams to the feature vector while (!ngrams.isEmpty()) { String ng = featureFromArray(ngrams, prefix); //if the current lemma is in the ngram list activate the feature in the vector if (params.containsKey("lemmaNgrams") && (!params.getProperty("lemmaNgrams").equalsIgnoreCase("0"))) { // add occurrence to feature vector (the functions checks if the given ngram feature exists). addNumericToFeatureVector(ng, fVector, toknumNgram); //tokNum } ng = featureFromArray(ngrams, ""); if (params.containsKey("polarLexiconGeneral") || params.containsKey("polarLexiconDomain")) { checkPolarityLexicons(ng, fVector, toknumPol, ngram); } //end polarity ngram checker ngrams.removeFirst(); } //end ngram checking } // if empty is false search for all ngrams in the window else { // add ngrams to the feature vector for (int i = 0; i < ngrams.size(); i++) { String ng = featureFromArray(ngrams.subList(0, i + 1), prefix); //if the current lemma is in the ngram list activate the feature in the vector if (params.containsKey("lemmaNgrams") && (!params.getProperty("lemmaNgrams").equalsIgnoreCase("0"))) { // add occurrence to feature vector (the functions checks if the given ngram feature exists). addNumericToFeatureVector(ng, fVector, toknumNgram); //tokNum } ng = featureFromArray(ngrams.subList(0, i + 1), ""); if (params.containsKey("polarLexiconGeneral") || params.containsKey("polarLexiconDomain")) { checkPolarityLexicons(ng, fVector, toknumPol, ngram); } //end polarity ngram checker } //end ngram checking } }
From source file:org.ocsoft.rosetto.models.base.elements.values.ListValue.java
/** * ????????.//from w ww. j ava2s . c o m * ????????????????. * ???????????. * ????ActionCall??. * @param func ?? * @return ???? */ public Map<String, RosettoValue> bind(RosettoFunction func, Scope currentScope) { if (func == null) throw new IllegalArgumentException("???null??"); //?? Map<String, RosettoValue> result = new HashMap<String, RosettoValue>(); //???? LinkedList<String> funcArgs = new LinkedList<String>(); //??????????? int requiredArgsCount = 0; //???????? for (String s : func.getArguments()) { int eqIndex = s.indexOf("="); if (eqIndex == -1) { //????????? funcArgs.add(s); //???????? requiredArgsCount++; } else { //???? String key = s.substring(0, eqIndex); RosettoValue value = Values.create(s.substring(eqIndex + 1, s.length())); //? funcArgs.add(key); //??????? result.put(key, value); } } //?????? //?? for (Entry<String, RosettoValue> e : getMap().entrySet()) { //?Entry??funcArgs?????funcArg boolean removed = funcArgs.remove(e.getKey()); //???? if (removed) requiredArgsCount--; //?? result.put(e.getKey(), e.getValue()); } //?? String mutableArg = searchMutableArg(funcArgs); if (mutableArg != null) { //???????? //???????? //??????????-1 if (requiredArgsCount - 1 > getList().size()) { throw new IllegalArgumentException("???????: " + getList().toString() + "|" + func.getArguments()); } //???????????????? //?? List<RosettoValue> margs = new LinkedList<RosettoValue>(); for (int i = 0; i < getList().size(); i++) { RosettoValue v = getList().get(i); if (!funcArgs.isEmpty()) { //???????????pop????????? String farg = funcArgs.pollFirst(); //?????????? if (farg.equals(mutableArg)) { //?????????????? if (!funcArgs.isEmpty()) { throw new IllegalArgumentException("mutable args must be last element"); } //?? margs.add(v); } //???????? result.put(farg, v); } else { //?? margs.add(v); } } //????? if (margs.size() > 0) { //????? String margName = mutableArg.substring(1); //listvalue??? result.put(margName, new ListValue(margs)); } } else { //??????? if (requiredArgsCount > getList().size()) { throw new IllegalArgumentException("???????: " + getList().toString() + "|" + func.getArguments()); } else if (funcArgs.size() < getList().size()) { throw new IllegalArgumentException( "?????: " + getList().toString() + "|" + func.getArguments()); } for (RosettoValue value : getList()) { //????????? if (value.getType() == ValueType.ACTION_CALL) { //ActionCall?????? result.put(funcArgs.pollFirst(), ((ActionCall) value).evaluate(currentScope)); } else { result.put(funcArgs.pollFirst(), value); } } } return result; }
From source file:org.apache.fop.layoutmgr.AbstractBreaker.java
/** * Justifies the boxes and returns them as a new KnuthSequence. * @param blockList block list to justify * @param alg reference to the algorithm instance * @param availableBPD the available BPD * @return the effective list// w ww . j a v a 2s . c o m */ private BlockSequence justifyBoxes // CSOK: MethodLength (BlockSequence blockList, PageBreakingAlgorithm alg, int availableBPD) { int optimalPageCount; alg.setConstantLineWidth(availableBPD); optimalPageCount = alg.findBreakingPoints(blockList, /*availableBPD,*/ 1, true, BreakingAlgorithm.ALL_BREAKS); log.debug("PLM> optimalPageCount= " + optimalPageCount); // ListIterator<KnuthElement> sequenceIterator = blockList.listIterator(); ListIterator<PageBreakPosition> breakIterator = alg.getPageBreaks().listIterator(); KnuthElement thisElement = null; PageBreakPosition thisBreak; int adjustedDiff; // difference already adjusted while (breakIterator.hasNext()) { thisBreak = breakIterator.next(); if (log.isDebugEnabled()) { log.debug("| first page: break= " + thisBreak.getLeafPos() + " difference= " + thisBreak.difference + " ratio= " + thisBreak.bpdAdjust); } adjustedDiff = 0; // glue and penalty items at the beginning of the page must // be ignored: // the first element returned by sequenceIterator.next() // inside the // while loop must be a box KnuthElement firstElement; while (sequenceIterator.hasNext()) { firstElement = sequenceIterator.next(); if (!firstElement.isBox()) { log.debug("PLM> ignoring glue or penalty element " + "at the beginning of the sequence"); if (firstElement.isGlue()) { ((BlockLevelLayoutManager) firstElement.getLayoutManager()) .discardSpace((KnuthGlue) firstElement); } } else { break; } } sequenceIterator.previous(); // scan the sub-sequence representing a page, // collecting information about potential adjustments MinOptMax lineNumberMaxAdjustment = MinOptMax.ZERO; MinOptMax spaceMaxAdjustment = MinOptMax.ZERO; LinkedList<KnuthGlue> blockSpacesList = new LinkedList<KnuthGlue>(); LinkedList<KnuthGlue> unconfirmedList = new LinkedList<KnuthGlue>(); LinkedList<KnuthGlue> adjustableLinesList = new LinkedList<KnuthGlue>(); boolean bBoxSeen = false; while (sequenceIterator.hasNext() && sequenceIterator.nextIndex() <= thisBreak.getLeafPos()) { thisElement = sequenceIterator.next(); if (thisElement.isGlue()) { // glue elements are used to represent adjustable // lines // and adjustable spaces between blocks KnuthGlue thisGlue = (KnuthGlue) thisElement; Adjustment adjustment = thisGlue.getAdjustmentClass(); if (adjustment.equals(Adjustment.SPACE_BEFORE_ADJUSTMENT) || adjustment.equals(Adjustment.SPACE_AFTER_ADJUSTMENT)) { // potential space adjustment // glue items before the first box or after the // last one // must be ignored unconfirmedList.add(thisGlue); } else if (adjustment.equals(Adjustment.LINE_NUMBER_ADJUSTMENT)) { // potential line number adjustment lineNumberMaxAdjustment = lineNumberMaxAdjustment.plusMax(thisElement.getStretch()); lineNumberMaxAdjustment = lineNumberMaxAdjustment.minusMin(thisElement.getShrink()); adjustableLinesList.add(thisGlue); } else if (adjustment.equals(Adjustment.LINE_HEIGHT_ADJUSTMENT)) { // potential line height adjustment } } else if (thisElement.isBox()) { if (!bBoxSeen) { // this is the first box met in this page bBoxSeen = true; } else { while (!unconfirmedList.isEmpty()) { // glue items in unconfirmedList were not after // the last box // in this page; they must be added to // blockSpaceList KnuthGlue blockSpace = unconfirmedList.removeFirst(); spaceMaxAdjustment = spaceMaxAdjustment.plusMax(blockSpace.getStretch()); spaceMaxAdjustment = spaceMaxAdjustment.minusMin(blockSpace.getShrink()); blockSpacesList.add(blockSpace); } } } } log.debug("| line number adj= " + lineNumberMaxAdjustment); log.debug("| space adj = " + spaceMaxAdjustment); if (thisElement.isPenalty() && thisElement.getWidth() > 0) { log.debug(" mandatory variation to the number of lines!"); ((BlockLevelLayoutManager) thisElement.getLayoutManager()) .negotiateBPDAdjustment(thisElement.getWidth(), thisElement); } if (thisBreak.bpdAdjust != 0 && (thisBreak.difference > 0 && thisBreak.difference <= spaceMaxAdjustment.getMax()) || (thisBreak.difference < 0 && thisBreak.difference >= spaceMaxAdjustment.getMin())) { // modify only the spaces between blocks adjustedDiff += adjustBlockSpaces(blockSpacesList, thisBreak.difference, (thisBreak.difference > 0 ? spaceMaxAdjustment.getMax() : -spaceMaxAdjustment.getMin())); log.debug("single space: " + (adjustedDiff == thisBreak.difference || thisBreak.bpdAdjust == 0 ? "ok" : "ERROR")); } else if (thisBreak.bpdAdjust != 0) { adjustedDiff += adjustLineNumbers(adjustableLinesList, thisBreak.difference, (thisBreak.difference > 0 ? lineNumberMaxAdjustment.getMax() : -lineNumberMaxAdjustment.getMin())); adjustedDiff += adjustBlockSpaces(blockSpacesList, thisBreak.difference - adjustedDiff, ((thisBreak.difference - adjustedDiff) > 0 ? spaceMaxAdjustment.getMax() : -spaceMaxAdjustment.getMin())); log.debug("lines and space: " + (adjustedDiff == thisBreak.difference || thisBreak.bpdAdjust == 0 ? "ok" : "ERROR")); } } // create a new sequence: the new elements will contain the // Positions // which will be used in the addAreas() phase BlockSequence effectiveList = new BlockSequence(blockList.getStartOn(), blockList.getDisplayAlign()); effectiveList.addAll(getCurrentChildLM().getChangedKnuthElements( blockList.subList(0, blockList.size() - blockList.ignoreAtEnd), /* 0, */0)); //effectiveList.add(new KnuthPenalty(0, -KnuthElement.INFINITE, // false, new Position(this), false)); effectiveList.endSequence(); ElementListObserver.observe(effectiveList, "breaker-effective", null); alg.getPageBreaks().clear(); //Why this? return effectiveList; }
From source file:com.redsqirl.workflow.server.Workflow.java
/** * Do sort of the workflow.// www . j a v a2 s.c o m * * If the sort is successful, it is a DAG * * @return null if OK, or a description of the error. * @throws RemoteException */ public String topoligicalSort() throws RemoteException { String error = null; LinkedList<DataFlowElement> newList = new LinkedList<DataFlowElement>(); LinkedList<DataFlowElement> queueList = new LinkedList<DataFlowElement>(); Iterator<DataFlowElement> iconIt = element.iterator(); while (iconIt.hasNext()) { DataFlowElement cur = iconIt.next(); if (cur.getInputComponent().values().size() == 0) { queueList.add(cur); } } while (!queueList.isEmpty()) { newList.add(queueList.removeFirst()); iconIt = element.iterator(); while (iconIt.hasNext()) { DataFlowElement cur = iconIt.next(); if (!newList.contains(cur) && !queueList.contains(cur)) { Iterator<List<DataFlowElement>> it = cur.getInputComponent().values().iterator(); boolean allThere = true; while (it.hasNext() && allThere) { allThere = newList.containsAll(it.next()); } if (allThere) { queueList.add(cur); } } } } if (newList.size() < element.size()) { error = LanguageManagerWF.getText("workflow.topologicalSort"); } else { element = newList; } return error; }
From source file:org.diorite.impl.inventory.recipe.craft.ShapelessCraftingRecipeImpl.java
@Override public CraftingRecipeCheckResult isMatching(final GridInventory inventory) { final Player player = (inventory.getHolder() instanceof Player) ? (Player) inventory.getHolder() : null; final Short2ObjectMap<ItemStack> onCraft = new Short2ObjectOpenHashMap<>(2, .5F); final int maxInvRow = inventory.getRows(), maxInvCol = inventory.getColumns(); final LinkedList<CraftingRecipeItem> ingredients = new LinkedList<>(this.getIngredients()); final Collection<CraftingRepeatableRecipeItem> repeatableIngredients = new LinkedList<>( this.getRepeatableIngredients()); final Collection<BiConsumer<Player, CraftingGrid>> reps = new ArrayList<>(maxInvCol * maxInvRow); final CraftingGrid items = new CraftingGridImpl(maxInvRow, maxInvCol); int col = -1, row = 0; ItemStack result;/*from w w w .ja v a 2 s . c o m*/ if (this.repeatableIngredients.isEmpty()) { for (short i = 1, size = (short) inventory.size(); i < size; i++) { if (++col >= maxInvCol) { col = 0; if (++row > maxInvRow) { throw new IllegalStateException("Inventory is larger than excepted."); } } final ItemStack item = inventory.getItem(i); if (item == null) { continue; } boolean matching = false; //noinspection Duplicates for (final Iterator<CraftingRecipeItem> iterator = ingredients.iterator(); iterator.hasNext();) { final CraftingRecipeItem ingredient = iterator.next(); final ItemStack valid = ingredient.isValid(player, item); if (valid != null) { final short icpy = i; reps.add((p, c) -> { final ItemStack repl = ingredient.getReplacement(p, c); if (repl != null) { onCraft.put(icpy, repl); } }); items.setItem(row, col, valid); iterator.remove(); matching = true; break; } } if (!matching) { return null; } } result = (this.resultFunc == null) ? this.result : this.resultFunc.apply(player, items.clone()); } else { final Map<CraftingRepeatableRecipeItem, List<ItemStack>> repeatableItems = new IdentityHashMap<>( this.repeatableIngredients.size()); for (short i = 1, size = (short) inventory.size(); i < size; i++) { if (++col >= maxInvCol) { col = 0; if (++row > maxInvRow) { throw new IllegalStateException("Inventory is larger than excepted."); } } final ItemStack item = inventory.getItem(i); if (item == null) { continue; } boolean matching = false; if (!ingredients.isEmpty()) { //noinspection Duplicates for (final Iterator<CraftingRecipeItem> iterator = ingredients.iterator(); iterator .hasNext();) { final CraftingRecipeItem ingredient = iterator.next(); final ItemStack valid = ingredient.isValid(player, item); if (valid != null) { final short icpy = i; reps.add((p, c) -> { final ItemStack repl = ingredient.getReplacement(p, c); if (repl != null) { onCraft.put(icpy, repl); } }); items.setItem(row, col, valid); iterator.remove(); matching = true; break; } } } if (!matching) { for (final CraftingRepeatableRecipeItem ingredient : this.repeatableIngredients) { final ItemStack valid = ingredient.isValid(player, item); if (valid != null) { final short icpy = i; reps.add((p, c) -> { final ItemStack repl = ingredient.getReplacement(p, c); if (repl != null) { onCraft.put(icpy, repl); } }); List<ItemStack> repItems = repeatableItems.get(ingredient); if (repItems == null) { repeatableIngredients.remove(ingredient); repItems = new ArrayList<>(10); repeatableItems.put(ingredient, repItems); } repItems.add(valid); items.setItem(row, col, valid); matching = true; break; } } } if (!matching) { return null; } } if (!repeatableIngredients.isEmpty()) { return null; } result = (this.resultFunc == null) ? this.result : this.resultFunc.apply(player, items.clone()); for (final Entry<CraftingRepeatableRecipeItem, List<ItemStack>> entry : repeatableItems.entrySet()) { result = entry.getKey().transform(result, entry.getValue()); result = entry.getKey().transform(result, items); } } reps.forEach(c -> c.accept(player, items)); return ingredients.isEmpty() ? new CraftingRecipeCheckResultImpl(this, result, items, onCraft) : null; }
From source file:tokyo.northside.jrst.JRSTLexer.java
/** * read table simple and complexe/* www. j a v a 2s. com*/ * * <pre> * +------------------------+------------+----------+----------+ * | Header row, column 1 | Header 2 | Header 3 | Header 4 | * | (header rows optional) | | | | * +========================+============+==========+==========+ * | body row 1, column 1 | column 2 | column 3 | column 4 | * +------------------------+------------+----------+----------+ * | body row 2 | Cells may span columns. | * +------------------------+------------+---------------------+ * </pre> * * @return Element * @throws IOException */ @SuppressWarnings("unchecked") public Element peekTable() throws IOException { beginPeek(); Element result = null; // in.skipBlankLines(); String line = in.readLine(); if (line != null) { Pattern pTableBegin = Pattern.compile("^\\s*(\\+-+)+\\+\\s*$"); Matcher matcher = null; matcher = pTableBegin.matcher(line); if (matcher.matches()) { // complexe table result = DocumentHelper.createElement(TABLE); result.addAttribute(TABLE_HEADER, FALSE); int level = level(line); result.addAttribute(LEVEL, String.valueOf(level)); line = line.trim(); int tableWidth = line.length(); result.addAttribute(TABLE_WIDTH, String.valueOf(tableWidth)); Pattern pCellEnd = Pattern .compile("^\\s{" + level + "}(\\+-+\\+|\\|(?:[^+]+))([^+]+(?:\\+|\\|\\s*$)|-+\\+)*\\s*"); // fin // de // ligne Pattern pCell = Pattern.compile("^\\s{" + level + "}(\\|[^|]+)+\\|\\s*$"); // une ligne Pattern pHeader = Pattern.compile("^\\s{" + level + "}(\\+=+)+\\+\\s*$"); // fin du header Pattern pEnd = Pattern.compile("^\\s{" + level + "}(\\+-+)+\\+\\s*$"); // fin de table // used to know if | is cell separator or not String lastSeparationLine = line; String lastLine = line; Element row = DocumentHelper.createElement(ROW); String[] table = in.readUntilBlank(); boolean done = false; for (String l : table) { done = false; l = l.trim(); if (l.length() != tableWidth) { // Erreur dans la table, peut-etre lever une exception ? result = null; break; } matcher = pEnd.matcher(l); if (!done && matcher.matches()) { // fin normale de ligne, on peut directement l'assigner lastSeparationLine = l; for (Element cell : (List<Element>) row.elements()) { cell.addAttribute(CELL_END, TRUE); } row.addAttribute(ROW_END_HEADER, FALSE); result.add(row); row = DocumentHelper.createElement(ROW); done = true; } matcher = pHeader.matcher(l); if (!done && matcher.matches()) { // fin de du header, on peut directement l'assigner lastSeparationLine = l; for (Element cell : (List<Element>) row.elements()) { cell.addAttribute(CELL_END, TRUE); } row.addAttribute(ROW_END_HEADER, TRUE); result.add(row); result.addAttribute(TABLE_HEADER, TRUE); row = DocumentHelper.createElement(ROW); done = true; } matcher = pCell.matcher(l); if (!done && matcher.matches()) { // debug row.addAttribute("debug", "pCell"); // recuperation des textes des cellules int start = -1; String content = ""; matcher = Pattern.compile("([^|]+)\\|").matcher(l); for (int cellNumber = 0; matcher.find(); cellNumber++) { int tmpstart = matcher.start(1); int end = matcher.end(1); String tmpcontent = matcher.group(1); // on a forcement un | ou un + au dessus du + // et forcement un + sur lastSeparationLine // sinon ca veut dire qu'il y avait un | dans la // cell if ((lastLine.charAt(end) == '|' || lastLine.charAt(end) == '+') && lastSeparationLine.charAt(end) == '+') { if ("".equals(content)) { content = tmpcontent; } else { content += tmpcontent; } if (start == -1) { start = tmpstart; } Element cell = null; if (row.nodeCount() <= cellNumber) { cell = row.addElement(CELL); cell.addAttribute(CELL_END, FALSE); } else { cell = (Element) row.node(cellNumber); } cell.addAttribute(CELL_INDEX_START, String.valueOf(start)); cell.addAttribute(CELL_INDEX_END, String.valueOf(end)); cell.setText(cell.getText() + content + "\n"); start = end + 1; // +1 to pass + or | at end // of cell content = ""; } else { // start = tmpstart; if (start == -1) { start = tmpstart; } content += tmpcontent + "|"; cellNumber--; } } done = true; } matcher = pCellEnd.matcher(l); if (!done && matcher.matches()) { // debug row.addAttribute("debug", "pCellEnd"); // fin d'une ligne, on ne peut pas l'assigner // directement // pour chaque continuation de cellule, il faut copier // l'ancienne valeur // mais on commence tout de meme par fermer tout les // cells for (Element cell : (List<Element>) row.elements()) { cell.addAttribute(CELL_END, TRUE); } StringBuffer tmp = new StringBuffer(l); int start = -1; String content = ""; matcher = Pattern.compile("([^+|]+|-+)([+|])").matcher(l); for (int cellNumber = 0; matcher.find(); cellNumber++) { int tmpstart = matcher.start(1); int end = matcher.end(1); String tmpcontent = matcher.group(1); String ender = matcher.group(2); if (!tmpcontent.matches("-+")) { // on a forcement un | au dessus du + ou du | // sinon ca veut dire qu'il y avait un + dans la // cell if (lastLine.charAt(end) == '|') { if (start == -1) { start = tmpstart; } // -1 and +1 to take the + or | at begin and // end String old = lastSeparationLine.substring(start - 1, end + 1); tmp.replace(start - 1, end + 1, old); if ("".equals(content)) { content = tmpcontent; } Element cell = null; if (row.nodeCount() <= cellNumber) { cell = row.addElement(CELL); } else { cell = (Element) row.node(cellNumber); } cell.setText(cell.getText() + content + "\n"); // on a ajouter des choses dans la cell, // donc // ce n'est pas la fin cell.addAttribute(CELL_END, FALSE); cell.addAttribute(CELL_INDEX_START, String.valueOf(start)); cell.addAttribute(CELL_INDEX_END, String.valueOf(end)); start = end + 1; // +1 to pass + or | at // end of cell content = ""; } else { // start = tmpstart; content += tmpcontent + ender; } } } lastSeparationLine = tmp.toString(); row.addAttribute(ROW_END_HEADER, FALSE); result.add(row); row = DocumentHelper.createElement(ROW); done = true; } if (!done) { log.warn("Bad table format line " + in.getLineNumber()); } lastLine = l; } // // line += "\n" + joinBlock(table, "\n", false); // // result.addText(line); } else if (line.matches("^\\s*(=+ +)+=+\\s*$")) { // Les donnees de la table peuvent depasser de celle-ci /* * ===== ===== ====== Inputs Output ------------ ------ A B A or * B ===== ===== ====== False False Second column of row 1. True * False Second column of row 2. * * True 2 - Second column of row 3. * * - Second item in bullet list (row 3, column 2). ============ * ====== */ result = DocumentHelper.createElement(TABLE); line = line.trim(); Pattern pBordersEquals = Pattern.compile("^\\s*(=+ +)+=+\\s*$"); // Separation // = Pattern pBordersTiret = Pattern.compile("^\\s*(-+ +)+-+\\s*$"); // Separation // - Pattern pBorders = Pattern.compile("^\\s*([=-]+ +)+[=-]+\\s*$"); // = // ou // - String[] table = in.readUntilBlank(); // Recuperation de la // table int tableWidth = line.length(); int nbSeparations = 0; for (String l : table) { if (l.length() > tableWidth) { tableWidth = l.length(); // Determination de la } // Determination de la // longueur max matcher = pBordersEquals.matcher(l); if (matcher.matches()) { nbSeparations++; } } // Header if the table contains 3 equals separations result.addAttribute(TABLE_HEADER, "" + (nbSeparations == 2)); int level = level(line); result.addAttribute(LEVEL, String.valueOf(level)); result.addAttribute(TABLE_WIDTH, String.valueOf(tableWidth + 1)); Element row = DocumentHelper.createElement(ROW); // Determination of the columns positions List<Integer> columns = new LinkedList<Integer>(); matcher = Pattern.compile("=+\\s+").matcher(line); for (int cellNumber = 0; matcher.find(); cellNumber++) { columns.add(matcher.end()); } columns.add(tableWidth); // Traitement du tbl /* * ===== ===== ====== Inputs Output ------------ ------ A B A or * B ===== ===== ====== False False Second column of row 1. True * False Second column of row 2. * * True 2 - Second column of row 3. * * - Second item in bullet list (row 3, column 2). ============ * ====== devient l'equivalent : ===== ===== ====== Inputs * Output ------------ ------ A B A or B ===== ===== ====== * False False Second column of row 1. ----- ----- ------ True * False Second column of row 2. ----- ----- ------ True 2 - * Second column of row 3. - Second item in bullet list (row 3, * column 2). ============ ====== */ String lineRef = line.replace('=', '-'); Matcher matcher2; List<String> tableTmp = new LinkedList<String>(); for (int i = 0; i < table.length - 1; i++) { tableTmp.add(table[i]); if (!table[i].equals("")) { if (!table[i + 1].substring(0, columns.get(0)).matches("\\s*")) { matcher = pBorders.matcher(table[i]); matcher2 = pBorders.matcher(table[i + 1]); if (!matcher.matches() && !matcher2.matches() && !table[i + 1].equals("")) { tableTmp.add(lineRef); } } } } tableTmp.add(table[table.length - 1]); table = new String[tableTmp.size()]; for (int i = 0; i < tableTmp.size(); i++) { table[i] = tableTmp.get(i); } boolean done = false; LinkedList<String> lastLines = new LinkedList<String>(); int separation = 1; for (String l : table) { if (l != null) { done = false; matcher = pBordersTiret.matcher(l); matcher2 = pBordersEquals.matcher(l); if (matcher.matches() || matcher2.matches()) { // Intermediate // separation while (!lastLines.isEmpty()) { matcher = Pattern.compile("[-=]+\\s*").matcher(l); String tmpLine = lastLines.getLast(); lastLines.removeLast(); int cellNumber; for (cellNumber = 0; matcher.find(); cellNumber++) { Element cell = null; if (row.nodeCount() <= cellNumber) { cell = row.addElement(CELL); } else { cell = (Element) row.node(cellNumber); } if (matcher.start() < tmpLine.length()) { if (columns.size() - 1 == cellNumber) { cell.setText( tmpLine.substring(matcher.start(), tmpLine.length()) + "\n"); } else { if (matcher.end() < tmpLine.length()) { cell.setText( tmpLine.substring(matcher.start(), matcher.end()) + "\n"); } else { cell.setText(tmpLine.substring(matcher.start(), tmpLine.length()) + "\n"); } } } if (lastLines.size() == 0) { row.addAttribute("debug", "pCell"); cell.addAttribute(CELL_END, TRUE); } else { row.addAttribute("debug", "pCellEnd"); cell.addAttribute(CELL_END, FALSE); } cell.addAttribute(CELL_INDEX_START, String.valueOf(matcher.start() + 1)); if (line.length() == matcher.end()) { cell.addAttribute(CELL_INDEX_END, String.valueOf(columns.get(columns.size() - 1))); } else { cell.addAttribute(CELL_INDEX_END, String.valueOf(matcher.end())); } } if (matcher2.matches()) { separation++; row.addAttribute(ROW_END_HEADER, "" + (separation == 2)); } else { row.addAttribute(ROW_END_HEADER, FALSE); } result.add(row); row = DocumentHelper.createElement(ROW); done = true; } } if (!done && l.matches("^\\s*(.+ +)+.+\\s*$")) { // Data lastLines.addFirst(l); // Les donnees sont stoquee // dans une file d'attente // lastLines (FIFO) done = true; } if (!done) { log.warn("Bad table format line " + in.getLineNumber()); } } } } } endPeek(); return result; }
From source file:elh.eus.absa.Features.java
/** * Extract word form n-grams up to a certain length from a kaf/naf file * //from w w w . jav a 2 s . co m * @param int length : which 'n' use for 'n-grams' * @param KAFDocument kafDoc : postagged kaf document to extract ngrams from. * @param boolean save : safe ngrams to file or not. * @return TreeSet<String> return word form ngrams of length length */ private int extractWfNgramsKAF(int length, KAFDocument kafDoc, boolean save) { //System.err.println("ngram extraction: _"+length+"_"); if (length == 0) { return 0; } for (List<WF> sent : kafDoc.getSentences()) { LinkedList<String> ngrams = new LinkedList<String>(); for (WF wf : sent) { if (ngrams.size() >= length) { ngrams.removeFirst(); } ngrams.add(wf.getForm()); //ngrams.add(normalize(wf.getForm(), params.getProperty("normalization", "none"))); // add ngrams to the feature list for (int i = 0; i < ngrams.size(); i++) { String ng = featureFromArray(ngrams.subList(0, i + 1), "wf"); addNgram("wf", ng); } } //empty ngram list and add remaining ngrams to the feature list while (!ngrams.isEmpty()) { String ng = featureFromArray(ngrams, "wf"); addNgram("wf", ng); ngrams.removeFirst(); } } return 1; }
From source file:elh.eus.absa.Features.java
/** * POS ngram extraction from a kaf document * // ww w . j a v a2s . co m * @param int length : which 'n' use for 'n-grams' * @param KAFDocument kafDoc : postagged kaf document to extract ngrams from. * @param boolean save : safe ngrams to file or not. * @return TreeSet<String> return lemma ngrams of length length */ public int extractPosNgrams(int length, KAFDocument kafDoc, List<String> discardPos, boolean save) { //System.err.println("POS ngram extraction: _"+length+"_"); if (length == 0) { return 0; } int sentNum = kafDoc.getSentences().size(); for (int s = 0; s < sentNum; s++) { LinkedList<String> ngrams = new LinkedList<String>(); for (Term term : kafDoc.getTermsBySent(s)) { if (ngrams.size() >= length) { ngrams.removeFirst(); } if (!discardPos.contains(term.getPos())) { ngrams.add(term.getPos()); } // add ngrams to the feature list for (int i = 0; i < ngrams.size(); i++) { String ng = featureFromArray(ngrams.subList(0, i + 1), "pos"); addNgram("pos", ng); } } //empty ngram list and add remaining ngrams to the feature list while (!ngrams.isEmpty()) { String ng = featureFromArray(ngrams, "pos"); addNgram("pos", ng); ngrams.removeFirst(); } } return 1; }
From source file:cnedu.ustcjd.widget.MultiSlider.java
/** * Get closest thumb to play with,//from w ww. j ava2 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.isEnabled() || mDraggingThumbs.contains(thumb)) 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:com.google.dart.engine.services.completion.CompletionEngine.java
private void currentLibraryLister(LinkedList<LibraryElement> queue, Set<LibraryElement> libraries) { while (!queue.isEmpty()) { LibraryElement sourceLib = queue.removeFirst(); libraries.add(sourceLib);// w ww . j a v a 2s . c o m LibraryElement[] expLibs = sourceLib.getExportedLibraries(); for (LibraryElement lib : expLibs) { if (!libraries.contains(lib)) { queue.add(lib); } } } }