Example usage for java.util Vector set

List of usage examples for java.util Vector set

Introduction

In this page you can find the example usage for java.util Vector set.

Prototype

public synchronized E set(int index, E element) 

Source Link

Document

Replaces the element at the specified position in this Vector with the specified element.

Usage

From source file:edu.stanford.cfuller.imageanalysistools.filter.ConvexHullByLabelFilter.java

/**
 * Applies the convex hull filter to the supplied mask.
 * @param im    The Image to process-- a mask whose regions will be replaced by their filled convex hulls.
 *//*w w w  .ja  v a  2 s. co  m*/
@Override
public void apply(WritableImage im) {

    RelabelFilter RLF = new RelabelFilter();

    RLF.apply(im);

    Histogram h = new Histogram(im);

    java.util.Hashtable<Integer, java.util.Vector<Integer>> xLists = new java.util.Hashtable<Integer, java.util.Vector<Integer>>();
    java.util.Hashtable<Integer, java.util.Vector<Integer>> yLists = new java.util.Hashtable<Integer, java.util.Vector<Integer>>();

    java.util.Vector<Integer> minValues = new java.util.Vector<Integer>(h.getMaxValue() + 1);
    java.util.Vector<Integer> minIndices = new java.util.Vector<Integer>(h.getMaxValue() + 1);

    for (int i = 0; i < h.getMaxValue() + 1; i++) {
        minValues.add(im.getDimensionSizes().get(ImageCoordinate.X));
        minIndices.add(0);
    }

    for (ImageCoordinate i : im) {

        int value = (int) im.getValue(i);

        if (value == 0)
            continue;

        if (!xLists.containsKey(value)) {
            xLists.put(value, new java.util.Vector<Integer>());
            yLists.put(value, new java.util.Vector<Integer>());
        }

        xLists.get(value).add(i.get(ImageCoordinate.X));
        yLists.get(value).add(i.get(ImageCoordinate.Y));

        if (i.get(ImageCoordinate.X) < minValues.get(value)) {
            minValues.set(value, i.get(ImageCoordinate.X));
            minIndices.set(value, xLists.get(value).size() - 1);
        }

    }

    java.util.Vector<Integer> hullPointsX = new java.util.Vector<Integer>();
    java.util.Vector<Integer> hullPointsY = new java.util.Vector<Integer>();

    ImageCoordinate ic = ImageCoordinate.createCoordXYZCT(0, 0, 0, 0, 0);

    for (int k = 1; k < h.getMaxValue() + 1; k++) {
        hullPointsX.clear();
        hullPointsY.clear();

        java.util.Vector<Integer> xList = xLists.get(k);
        java.util.Vector<Integer> yList = yLists.get(k);

        int minIndex = (int) minIndices.get(k);

        //start at the leftmost point

        int currentIndex = minIndex;
        int currentX = xList.get(currentIndex);
        int currentY = yList.get(currentIndex);

        hullPointsX.add(currentX);
        hullPointsY.add(currentY);

        org.apache.commons.math3.linear.RealVector angles = new org.apache.commons.math3.linear.ArrayRealVector(
                xList.size());

        Vector3D currentVector = new Vector3D(0, -1, 0);

        java.util.HashSet<Integer> visited = new java.util.HashSet<Integer>();

        do {

            visited.add(currentIndex);

            int maxIndex = 0;
            double maxAngle = -2 * Math.PI;
            double dist = Double.MAX_VALUE;
            for (int i = 0; i < xList.size(); i++) {
                if (i == currentIndex)
                    continue;
                Vector3D next = new Vector3D(xList.get(i) - xList.get(currentIndex),
                        yList.get(i) - yList.get(currentIndex), 0);

                double angle = Vector3D.angle(currentVector, next);
                angles.setEntry(i, angle);
                if (angle > maxAngle) {
                    maxAngle = angle;
                    maxIndex = i;
                    dist = next.getNorm();
                } else if (angle == maxAngle) {
                    double tempDist = next.getNorm();
                    if (tempDist < dist) {
                        dist = tempDist;
                        maxAngle = angle;
                        maxIndex = i;
                    }
                }
            }

            currentX = xList.get(maxIndex);
            currentY = yList.get(maxIndex);

            currentVector = new Vector3D(xList.get(currentIndex) - currentX, yList.get(currentIndex) - currentY,
                    0);

            hullPointsX.add(currentX);
            hullPointsY.add(currentY);

            currentIndex = maxIndex;

        } while (!visited.contains(currentIndex));

        //hull vertices have now been determined .. need to fill in the lines
        //between them so I can apply a fill filter

        //approach: x1, y1 to x0, y0:
        //start at min x, min y, go to max x, max y
        // if x_i, y_i = x0, y0  + slope to within 0.5 * sqrt(2), then add to hull

        double eps = Math.sqrt(2);

        for (int i = 0; i < hullPointsX.size() - 1; i++) {

            int x0 = hullPointsX.get(i);
            int y0 = hullPointsY.get(i);

            int x1 = hullPointsX.get(i + 1);
            int y1 = hullPointsY.get(i + 1);

            int xmin = (x0 < x1) ? x0 : x1;
            int ymin = (y0 < y1) ? y0 : y1;
            int xmax = (x0 > x1) ? x0 : x1;
            int ymax = (y0 > y1) ? y0 : y1;

            x1 -= x0;
            y1 -= y0;

            double denom = (x1 * x1 + y1 * y1);

            for (int x = xmin; x <= xmax; x++) {
                for (int y = ymin; y <= ymax; y++) {

                    int rel_x = x - x0;
                    int rel_y = y - y0;

                    double projLength = (x1 * rel_x + y1 * rel_y) / denom;

                    double projPoint_x = x1 * projLength;
                    double projPoint_y = y1 * projLength;

                    if (Math.hypot(rel_x - projPoint_x, rel_y - projPoint_y) < eps) {
                        ic.set(ImageCoordinate.X, x);
                        ic.set(ImageCoordinate.Y, y);
                        im.setValue(ic, k);
                    }

                }
            }

        }

    }

    ic.recycle();

    FillFilter ff = new FillFilter();

    ff.apply(im);

}

From source file:edu.ku.brc.specify.tasks.subpane.wb.ConfigureXLS.java

/**
 * Fills badHeads with indexes for columns that contain data but don't have a header or have an non-string header (because it makes things difficult with HSSF).
 * Fills emptyCols with indexes for columns that are totally empty.
 * Assumes that badHeads and emptyCols are not null and empty.
 * /* w ww .  j  a v a  2 s  .  c om*/
 */
public void checkHeadsAndCols(final HSSFSheet sheet, Vector<Integer> badHeads, Vector<Integer> emptyCols) {
    boolean firstRow = true;
    Vector<Boolean> firstRowCells = new Vector<Boolean>();
    Vector<Boolean> restCells = new Vector<Boolean>();

    // Iterate over each row in the sheet
    Iterator<?> rows = sheet.rowIterator();
    while (rows.hasNext()) {
        HSSFRow row = (HSSFRow) rows.next();
        int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
        for (int col = 0; col < maxSize; col++) {
            if (firstRow) {
                if (row.getCell(col) == null) {
                    firstRowCells.add(false);
                } else if (row.getCell(col).getCellType() == HSSFCell.CELL_TYPE_STRING) {
                    firstRowCells.add(true);
                } else {
                    firstRowCells.add(null);
                }
            } else {
                if (col == restCells.size()) {
                    restCells.add(false);
                }
                if (!restCells.get(col)) {
                    restCells.set(col, row.getCell(col) != null);
                }
            }
        }
        firstRow = false;
    }

    //pad smaller vector with false if necessary.
    while (restCells.size() < firstRowCells.size()) {
        restCells.add(false);
    }
    while (firstRowCells.size() < restCells.size()) {
        firstRowCells.add(false);
    }

    for (int c = 0; c < firstRowCells.size(); c++) {
        if (firstRowCells.get(c) == null || (!firstRowCells.get(c) && restCells.get(c))) {
            badHeads.add(c);
        }
        if (firstRowCells.get(c) != null && !firstRowCells.get(c) && !restCells.get(c)) {
            emptyCols.add(c);
        }
    }
}

From source file:edu.cmu.tetrad.search.Ling.java

/**
 * This is the method used in Patrik's code.
 *///from  w w  w.  j  a  v a  2  s .  c o m
public DoubleMatrix2D pruneEdgesByResampling(DoubleMatrix2D data) {
    Matrix X = new DenseMatrix(data.viewDice().toArray());

    int npieces = 10;
    int cols = X.numColumns();
    int rows = X.numRows();
    int piecesize = (int) Math.floor(cols / npieces);

    List<Matrix> bpieces = new ArrayList<Matrix>();
    List<no.uib.cipr.matrix.Vector> diststdpieces = new ArrayList<no.uib.cipr.matrix.Vector>();
    List<no.uib.cipr.matrix.Vector> cpieces = new ArrayList<no.uib.cipr.matrix.Vector>();

    for (int p = 0; p < npieces; p++) {

        //          % Select subset of data, and permute the variables to the causal order
        //          Xp = X(k,((p-1)*piecesize+1):(p*piecesize));

        int p0 = (p) * piecesize;
        int p1 = (p + 1) * piecesize - 1;
        int[] range = range(p0, p1);

        Matrix Xp = X;

        //          % Remember to subract out the mean
        //          Xpm = mean(Xp,2);
        //          Xp = Xp - Xpm*ones(1,size(Xp,2));
        //
        //          % Calculate covariance matrix
        //          cov = (Xp*Xp')/size(Xp,2);

        double[] Xpm = new double[rows];

        for (int i = 0; i < rows; i++) {
            double sum = 0.0;

            for (int j = 0; j < Xp.numColumns(); j++) {
                sum += Xp.get(i, j);
            }

            Xpm[i] = sum / Xp.numColumns();
        }

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < Xp.numColumns(); j++) {
                Xp.set(i, j, Xp.get(i, j) - Xpm[i]);
            }
        }

        Matrix XpT = new DenseMatrix(Xp.numColumns(), rows);
        Matrix Xpt = Xp.transpose(XpT);

        Matrix cov = new DenseMatrix(rows, rows);
        cov = Xp.mult(Xpt, cov);

        for (int i = 0; i < cov.numRows(); i++) {
            for (int j = 0; j < cov.numColumns(); j++) {
                cov.set(i, j, cov.get(i, j) / Xp.numColumns());
            }
        }

        //          % Do QL decomposition on the inverse square root of cov
        //          [Q,L] = tridecomp(cov^(-0.5),'ql');

        boolean posDef = LingUtils.isPositiveDefinite(new DenseDoubleMatrix2D(Matrices.getArray(cov)));
        //            TetradLogger.getInstance().log("lingamDetails","Positive definite = " + posDef);

        if (!posDef) {
            System.out.println("Covariance matrix is not positive definite.");
        }

        DenseMatrix sqrt;

        try {
            sqrt = sqrt(new DenseMatrix(cov));
        } catch (NotConvergedException e) {
            throw new RuntimeException(e);
        }

        DenseMatrix I = Matrices.identity(rows);
        DenseMatrix AI = I.copy();
        DenseMatrix invSqrt;

        try {
            invSqrt = new DenseMatrix(sqrt.solve(I, AI));
        } catch (MatrixSingularException e) {
            throw new RuntimeException("Singular matrix.", e);
        }

        QL ql = QL.factorize(invSqrt);
        Matrix L = ql.getL();

        //          % The estimated disturbance-stds are one over the abs of the diag of L
        //          newestdisturbancestd = 1./diag(abs(L));

        no.uib.cipr.matrix.Vector newestdisturbancestd = new DenseVector(rows);

        for (int t = 0; t < rows; t++) {
            newestdisturbancestd.set(t, 1.0 / Math.abs(L.get(t, t)));
        }

        //          % Normalize rows of L to unit diagonal
        //          L = L./(diag(L)*ones(1,dims));
        //
        for (int s = 0; s < rows; s++) {
            for (int t = 0; t <= s; t++) {
                L.set(s, t, L.get(s, t) / L.get(s, s));
            }
        }

        //          % Calculate corresponding B
        //          bnewest = eye(dims)-L;

        Matrix bnewest = Matrices.identity(rows);
        bnewest = bnewest.add(-1.0, L);

        no.uib.cipr.matrix.Vector cnewest = new DenseVector(rows);
        cnewest = L.mult(new DenseVector(Xpm), cnewest);

        bpieces.add(bnewest);
        diststdpieces.add(newestdisturbancestd);
        cpieces.add(cnewest);
    }

    //
    //        for i=1:dims,
    //          for j=1:dims,
    //
    //            themean = mean(Bpieces(i,j,:));
    //            thestd = std(Bpieces(i,j,:));
    //            if abs(themean)<prunefactor*thestd,
    //          Bfinal(i,j) = 0;
    //            else
    //          Bfinal(i,j) = themean;
    //            end
    //
    //          end
    //        end

    Matrix means = new DenseMatrix(rows, rows);
    Matrix stds = new DenseMatrix(rows, rows);

    Matrix BFinal = new DenseMatrix(rows, rows);

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < rows; j++) {
            double sum = 0.0;

            for (int y = 0; y < npieces; y++) {
                sum += bpieces.get(y).get(i, j);
            }

            double themean = sum / (npieces);

            double sumVar = 0.0;

            for (int y = 0; y < npieces; y++) {
                sumVar += Math.pow((bpieces.get(y).get(i, j)) - themean, 2);
            }

            double thestd = Math.sqrt(sumVar / (npieces));

            means.set(i, j, themean);
            stds.set(i, j, thestd);

            if (Math.abs(themean) < getPruneFactor() * thestd) {
                BFinal.set(i, j, 0);
            } else {
                BFinal.set(i, j, themean);
            }
        }
    }

    //
    //        diststdfinal = mean(diststdpieces,2);
    //        cfinal = mean(cpieces,2);
    //
    //        % Finally, rename all the variables to the way we defined them
    //        % in the function definition
    //
    //        Bpruned = Bfinal;
    //        stde = diststdfinal;
    //        ci = cfinal;

    return new DenseDoubleMatrix2D(Matrices.getArray(BFinal));
}

From source file:uk.ac.gda.client.experimentdefinition.ExperimentEditorManager.java

private List<IFile> listFilesToOpen(final IExperimentObject ob) {
    Map<String, IFile> mapOfTypesToFiles = ob.getFilesWithTypes();
    Collection<IExperimentBeanDescription> allBeanDescriptions = ExperimentBeanManager.INSTANCE
            .getBeanDescriptions();//from  ww  w .jav a 2  s .co  m

    // reorder Map based on order in allBeanDescriptions as this is the same order registered in the Extension Point
    // which should be the order to be shown in the UI
    mapOfTypesToFiles = orderMapOfTypes(ob, mapOfTypesToFiles, allBeanDescriptions);

    // start list of files to open and list of missing file types
    List<IFile> filteredEditorList = new ArrayList<IFile>();
    for (String fileType : mapOfTypesToFiles.keySet()) {
        IFile file = mapOfTypesToFiles.get(fileType);
        if (file != null && file.exists())
            filteredEditorList.add(file);
        else {
            // now match missing file types to descriptions
            Vector<IExperimentBeanDescription> beansOfType = new Vector<IExperimentBeanDescription>();
            Vector<IExperimentBeanDescription> beanType = new Vector<IExperimentBeanDescription>();
            for (IExperimentBeanDescription beanDesc : allBeanDescriptions) {
                if (beanDesc.getBeanType().equalsIgnoreCase(fileType)) {
                    beansOfType.add(beanDesc);
                    if (beanDesc.includeInNew()) {
                        beanType.add(beanDesc); // only want one here
                        break;
                    }
                }
            }
            // if a problem then take any type.
            if (beanType.size() == 0)
                beanType.set(0, beansOfType.get(0));
            IFile selection;
            if (file == null) {
                XMLFileDialog xmlFileDialog = new XMLFileDialog(
                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), beanType,
                        "Incomplete Setup for " + beanType.get(0).getBeanType(),
                        "The file has not been set yet.\n\n"
                                + "Choose an existing file, or to create a new file, or press Cancel");
                selection = xmlFileDialog.open(ob.getFolder());
            } else {
                XMLFileDialog xmlFileDialog = new XMLFileDialog(
                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), beanType,
                        "Incomplete Setup for " + beanType.get(0).getBeanType(),
                        "The file '" + file.getName() + "' does not exist in '" + file.getParent().getName()
                                + "'\n\n" + "Choose an existing file, create a new file, or press Cancel");
                selection = xmlFileDialog.open(file.getParent());
            }
            if (selection != null) {
                String name = selection.getName();
                ob.setFileName(beanType.get(0).getBeanType(), name);
                if (!"None".equalsIgnoreCase(name))
                    filteredEditorList.add(selection);
                try {
                    IExperimentObjectManager man = ExperimentFactory.getManager(ob.getFolder(),
                            ob.getMultiScanName());
                    man.write();
                } catch (Exception e) {
                    logger.error("Cannot write: " + ob.getRunName(), e);
                }
            }
        }
    }
    return filteredEditorList;
}

From source file:com.apache.fastandroid.novel.view.readview.PageFactory.java

/**
 * ???//from www .j  a va2 s.co m
 *
 * @return
 */
private Vector<String> pageDown() {
    String strParagraph = "";
    Vector<String> lines = new Vector<>();
    int paraSpace = 0;
    mPageLineCount = mVisibleHeight / (mFontSize + mLineSpace);
    while ((lines.size() < mPageLineCount) && (curEndPos < mbBufferLen)) {
        byte[] parabuffer = readParagraphForward(curEndPos);
        curEndPos += parabuffer.length;
        try {
            strParagraph = new String(parabuffer, charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        strParagraph = strParagraph.replaceAll("\r\n", "  ").replaceAll("\n", " "); // ????

        while (strParagraph.length() > 0) {
            int paintSize = mPaint.breakText(strParagraph, true, mVisibleWidth, null);
            lines.add(strParagraph.substring(0, paintSize));
            strParagraph = strParagraph.substring(paintSize);
            if (lines.size() >= mPageLineCount) {
                break;
            }
        }
        lines.set(lines.size() - 1, lines.get(lines.size() - 1) + "@");
        if (strParagraph.length() != 0) {
            try {
                curEndPos -= (strParagraph).getBytes(charset).length;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        paraSpace += mLineSpace;
        mPageLineCount = (mVisibleHeight - paraSpace) / (mFontSize + mLineSpace);
    }
    return lines;
}

From source file:org.apache.hadoop.raid.Encoder.java

private Vector<Path> getPartialPaths(int encodingUnit, int expectedNum, FileStatus[] stats, Codec codec,
        long numStripes) throws IOException {
    Vector<Path> partialPaths = new Vector<Path>(expectedNum);
    partialPaths.setSize(expectedNum);// ww  w.j  av a2  s. c om
    for (FileStatus stat : stats) {
        int startStripeIdx;
        try {
            startStripeIdx = Integer.parseInt(stat.getPath().getName());
        } catch (NumberFormatException nfe) {
            throw new IOException("partial file " + stat.getPath() + " is not a number");
        }
        if (startStripeIdx % encodingUnit != 0) {
            throw new IOException("partial file " + stat.getPath() + " couldn't " + "match " + encodingUnit);
        }
        long numBlocks = RaidNode.numBlocks(stat);
        long expectedNumBlocks = Math.min(encodingUnit, numStripes - startStripeIdx) * codec.parityLength;
        if (numBlocks != expectedNumBlocks) {
            throw new IOException("partial file " + stat.getPath() + " has " + numBlocks
                    + " blocks, but it should be " + expectedNumBlocks);
        }
        partialPaths.set(startStripeIdx / encodingUnit, stat.getPath());
    }
    return partialPaths;
}

From source file:org.zywx.wbpalmstar.engine.universalex.EUExBase.java

/**
 * viewid//from w w w  .  j a va 2s .c  o m
 *
 * @param child
 * @param index
 * @param opid
 */
public final void addSubviewToContainer(final View child, final int index, final String opid,
        final FrameLayout.LayoutParams parms) {
    if (null == mBrwView || opid == null || index < 0 || parms == null) {
        return;
    }
    ((EBrowserActivity) mContext).runOnUiThread(new Runnable() {

        @Override
        public void run() {
            EBrowserWindow mWindow = mBrwView.getBrowserWindow();
            int count = mWindow.getChildCount();
            int l = (int) (parms.leftMargin);
            int t = (int) (parms.topMargin);
            int w = parms.width;
            int h = parms.height;
            for (int i = 0; i < count; i++) {
                View view = mWindow.getChildAt(i);
                if (view instanceof ContainerViewPager) {
                    final ContainerViewPager pager = (ContainerViewPager) view;
                    if (opid.equals(pager.getContainerVO().getId())) {
                        ContainerAdapter adapter = (ContainerAdapter) pager.getAdapter();
                        Vector<FrameLayout> views = adapter.getViewList();
                        boolean needAnim = views.size() == 0;//view
                        child.setLayoutParams(parms);
                        FrameLayout layout = new FrameLayout(mContext);
                        layout.addView(child);
                        if (views.size() <= index) {
                            for (int j = views.size(); j <= index; j++) {
                                if (j == index) {
                                    views.add(layout);
                                } else {
                                    views.add(new FrameLayout(mContext));
                                }
                            }
                        } else {
                            views.set(index, layout);
                        }
                        adapter.setViewList(views);
                        adapter.notifyDataSetChanged();
                        if (needAnim && pager.getContainerVO().getAnimTime() != 0) {
                            startAnimationDelay(pager, child);
                        }
                        return;
                    } //end equals opid
                } //end instanceof
            } //end for
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(w, h);
            lp.leftMargin = l;
            lp.topMargin = t;
            addViewToCurrentWindow(child, lp);
        }// end run 
    });// end runOnUI
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Perform a selection query that retrieves all points in the given range.
 * The range is specified in the two-dimensional array positions. 
 * @param in//from   ww  w .ja  v  a 2s.  c o  m
 * @param query_mbr
 * @return
 * @throws IOException
 */
public static Node aggregateQuery(FSDataInputStream in, Rectangle query_mbr) throws IOException {
    long treeStartPosition = in.getPos();
    Node result = new Node();
    int numOfSelectedRecords = 0;
    int resolution = in.readInt();
    short fillValue = in.readShort();
    int cardinality = in.readInt();
    final Vector<Integer> selectedNodesPos = new Vector<Integer>();
    final Vector<Integer> selectedStarts = new Vector<Integer>();
    final Vector<Integer> selectedEnds = new Vector<Integer>();
    StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution);
    // Nodes to be searched. Contains node positions in the array of nodes
    Stack<Integer> nodes_2b_searched = new Stack<Integer>();
    nodes_2b_searched.add(0); // Root node (ID=1)
    Rectangle node_mbr = new Rectangle();
    while (!nodes_2b_searched.isEmpty()) {
        int node_pos = nodes_2b_searched.pop();
        stockQuadTree.getNodeMBR(node_pos, node_mbr);
        if (query_mbr.contains(node_mbr)) {
            // Add this node to the selection list and stop this branch
            selectedNodesPos.add(node_pos);
        } else if (query_mbr.intersects(node_mbr)) {
            int first_child_id = stockQuadTree.nodesID[node_pos] * 4 + 0;
            int first_child_pos = Arrays.binarySearch(stockQuadTree.nodesID, first_child_id);
            if (first_child_pos < 0) {
                // No children. Hit a leaf node
                // Scan and add matching points only
                java.awt.Point record_coords = new Point();
                for (int record_pos = stockQuadTree.nodesStartPosition[node_pos]; record_pos < stockQuadTree.nodesEndPosition[node_pos]; record_pos++) {
                    stockQuadTree.getRecordCoords(record_pos, record_coords);
                    if (query_mbr.contains(record_coords)) {
                        // matched a record.
                        if (!selectedEnds.isEmpty() && selectedEnds.lastElement() == record_pos) {
                            // Merge with an adjacent range
                            selectedEnds.set(selectedEnds.size() - 1, record_pos + 1);
                        } else {
                            // Add a new range of unit width
                            selectedStarts.add(record_pos);
                            selectedEnds.add(record_pos + 1);
                        }
                        numOfSelectedRecords++;
                    }
                }
            } else {
                // Non-leaf node. Add all children to the list of nodes to search
                // Add in reverse order to the stack so that results come in sorted order
                nodes_2b_searched.add(first_child_pos + 3);
                nodes_2b_searched.add(first_child_pos + 2);
                nodes_2b_searched.add(first_child_pos + 1);
                nodes_2b_searched.add(first_child_pos + 0);
            }
        }
    }
    // Result 1: Accumulate all values
    // Sort disk offsets to eliminate backward seeks
    if (!selectedStarts.isEmpty()) {
        LOG.debug("Aggregate query selected " + selectedNodesPos.size() + " nodes and " + numOfSelectedRecords
                + " records");

        final IndexedSortable sortable = new IndexedSortable() {
            @Override
            public int compare(int i, int j) {
                return selectedStarts.get(i) - selectedStarts.get(j);
            }

            @Override
            public void swap(int i, int j) {
                int temp = selectedStarts.get(i);
                selectedStarts.set(i, selectedStarts.get(j));
                selectedStarts.set(j, temp);

                temp = selectedEnds.get(i);
                selectedEnds.set(i, selectedEnds.get(j));
                selectedEnds.set(j, temp);
            }
        };
        new QuickSort().sort(sortable, 0, selectedStarts.size());

        long dataStartPosition = getValuesStartOffset(cardinality);
        Point resultCoords = new Point();
        // Return all values in the selected ranges
        for (int iRange = 0; iRange < selectedStarts.size(); iRange++) {
            int treeStart = selectedStarts.get(iRange);
            int treeEnd = selectedEnds.get(iRange);
            long startPosition = dataStartPosition + selectedStarts.get(iRange) * cardinality * 2;
            in.seek(startPosition);
            for (int treePos = treeStart; treePos < treeEnd; treePos++) {
                // Retrieve the coords for the point at treePos
                stockQuadTree.getRecordCoords(treePos, resultCoords);
                // Read all entries at current position
                for (int iValue = 0; iValue < cardinality; iValue++) {
                    short value = in.readShort();
                    if (value != fillValue)
                        result.accumulate(value);
                }
            }
        }

    }

    // Result 2: Accumulate all nodes
    if (!selectedNodesPos.isEmpty()) {
        long nodesStartPosition = treeStartPosition + getNodesStartOffset(resolution, cardinality);
        // Sort node positions to eliminate backward seeks
        IndexedSortable nodeSortable = new IndexedSortable() {
            @Override
            public int compare(int i, int j) {
                return selectedNodesPos.get(i) - selectedNodesPos.get(j);
            }

            @Override
            public void swap(int i, int j) {
                int temp = selectedNodesPos.get(i);
                selectedNodesPos.set(i, selectedNodesPos.get(j));
                selectedNodesPos.set(j, temp);
            }
        };
        new QuickSort().sort(nodeSortable, 0, selectedNodesPos.size());

        Node selectedNode = new Node();
        for (int node_pos : selectedNodesPos) {
            long nodePosition = nodesStartPosition + node_pos * NodeSize;
            in.seek(nodePosition);
            selectedNode.readFields(in);
            result.accumulate(selectedNode);
        }
    }
    return result;
}

From source file:com.apache.fastandroid.novel.view.readview.PageFactory.java

/**
 * ?????//from w  w  w.ja  v a  2 s  .  co m
 *
 * @return
 */
public Vector<String> pageLast() {
    String strParagraph = "";
    Vector<String> lines = new Vector<>();
    currentPage = 0;
    while (curEndPos < mbBufferLen) {
        int paraSpace = 0;
        mPageLineCount = mVisibleHeight / (mFontSize + mLineSpace);
        curBeginPos = curEndPos;
        while ((lines.size() < mPageLineCount) && (curEndPos < mbBufferLen)) {
            byte[] parabuffer = readParagraphForward(curEndPos);
            curEndPos += parabuffer.length;
            try {
                strParagraph = new String(parabuffer, charset);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            strParagraph = strParagraph.replaceAll("\r\n", "  ");
            strParagraph = strParagraph.replaceAll("\n", " "); // ????

            while (strParagraph.length() > 0) {
                int paintSize = mPaint.breakText(strParagraph, true, mVisibleWidth, null);
                lines.add(strParagraph.substring(0, paintSize));
                strParagraph = strParagraph.substring(paintSize);
                if (lines.size() >= mPageLineCount) {
                    break;
                }
            }
            lines.set(lines.size() - 1, lines.get(lines.size() - 1) + "@");

            if (strParagraph.length() != 0) {
                try {
                    curEndPos -= (strParagraph).getBytes(charset).length;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            paraSpace += mLineSpace;
            mPageLineCount = (mVisibleHeight - paraSpace) / (mFontSize + mLineSpace);
        }
        if (curEndPos < mbBufferLen) {
            lines.clear();
        }
        currentPage++;
    }
    //SettingManager.getInstance().saveReadProgress(bookId, currentChapter, curBeginPos, curEndPos);
    return lines;
}

From source file:presentation.webgui.vitroappservlet.uploadService.UploadServlet.java

private void doFileUpload(HttpSession session, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    String fname = "";
    HashMap<String, String> myFileRequestParamsHM = new HashMap<String, String>();

    try {/* w ww . j  a v  a2 s.c om*/
        FileUploadListener listener = new FileUploadListener(request.getContentLength());
        FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);

        ServletFileUpload upload = new ServletFileUpload(factory);
        //        upload.setSizeMax(83886080); /* the unit is bytes */

        FileItem fileItem = null;
        fileItem = myrequestGetParameter(upload, request, myFileRequestParamsHM);

        String mode = myFileRequestParamsHM.get("mode");

        session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());

        boolean hasError = false;

        if (fileItem != null) {
            /**
             * (for KML only files) ( not prefabs (collada) or icons or images)
             */
            WstxInputFactory f = null;
            XMLStreamReader2 sr = null;
            SMInputCursor iroot = null;
            if (mode.equals("3dFile") || mode.equals("LinePlaceMarksFile")
                    || mode.equals("RoomCenterPointsFile")) {
                f = new WstxInputFactory();
                f.configureForConvenience();
                // Let's configure factory 'optimally'...
                f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
                f.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);

                sr = (XMLStreamReader2) f.createXMLStreamReader(fileItem.getInputStream());
                iroot = SMInputFactory.rootElementCursor(sr);
                // If we needed to store some information about preceding siblings,
                // we should enable tracking. (we need it for  mygetElementValueStaxMultiple method)
                iroot.setElementTracking(SMInputCursor.Tracking.PARENTS);

                iroot.getNext();
                if (!"kml".equals(iroot.getLocalName().toLowerCase())) {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "Root element not kml, as expected, but " + iroot.getLocalName());
                    return;
                }
            }

            fname = "";
            if (mode.equals("3dFile")) {
                if ((fileItem.getSize() / 1024) > 25096) { // with woodstox stax, file size should not be a problem. Let's put some limit however!
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "File is very large for XML handler to process!");
                    return;
                }

                fname = "";
                String[] elementsToFollow = { "document", "name" };
                Vector<String> resultValues = SMTools.mygetElementValueStax(iroot, elementsToFollow, 0);
                if (resultValues != null && !resultValues.isEmpty()) {
                    fname = resultValues.elementAt(0);
                }

                if (!fname.equals("")) {
                    // check for kml extension and Add it if necessary!!
                    int lastdot = fname.lastIndexOf('.');
                    if (lastdot != -1) {
                        if (lastdot == 0) // if it is the first char then ignore it and add an extension anyway
                        {
                            fname += ".kml";
                        } else if (lastdot < fname.length() - 1) {
                            if (!(fname.substring(lastdot + 1).toLowerCase().equals("kml"))) {
                                fname += ".kml";
                            }
                        } else if (lastdot == fname.length() - 1) {
                            fname += "kml";
                        }
                    } else {
                        fname += ".kml";
                    }

                    String realPath = this.getServletContext().getRealPath("/");
                    int lastslash = realPath.lastIndexOf(File.separator);
                    realPath = realPath.substring(0, lastslash);
                    // too slow
                    //FileWriter out = new FileWriter(realPath+File.separator+"KML"+File.separator+fname);
                    //document.sendToWriter(out);
                    // too slow
                    //StringWriter outString = new StringWriter();
                    //document.sendToWriter(outString);
                    //out.close();

                    // fast - do not process and store xml file, just store it.
                    File outFile = new File(realPath + File.separator + "Models" + File.separator + "Large"
                            + File.separator + fname);
                    outFile.createNewFile();
                    FileWriter tmpoutWriter = new FileWriter(outFile);
                    BufferedWriter buffWriter = new BufferedWriter(tmpoutWriter);
                    buffWriter.write(new String(fileItem.get()));
                    buffWriter.flush();
                    buffWriter.close();
                    tmpoutWriter.close();
                } else {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "No name tag found inside the KML file!");
                    return;
                }
            } else if (mode.equals("LinePlaceMarksFile")) {
                fname = "";
                String[] elementsToFollow = { "document", "folder", "placemark", "point", "coordinates" };
                Vector<String> resultValues = SMTools.mygetElementValueStax(iroot, elementsToFollow, 0);
                if (resultValues != null && resultValues.size() < 2) {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "File does not contain 2 placemarks!");
                    return;
                }

                for (int i = 0; (i < resultValues.size()) && (i < 2); i++) {
                    fname = fname + ":" + resultValues.elementAt(i);
                }
            } else if (mode.equals("RoomCenterPointsFile")) {
                fname = "";
                // here: process PlaceMarks for rooms (centerpoints) in the building
                String[] elementsToFollow0 = { "document", "folder", "placemark", "point", "coordinates" };
                String[] elementsToFollow1 = { "document", "folder", "placemark", "name" };
                // add elements to follow for room names and coordinates        
                Vector<String[]> elementsToFollow = new Vector<String[]>();
                elementsToFollow.add(elementsToFollow0);
                elementsToFollow.add(elementsToFollow1);
                Vector<Vector<String>> resultValues = new Vector<Vector<String>>();
                SMTools.mygetMultipleElementValuesStax(iroot, elementsToFollow, resultValues);

                Vector<String> resultValuesForCoords = resultValues.elementAt(0);
                Vector<String> resultValuesForNames = resultValues.elementAt(1);

                if (resultValuesForCoords == null || resultValuesForCoords.size() == 0
                        || resultValuesForNames == null || resultValuesForCoords.size() == 0
                        || resultValuesForCoords.size() != resultValuesForNames.size()) {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "File does not contain valid data for rooms!");
                    return;
                }

                for (int i = 0; i < resultValuesForNames.size(); i++) {
                    // since we use ;  and ':' to seperate rooms, we replace the comma's in the rooms' names.
                    if (resultValuesForNames.elementAt(i).indexOf(';') >= 0
                            || resultValuesForNames.elementAt(i).indexOf(':') >= 0) {
                        String tmp = new String(resultValuesForNames.elementAt(i));
                        tmp.replace(';', ' ');
                        tmp.replace(':', ' ');
                        resultValuesForNames.set(i, tmp);
                    }
                    fname = fname + ";" + resultValuesForNames.elementAt(i) + ":"
                            + resultValuesForCoords.elementAt(i);
                }

            } else if (mode.equals("DefaultIconfile") || mode.equals("DefaultPrefabfile")
                    || mode.equals("SpecialValueIconfile") || mode.equals("SpecialValuePrefabfile")
                    || mode.equals("NumericRangeIconfile") || mode.equals("NumericRangePrefabfile")) {
                fname = "";
                if ((fileItem.getSize() / 1024) > 10096) { // no more than 10 Mbs of size for small prefabs or icons
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError, "File is very large!");
                    return;
                }
                fname = fileItem.getName();
                if (!fname.equals("")) {
                    String realPath = this.getServletContext().getRealPath("/");
                    int lastslash = realPath.lastIndexOf(File.separator);
                    realPath = realPath.substring(0, lastslash);

                    File outFile = new File(realPath + File.separator + "Models" + File.separator + "Media"
                            + File.separator + fname);
                    outFile.createNewFile();
                    /*
                    FileWriter tmpoutWriter = new FileWriter(outFile);
                    BufferedWriter buffWriter = new BufferedWriter(tmpoutWriter);                      
                    buffWriter.write(new String(fileItem.get()));
                    buffWriter.flush();
                    buffWriter.close();
                    tmpoutWriter.close();
                    */
                    fileItem.write(outFile);
                } else {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "No valid name for uploaded file!");
                    return;
                }
            }

            fileItem.delete();
        }

        if (!hasError) {
            sendCompleteResponse(myFileRequestParamsHM, response, hasError, fname);
        } else {
            hasError = true;
            sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                    "Could not process uploaded file. Please see log for details.");
        }
    } catch (Exception e) {
        boolean hasError = true;
        sendCompleteResponse(myFileRequestParamsHM, response, hasError, "::" + fname + "::" + e.getMessage());
    }
}