Example usage for java.util ArrayList listIterator

List of usage examples for java.util ArrayList listIterator

Introduction

In this page you can find the example usage for java.util ArrayList listIterator.

Prototype

public ListIterator<E> listIterator() 

Source Link

Document

Returns a list iterator over the elements in this list (in proper sequence).

Usage

From source file:vteaexploration.plottools.panels.XYExplorationPanel.java

@Override
public int getGatedSelected(ImagePlus ip) {
    ArrayList<MicroObject> ImageGatedObjects = new ArrayList<MicroObject>();
    ArrayList<MicroObject> volumes = (ArrayList) plotvalues.get(1);
    try {/*from  w w w .  j  ava  2s .  co m*/
        ListIterator<MicroObject> itr = volumes.listIterator();
        while (itr.hasNext()) {
            MicroObject m = itr.next();
            int[] c = new int[2];
            c = m.getBoundsCenter();
            if (ip.getRoi().contains(c[0], c[1])) {
                ImageGatedObjects.add(m);
            }
        }
    } catch (NullPointerException e) {
        return 0;
    }

    Gate gate;
    ListIterator<Gate> gate_itr = gates.listIterator();
    ArrayList<MicroObject> result = new ArrayList<MicroObject>();

    while (gate_itr.hasNext()) {
        gate = gate_itr.next();
        if (gate.getSelected()) {
            Path2D path = gate.createPath2DInChartSpace();

            MicroObjectModel volume;
            double xValue = 0;
            double yValue = 0;

            ListIterator<MicroObject> it = ImageGatedObjects.listIterator();
            try {
                while (it.hasNext()) {
                    volume = it.next();
                    if (volume != null) {
                        xValue = ((Number) processPosition(currentX, (MicroObject) volume)).doubleValue();
                        yValue = ((Number) processPosition(currentY, (MicroObject) volume)).doubleValue();
                        if (path.contains(xValue, yValue)) {
                            result.add((MicroObject) volume);
                        }
                    }
                }
            } catch (NullPointerException e) {
                return 0;
            }
        }
    }
    return result.size();
}

From source file:com.hortonworks.atlas.cli.AtlasCLI.java

/**
 * //from  w ww .j av  a2s .  com
 * @param line
 */
public void loadHierarchy(CommandLine line) {

    String path = line.getOptionValue(AtlasCLIOptions.filepath);
    JsonHierarchy jsn;

    try {

        jsn = new JsonHierarchy();
        jsn.parseJSON(path);

        ArrayList<EntityModel> emList = jsn.getEmList();
        ArrayList<TupleModel> tmModel = jsn.getTmapList();

        /**
         * Create the Traits
         */

        ListIterator<TupleModel> arMdl = tmModel.listIterator();
        TupleModel tpM = null;
        String trait = null;
        String supertrait = null;
        Taxonomy tx1 = new Taxonomy();

        System.out.print("Getting new Client");
        // NewAtlasClient nac = new NewAtlasClient(this.baseurl);

        List<String> tl = null;
        try {
            tl = this.aClient.listTypes();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        while (arMdl.hasNext()) {
            try {
                tpM = arMdl.next();
                trait = tpM.getCurrnode();
                supertrait = tpM.getParentnode();

                if (!tl.contains(trait)) {
                    String traitJson = tx1.createTraitTypes(trait, supertrait);
                    System.out.println(trait + " created..");

                    this.aClient.createType(traitJson);

                } else {
                    System.out.println(trait + " exists. Skipping");
                    continue;
                }
            } catch (AtlasServiceException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        /**
         * Create Entities
         */

        ListIterator<EntityModel> lsiEM = emList.listIterator();
        EntityModel em = null;
        String type = null;
        String name = null;
        trait = null;
        Referenceable ref;
        String Id;
        Struct stc;
        AtlasEntitySearch aES;
        String type_name;
        String value;

        while (lsiEM.hasNext()) {

            em = lsiEM.next();
            name = em.getName();
            trait = em.getParent();

            aES = new AtlasEntitySearch(baseurl);
            type_name = em.getType();
            value = em.getName();

            try {
                ref = aES.getReferenceByName(type_name, value);
                if (ref != null) {
                    Id = ref.getId()._getId();
                    stc = new Struct(trait);
                    this.addTrait(Id, stc);

                    System.out.println(String.format("Trait %s update to entity %s", trait, value));
                } else {

                    System.out.println(
                            String.format("Entity %s, not found in Atlas. Trait not added", trait, value));
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:omr.sheet.LinesBuilder.java

/**
 * Staff are detected in the list of (raw) peaks, simply by looking for
 * regular series of peaks.//www  .jav a 2  s  .  c  o  m
 *
 * @param peaks the raw list of peaks found
 */
private void retrieveStaves(List<Peak> peaks) throws StepException {
    // One single iterator, since from peak area to peak area, we keep
    // moving forward in an ordered list of vertices
    ArrayList<GlyphSection> vertices = new ArrayList<GlyphSection>(lag.getVertices());
    Collections.sort(vertices, Section.idComparator);

    ListIterator<GlyphSection> vi = vertices.listIterator();

    // Maximum deviation accepted in the series of peaks in a staff
    final double maxDeviation = scale.toPixelsDouble(constants.maxInterlineDeviation);

    // Maximum difference in interval between a 6th line and the average
    // interval in the previous 5 lines
    final double maxDiff = scale.toPixelsDouble(constants.maxInterlineDiffFrac);

    // Desired length of series (TODO)
    final int interlineNb = 4;

    int firstPeak = 0;
    int lastPeak = 0;
    Population intervals = new Population();
    LineBuilder.reset();

    // Use a new staff retriever
    StaffBuilder staffBuilder = new StaffBuilder(sheet, lag, vi);

    // Browse through the peak list
    Peak prevPeak = null;

    for (ListIterator<Peak> li = peaks.listIterator(); li.hasNext();) {
        // Get peak at hand
        Peak peak = li.next();

        if (logger.isFineEnabled()) {
            logger.fine((li.nextIndex() - 1) + " " + peak);
        }

        // If very first one, we don't yet have intervals
        if (li.nextIndex() == 1) {
            prevPeak = peak;

            continue;
        }

        // Compute interval with previous peak
        double interval = computeInterval(prevPeak, peak);

        if (logger.isFineEnabled()) {
            logger.fine("interval=" + interval);
        }

        intervals.includeValue(interval);
        prevPeak = peak;

        // Check for regularity of current series
        if (intervals.getCardinality() > 1) {
            double stdDev = intervals.getStandardDeviation();

            if (logger.isFineEnabled()) {
                logger.fine("stdDev=" + (float) stdDev);
            }

            if (stdDev > maxDeviation) {
                if (logger.isFineEnabled()) {
                    logger.fine("Interval gap detected");
                }

                intervals.reset(interval);
            } else if (intervals.getCardinality() == interlineNb) {
                if (logger.isFineEnabled()) {
                    logger.fine("End of staff");
                }

                // We have a suitable series.  However, let's look for a
                // better sixth one if any on the other side of the staff
                lastPeak = li.nextIndex() - 1;
                firstPeak = lastPeak - interlineNb;

                if (li.hasNext()) {
                    Peak nextPeak = li.next();
                    interval = computeInterval(peak, nextPeak);

                    if ((Math.abs(interval - intervals.getMeanValue()) <= maxDiff) // Good candidate, compare with first one
                            && (nextPeak.getMax() > peaks.get(firstPeak).getMax())) {
                        if (logger.isFineEnabled()) {
                            logger.fine("Moving to sixth line");
                        }

                        // Fix computation of interval value
                        intervals.excludeValue(computeInterval(peaks.get(firstPeak), peaks.get(firstPeak + 1)));
                        intervals.includeValue(interval);

                        // Update indices
                        firstPeak++;
                        lastPeak++;
                    } else {
                        li.previous(); // Undo the move to the sixth peak
                    }
                }

                // We now have a set of peaks that signals a staff area
                if (logger.isFineEnabled()) {
                    logger.fine("Staff from peaks " + firstPeak + " to " + lastPeak);
                }

                staves.add(staffBuilder.buildInfo(peaks.subList(firstPeak, lastPeak + 1),
                        intervals.getMeanValue()));

                if (logger.isFineEnabled()) {
                    System.out.println();
                }

                // Move to the next peak, candidate for starting a new
                // staff
                if (li.hasNext()) {
                    intervals.reset();
                    prevPeak = li.next();

                    if (logger.isFineEnabled()) {
                        logger.fine((li.nextIndex() - 1) + " " + prevPeak);
                    }
                }
            }
        }
    }
}

From source file:vteaexploration.plottools.panels.XYChartPanel.java

private DefaultXYZDataset createXYZDataset(ArrayList alVolumes, int x, int y, int l) {
    //System.out.println("PROFILING: New dataset, for  " + alVolumes.size() + " objects.");
    DefaultXYZDataset result = new DefaultXYZDataset();
    int counter = 0;

    double[] xCorrected = new double[alVolumes.size()];
    double[] yCorrected = new double[alVolumes.size()];
    double[] lCorrected = new double[alVolumes.size()];

    ListIterator litr = alVolumes.listIterator();

    while (litr.hasNext()) {
        //            try {
        MicroObjectModel volume = (MicroObjectModel) litr.next();
        xCorrected[counter] = processPosition(x, volume).doubleValue();
        yCorrected[counter] = processPosition(y, volume).doubleValue();
        if (l > 0) {
            lCorrected[counter] = processPosition(l, volume).doubleValue();
        } else {//from  w ww. j av a2s  .c om
            lCorrected[counter] = 0;
        }

        counter++;
        //            } 
        //            catch (NullPointerException e) {
        //                System.out.println("EXCEPTION:  Error building dataset.");
        //            }
    }

    double[][] series = new double[][] { xCorrected, yCorrected, lCorrected };
    result.addSeries("first", series);

    return result;
}

From source file:com.smi.travel.monitor.MonitorAmadeus.java

@Override
void buildBookingPassenger(BookingAirline bAir) {
    String passengerTypes = new String("");
    int costRefIndex = 0;
    MAmadeus pName = amadeusMap.get("passenger name");
    ArrayList<String> lines = (ArrayList<String>) sectionData.get(pName.getSection());
    //        System.out.println("Passenger " + lines.size());
    String ticketType = getField("ticket type");
    ListIterator<String> iterator = lines.listIterator();
    String line = null;//from w  ww  . j  a  v  a 2  s  . c o  m
    BookingPassenger bp = null;
    while (iterator.hasNext()) {
        line = iterator.next();
        //            System.out.println("line-> " + line);
        String[] mline = line.split("\\r?\\n");

        String passengerName = getField("passenger name", mline[0]).trim();
        //            String passengerType = getField("passenger type", mline[0]);
        //            if (StringUtils.isEmpty(passengerType)
        //                    || !("ADT".equalsIgnoreCase(passengerType))
        //                    || !("CHD".equalsIgnoreCase(passengerType))
        //                    || !("INF".equalsIgnoreCase(passengerType))) {
        //                passengerType = "NON";
        //            }

        MAmadeus ticketNo1Ama = amadeusMap.get("ticket serial1");
        String section = ticketNo1Ama.getSection();
        String ticketLine = null;
        for (int i = 1; i < mline.length; i++) {
            if (mline[i].startsWith(section)) {
                ticketLine = mline[i];
                break;
            }
        }
        //            System.out.println("Ticket ->" + ticketLine);
        String ticketNo1 = getField("ticket serial1", ticketLine);
        String ticketNo2 = getField("ticket serial2", ticketLine);
        String ticketNo3 = getField("ticket serial3", ticketLine);

        //            System.out.println("passengerName " + passengerName);
        String[] splitName = passengerName.split("/");
        String lastName = splitName[0];
        String[] splitName2 = splitName[1].split(" ");
        // Using nameSeparatorIndex to handle case of blank space in first name.
        int nameSeparatorIndex = splitName[1].lastIndexOf(" ");
        String firstName = splitName[1].substring(0, nameSeparatorIndex);

        //            String firstName = splitName[1].substring(0, splitName[1].length() - 2);
        //            String initial = splitName[1].substring(splitName[1].length() - 2);
        String initial;
        String passengerType;
        if (!splitName2[1].contains("(")) {
            // plus 1 to exclude blankspace index.
            initial = splitName[1].substring(nameSeparatorIndex + 1);
            passengerType = "ADT";
        } else {
            int indexLess = splitName2[1].indexOf("(");
            int indexMore = splitName2[1].indexOf(")");
            initial = splitName2[1].substring(0, indexLess);
            passengerType = splitName2[1].substring(indexLess + 1, indexMore);
        }

        MAmadeus fareComAma = amadeusMap.get("fare commission");
        String fareSection = fareComAma.getSection();
        String fareLine = null;
        for (int i = 1; i < mline.length; i++) {
            if (mline[i].startsWith(fareSection)) {
                fareLine = mline[i];
                break;
            }
        }
        String fareCommission;
        if (fareLine == null) {
            fareCommission = "0";
        } else {
            fareCommission = getField("fare commission", fareLine).trim();
            fareCommission = fareCommission.replace("A", "");
        }
        String currency = getField("currency").trim();

        String ticket_fare = getTicketFare(currency);
        //            String ticket_fare = getField("ticket fare").trim();
        ticket_fare = stripNumberDecimalString(ticket_fare);
        String total_amount = getField("ticket total").trim();
        int tax = Integer.valueOf(total_amount) - Integer.valueOf(ticket_fare);
        if (tax < 0) {
            tax = tax * (-1);
        }

        //            System.out.println("lastname [" + lastName + "] ,firstname[" + firstName + "] ,initial[" + initial + "] passengerType[" + passengerType + "]");
        bp = new BookingPassenger();
        bp.setFirstName(firstName);
        bp.setLastName(lastName);
        bp.setInitialName(initial);
        bp.setPassengerType(passengerType);
        bp.setTicketType(ticketType);
        bp.setTicketnoS1(ticketNo1);//ticketNoS1);
        bp.setTicketnoS2(ticketNo2);
        bp.setTicketnoS3(ticketNo3);
        bp.setTicketFare(Integer.valueOf(ticket_fare));
        bp.setTicketTax(tax);
        bAir.getBookingPassengers().add(bp);
        bp.setBookingAirline(bAir);
        if (!passengerTypes.contains(passengerType)) {
            passengerTypes = passengerTypes + "," + passengerType;
            Integer cost;
            Integer price;
            if (isInternationalTicket(ticketType)) {
                String costS = getField("cost").trim();

                // No cost line. Set to ticket_fare.
                if ("0".equalsIgnoreCase(costS)) {
                    costS = ticket_fare;
                }
                cost = Integer.valueOf(costS);
                System.out.println("cost [" + cost + "]");
                price = cost + Integer.valueOf(fareCommission);
            } else {
                price = Integer.valueOf(ticket_fare);
                cost = (price * 95) / 100;
            }
            costRefIndex++;
            //Update cost,price,tax according to passengertype
            // Only first flight
            BookingFlight bf = (BookingFlight) bAir.getBookingFlights().iterator().next();
            //                BookingFlight bf = this.getMostEarlyFlight(bAir.getBookingPnr());
            if ("ADT".equalsIgnoreCase(passengerType)) {
                bf.setAdCost(cost);
                bf.setAdPrice(price);
                bf.setAdTax(tax);
            } else if ("CHD".equalsIgnoreCase(passengerType)) {
                bf.setChCost(cost);
                bf.setChPrice(price);
                bf.setChTax(tax);
            } else if ("INF".equalsIgnoreCase(passengerType)) {
                bf.setInCost(cost);
                bf.setInPrice(price);
                bf.setInTax(tax);
            } else {
                bf.setAdCost(cost);
                bf.setAdPrice(price);
                bf.setAdTax(tax);
            }
            //                }
        }

    }
}

From source file:vteaexploration.plottools.panels.XYExplorationPanel.java

@Override
public int getSelectedObjects() {
    Gate gate;/*from ww w . j  a  v a 2 s  . co m*/
    ListIterator<Gate> gate_itr = gates.listIterator();

    //.get
    int selected = 0;
    int gated = 0;
    int total = 0;

    ArrayList<MicroObject> result = new ArrayList<MicroObject>();

    while (gate_itr.hasNext()) {
        gate = gate_itr.next();
        if (gate.getSelected()) {
            Path2D path = gate.createPath2DInChartSpace();

            ArrayList<MicroObject> volumes = (ArrayList) this.plotvalues.get(1);
            MicroObjectModel volume;

            double xValue = 0;
            double yValue = 0;

            ListIterator<MicroObject> it = volumes.listIterator();
            try {
                while (it.hasNext()) {
                    volume = it.next();
                    if (volume != null) {
                        xValue = ((Number) processPosition(currentX, (MicroObject) volume)).doubleValue();
                        yValue = ((Number) processPosition(currentY, (MicroObject) volume)).doubleValue();
                        if (path.contains(xValue, yValue)) {
                            result.add((MicroObject) volume);
                        }
                    }
                }
            } catch (NullPointerException e) {
                return 0;
            }
        }
    }

    //System.out.println("RESULT: total gates " + gates.size() + ": " + this.getTitle() + ", Gated: " + selected + ", Total: " + total + ", for: " + 100 * (new Double(selected).doubleValue() / (new Double(total)).doubleValue()) + "%");
    return result.size();
}

From source file:org.hfoss.posit.android.web.Communicator.java

public boolean sendFind(Find find, String action) {
    boolean success = false;
    String url;/*from   www  .j a v a2 s .  c  o m*/
    HashMap<String, String> sendMap = find.getContentMapGuid();
    // Log.i(TAG, "sendFind map = " + sendMap.toString());
    cleanupOnSend(sendMap);
    sendMap.put("imei", imei);
    String guid = sendMap.get(PositDbHelper.FINDS_GUID);
    long id = find.getId();
    // Create the url

    if (action.equals("create")) {
        url = server + "/api/createFind?authKey=" + authKey;
    } else {
        url = server + "/api/updateFind?authKey=" + authKey;
    }
    if (Utils.debug) {
        Log.i(TAG, "SendFind=" + sendMap.toString());
    }

    // Send the find
    try {
        responseString = doHTTPPost(url, sendMap);
    } catch (Exception e) {
        Log.i(TAG, e.getMessage());
        Utils.showToast(mContext, e.getMessage());
        return false;
    }
    if (Utils.debug)
        Log.i(TAG, "sendFind.ResponseString: " + responseString);

    // If the update failed return false
    if (responseString.indexOf("True") == -1) {
        Log.i(TAG, "sendFind result doesn't contain 'True'");
        return false;
    } else {
        PositDbHelper dbh = new PositDbHelper(mContext);
        success = dbh.markFindSynced(id);
        if (Utils.debug)
            Log.i(TAG, "sendfind synced " + id + " " + success);
    }

    if (success) {
        // Otherwise send the Find's images

        //long id = Long.parseLong(sendMap.get(PositDbHelper.FINDS_ID));
        PositDbHelper dbh = new PositDbHelper(mContext);
        ArrayList<ContentValues> photosList = dbh.getImagesListSinceUpdate(id, projectId);

        Log.i(TAG, "sendFind, photosList=" + photosList.toString());

        Iterator<ContentValues> it = photosList.listIterator();
        while (it.hasNext()) {
            ContentValues imageData = it.next();
            Uri uri = Uri.parse(imageData.getAsString(PositDbHelper.PHOTOS_IMAGE_URI));
            String base64Data = convertUriToBase64(uri);
            uri = Uri.parse(imageData.getAsString(PositDbHelper.PHOTOS_THUMBNAIL_URI));
            String base64Thumbnail = convertUriToBase64(uri);
            sendMap = new HashMap<String, String>();
            sendMap.put(COLUMN_IMEI, Utils.getIMEI(mContext));
            sendMap.put(PositDbHelper.FINDS_GUID, guid);

            sendMap.put(PositDbHelper.PHOTOS_IDENTIFIER,
                    imageData.getAsString(PositDbHelper.PHOTOS_IDENTIFIER));
            sendMap.put(PositDbHelper.FINDS_PROJECT_ID, imageData.getAsString(PositDbHelper.FINDS_PROJECT_ID));
            sendMap.put(PositDbHelper.FINDS_TIME, imageData.getAsString(PositDbHelper.FINDS_TIME));
            sendMap.put(PositDbHelper.PHOTOS_MIME_TYPE, imageData.getAsString(PositDbHelper.PHOTOS_MIME_TYPE));

            sendMap.put("mime_type", "image/jpeg");

            sendMap.put(PositDbHelper.PHOTOS_DATA_FULL, base64Data);
            sendMap.put(PositDbHelper.PHOTOS_DATA_THUMBNAIL, base64Thumbnail);
            sendMedia(sendMap);
        }
    }
    // Update the Synced attribute.
    return success;
}

From source file:vteaexploration.plottools.panels.XYExplorationPanel.java

public void makeOverlayImage(ArrayList gates, int x, int y, int xAxis, int yAxis) {
    //convert gate to chart x,y path

    Gate gate;/*from   ww w .j  ava 2  s .c  o m*/
    ListIterator<Gate> gate_itr = gates.listIterator();

    //.get

    int total = 0;
    int gated = 0;
    int selected = 0;
    int gatedSelected = 0;

    int gatecount = gates.size();

    while (gate_itr.hasNext()) {
        gate = gate_itr.next();
        if (gate.getSelected()) {
            Path2D path = gate.createPath2DInChartSpace();

            ArrayList<MicroObject> result = new ArrayList<MicroObject>();

            ArrayList<MicroObject> volumes = (ArrayList) this.plotvalues.get(1);
            MicroObjectModel volume;

            double xValue = 0;
            double yValue = 0;

            ListIterator<MicroObject> it = volumes.listIterator();
            try {
                while (it.hasNext()) {
                    volume = it.next();
                    if (volume != null) {
                        xValue = ((Number) processPosition(xAxis, (MicroObject) volume)).doubleValue();
                        yValue = ((Number) processPosition(yAxis, (MicroObject) volume)).doubleValue();
                        if (path.contains(xValue, yValue)) {
                            result.add((MicroObject) volume);
                        }
                    }
                }
            } catch (NullPointerException e) {
            }
            ;

            Overlay overlay = new Overlay();

            int count = 0;
            BufferedImage placeholder = new BufferedImage(impoverlay.getWidth(), impoverlay.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);

            ImageStack gateOverlay = new ImageStack(impoverlay.getWidth(), impoverlay.getHeight());

            selected = getSelectedObjects();

            total = volumes.size();

            gated = getGatedObjects(impoverlay);

            gatedSelected = getGatedSelected(impoverlay);

            for (int i = 0; i <= impoverlay.getNSlices(); i++) {
                BufferedImage selections = new BufferedImage(impoverlay.getWidth(), impoverlay.getHeight(),
                        BufferedImage.TYPE_INT_ARGB);

                Graphics2D g2 = selections.createGraphics();

                ImageRoi ir = new ImageRoi(0, 0, placeholder);
                ListIterator<MicroObject> vitr = result.listIterator();

                while (vitr.hasNext()) {
                    try {
                        MicroObject vol = (MicroObject) vitr.next();

                        int[] x_pixels = vol.getXPixelsInRegion(i);
                        int[] y_pixels = vol.getYPixelsInRegion(i);

                        for (int c = 0; c < x_pixels.length; c++) {

                            g2.setColor(gate.getColor());
                            g2.drawRect(x_pixels[c], y_pixels[c], 1, 1);
                        }
                        ir = new ImageRoi(0, 0, selections);
                        count++;

                    } catch (NullPointerException e) {
                    }
                }

                ir.setPosition(i);
                ir.setOpacity(0.4);
                overlay.add(ir);

                gateOverlay.addSlice(ir.getProcessor());

                java.awt.Font f = new Font("Arial", Font.BOLD, 12);
                BigDecimal percentage = new BigDecimal(selected);
                BigDecimal totalBD = new BigDecimal(total);
                percentage = percentage.divide(totalBD, 4, BigDecimal.ROUND_UP);

                BigDecimal percentageGated = new BigDecimal(gated);
                BigDecimal totalGatedBD = new BigDecimal(total);
                percentageGated = percentageGated.divide(totalGatedBD, 4, BigDecimal.ROUND_UP);

                BigDecimal percentageGatedSelected = new BigDecimal(gatedSelected);
                BigDecimal totalGatedSelectedBD = new BigDecimal(total);
                percentageGatedSelected = percentageGatedSelected.divide(totalGatedSelectedBD, 4,
                        BigDecimal.ROUND_UP);

                // System.out.println("PROFILING: gate fraction: " + percentage.toString());
                if (impoverlay.getWidth() > 256) {

                    TextRoi textTotal = new TextRoi(5, 10,
                            selected + "/" + total + " gated (" + 100 * percentage.doubleValue() + "%)");

                    if (gated > 0) {
                        textTotal = new TextRoi(5, 10, selected + "/" + total + " total ("
                                + 100 * percentage.doubleValue() + "%)" + "; " + gated + "/" + total + " roi ("
                                + 100 * percentageGated.doubleValue() + "%)" + "; " + gatedSelected + "/"
                                + total + " overlap (" + 100 * percentageGatedSelected.doubleValue() + "%)", f);
                    }
                    //TextRoi textImageGated = new TextRoi(5, 18, selected + "/" + total + " gated objects (" + 100 * percentage.doubleValue() + "%)", f);
                    textTotal.setPosition(i);
                    //textImageGated.setPosition(i);
                    overlay.add(textTotal);
                } else {
                    f = new Font("Arial", Font.PLAIN, 10);
                    TextRoi line1 = new TextRoi(5, 5,
                            selected + "/" + total + " gated" + "(" + 100 * percentage.doubleValue() + "%)", f);
                    overlay.add(line1);
                    if (gated > 0) {
                        f = new Font("Arial", Font.PLAIN, 10);
                        TextRoi line2 = new TextRoi(5, 18,
                                gated + "/" + total + " roi (" + 100 * percentageGated.doubleValue() + "%)", f);
                        overlay.add(line2);
                        TextRoi line3 = new TextRoi(5, 31, gatedSelected + "/" + total + " overlap ("
                                + 100 * percentageGatedSelected.doubleValue() + "%)", f);
                        overlay.add(line3);
                    }
                    line1.setPosition(i);

                }
            }
            impoverlay.setOverlay(overlay);

            //ImagePlus gateMaskImage = new ImagePlus("gates", gateOverlay);

            //gateMaskImage.show();

            gate.setGateOverlayStack(gateOverlay);

        }

        impoverlay.draw();
        impoverlay.setTitle(this.getTitle());

        if (impoverlay.getDisplayMode() != IJ.COMPOSITE) {
            impoverlay.setDisplayMode(IJ.COMPOSITE);
        }

        if (impoverlay.getSlice() == 1) {
            impoverlay.setZ(Math.round(impoverlay.getNSlices() / 2));
        } else {
            impoverlay.setSlice(impoverlay.getSlice());
        }
        impoverlay.show();
    }
}

From source file:edu.unc.lib.dl.util.ContainerContentsHelper.java

/**
 * @param oldXML//  www  . j  a va  2  s  .  c o m
 * @param container
 * @param children
 * @return
 */
public static Document addChildContentListInCustomOrder(Document oldXML, PID container, List<PID> children,
        Collection<PID> reorderedPids) {
    log.debug("HERE incoming children:");
    for (int i = 0; i < children.size(); i++) {
        log.debug(i + " => " + children.get(i));
    }

    // first build a list of existing pid order in the container
    Element parentDiv = oldXML.getRootElement().getChild("div", JDOMNamespaceUtil.METS_NS);
    List<Element> childDivs = parentDiv.getChildren();
    int maxExistingOrder = 5;
    if (childDivs.size() > 0) {
        maxExistingOrder = Integer.parseInt(childDivs.get(childDivs.size() - 1).getAttributeValue("ORDER"));
    }
    ArrayList<PID> order = new ArrayList<PID>(maxExistingOrder);
    try {
        for (Element child : childDivs) {
            int ord = Integer.parseInt(child.getAttributeValue("ORDER"));
            PID pid = new PID(child.getAttributeValue("ID"));
            if (ord >= order.size()) {
                while (ord > order.size()) { // insert nulls
                    order.add(null);
                }
                order.add(pid);
            } else {
                order.add(ord, pid);
            }
        }
    } catch (NullPointerException e) {
        throw new IllegalRepositoryStateException("Invalid container contents XML (MD_CONTENTS) on: ", e);
    }

    log.debug("HERE order before merge:");
    for (int i = 0; i < order.size(); i++) {
        log.debug(i + " => " + order.get(i));
    }

    PID[] originalOrder = order.toArray(new PID[0]);

    // clear out the current children
    parentDiv.removeContent();

    int maxIncomingOrder = 0;
    if (children.size() > 0) {
        maxIncomingOrder = children.size() - 1;
    }
    int capacityEstimate = Math.max(maxIncomingOrder, maxExistingOrder) + 10;
    order.ensureCapacity(capacityEstimate);

    for (ListIterator<PID> foo = children.listIterator(); foo.hasNext();) {
        int ord = foo.nextIndex();
        PID child = foo.next();
        if (ord >= order.size()) {
            while (ord > order.size()) { // insert nulls
                order.add(null);
            }
            order.add(child);
        } else {
            order.add(ord, child);
        }
    }

    log.debug("HERE order after merge:");
    for (int i = 0; i < order.size(); i++) {
        log.debug(i + " => " + order.get(i));
    }

    for (int i = 0; i < originalOrder.length; i++) {
        PID orig = originalOrder[i];
        if (orig != null) {
            if (!orig.equals(order.get(i))) {
                reorderedPids.add(orig);
            }
        }
    }

    for (ListIterator<PID> li = order.listIterator(); li.hasNext();) {
        int ord = li.nextIndex();
        PID pid = li.next();
        if (pid != null) {
            Element el = new Element("div", parentDiv.getNamespace()).setAttribute("ID", pid.getPid())
                    .setAttribute("ORDER", String.valueOf(ord));
            parentDiv.addContent(el);
        }
    }

    return oldXML;
}

From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8DictionaryTable.java

public MSSBamDictionaryBuff[] readDerivedByTenantIdx(MSSBamAuthorization Authorization, long TenantId) {
    final String S_ProcName = "readDerivedByTenantIdx";
    if (!schema.isTransactionOpen()) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Transaction not open");
    }//w  w w .  j  a  v a  2  s.  co m
    ArrayList<String> classCodeList = new ArrayList<String>();
    String classCode;
    try {
        Connection cnx = schema.getCnx();
        String sql = S_sqlSelectDictionaryDistinctClassCode + "WHERE " + "anyo.TenantId = "
                + Long.toString(TenantId) + " ";
        Statement stmt = cnx.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = stmt.executeQuery(sql);
        while (resultSet.next()) {
            classCode = resultSet.getString(1);
            classCodeList.add(classCode);
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    }
    ArrayList<MSSBamDictionaryBuff> resultList = new ArrayList<MSSBamDictionaryBuff>();
    ListIterator<String> classCodeIter = classCodeList.listIterator();
    while (classCodeIter.hasNext()) {
        classCode = classCodeIter.next();
        if (classCode.equals("DICT")) {
            MSSBamDictionaryBuff[] subList = readBuffByTenantIdx(Authorization, TenantId);
            for (int subListIdx = 0; subListIdx < subList.length; subListIdx++) {
                resultList.add(subList[subListIdx]);
            }
        } else if (classCode.equals("RMD")) {
            MSSBamMSSBamBuff[] subList = schema.getTableMSSBam().readBuffByTenantIdx(Authorization, TenantId);
            for (int subListIdx = 0; subListIdx < subList.length; subListIdx++) {
                resultList.add(subList[subListIdx]);
            }
        } else {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Did not expect ClassCode \"" + classCode + "\"");
        }
    }
    return (resultList.toArray(new MSSBamDictionaryBuff[0]));

}