Example usage for java.util ArrayList remove

List of usage examples for java.util ArrayList remove

Introduction

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

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes the first occurrence of the specified element from this list, if it is present.

Usage

From source file:org.bedework.timezones.server.MethodBase.java

/** Return a path, beginning with a "/", after "." and ".." are removed.
 * If the parameter path attempts to go above the root we return null.
 *
 * Other than the backslash thing why not use URI?
 *
 * @param path      String path to be fixed
 * @return String   fixed path//from   w  w w . ja v a2  s  . c o m
 * @throws ServletException
 */
public static ResourceUri fixPath(final String path) throws ServletException {
    if (path == null) {
        return new ResourceUri();
    }

    String decoded;
    try {
        decoded = URLDecoder.decode(path, "UTF8");
    } catch (final Throwable t) {
        throw new ServletException("bad path: " + path);
    }

    if (decoded == null) {
        return new ResourceUri();
    }

    /** Make any backslashes into forward slashes.
     */
    if (decoded.indexOf('\\') >= 0) {
        decoded = decoded.replace('\\', '/');
    }

    /** Ensure a leading '/'
     */
    if (!decoded.startsWith("/")) {
        decoded = "/" + decoded;
    }

    /** Remove all instances of '//'.
     */
    while (decoded.contains("//")) {
        decoded = decoded.replaceAll("//", "/");
    }
    /** Somewhere we may have /./ or /../
     */

    final StringTokenizer st = new StringTokenizer(decoded, "/");

    final ArrayList<String> al = new ArrayList<>();
    while (st.hasMoreTokens()) {
        final String s = st.nextToken();

        if (s.equals(".")) {
            // ignore
            continue;
        }

        if (s.equals("..")) {
            // Back up 1
            if (al.size() == 0) {
                // back too far
                return new ResourceUri();
            }

            al.remove(al.size() - 1);
            continue;
        }

        al.add(s);
    }

    final ResourceUri ruri = new ResourceUri();

    /** Reconstruct */
    for (final String s : al) {
        ruri.addPathElement(s);
    }

    return ruri;
}

From source file:levelBuilder.DialogMaker.java

/**
 * Displays properties of the currently selected node.
 * Also allows changing of most node properties. 
 *//*w  ww . j  a  va  2  s.co m*/
private static void nodePropertiesWindow() {
    //Performs actions based on button pushes.
    class ActionHandler implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            switch (e.getActionCommand()) {
            case "probSet":
                //parsing new probSet string to double[]
                ArrayList<double[]> probSets = selectedNode.getProbSets();
                if (probSetField.getText().equals(""))
                    probSets.remove(strategy);
                else {
                    String[] probSetInput = probSetField.getText().split(",");
                    int numChildren = probSetInput.length;
                    double[] newProbSet = new double[numChildren];
                    for (int c = 0; c < numChildren; c++)
                        newProbSet[c] = Double.parseDouble(probSetInput[c]);
                    if (probSets.size() > strategy)//TODO is this right?
                        probSets.add(strategy, newProbSet);
                    else
                        probSets.set(strategy, newProbSet);
                }
                selectedNode.setProbSets(probSets);
            case "npc":
                if (isNPCBoxChecked)
                    selectedNode.setNPC();
                else
                    selectedNode.setPC();
            case "text":
                dg.changeNodeText(selectedNode, textField.getText());
            case "strategy":
                strategy = Integer.parseInt(strategyField.getText());
            }
        }
    }

    JPanel fieldPanel = new JPanel(new GridLayout(0, 1, 0, 0));
    JPanel labelPanel = new JPanel(new GridLayout(0, 1, 0, 0));
    JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 0, 0));
    JPanel masterPanel = new JPanel(new GridLayout(0, 3, 0, 0));

    //Buttons, ckeckboxes, textboxes, and labels
    textField = new JTextField("May I buy your wand?", 10);
    fieldPanel.add(textField);
    labelPanel.add(new JLabel("Node Text"));
    JButton button1 = new JButton("Change");
    button1.setActionCommand("text");
    button1.addActionListener(new ActionHandler());
    buttonPanel.add(button1);

    npcBox = new JCheckBox();
    npcBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.DESELECTED)
                isNPCBoxChecked = false;
            else
                isNPCBoxChecked = true;
        }
    });
    fieldPanel.add(npcBox);
    labelPanel.add(new JLabel("NPC"));
    JButton button2 = new JButton("Change");
    button2.setActionCommand("npc");
    button2.addActionListener(new ActionHandler());
    buttonPanel.add(button2);

    childrenField = new JTextField("child1,child2", 10);
    fieldPanel.add(childrenField);
    labelPanel.add(new JLabel("Children"));
    JButton button3 = new JButton("");
    buttonPanel.add(button3);

    probSetField = new JTextField("0.1,0.9", 10);
    fieldPanel.add(probSetField);
    labelPanel.add(new JLabel("Probability set"));
    JButton button4 = new JButton("Change");
    button4.setActionCommand("probSet");
    button4.addActionListener(new ActionHandler());
    buttonPanel.add(button4);

    strategyField = new JTextField("0", 10);
    fieldPanel.add(strategyField);
    labelPanel.add(new JLabel("Strategy"));
    JButton button5 = new JButton("Change");
    button5.setActionCommand("strategy");
    button5.addActionListener(new ActionHandler());
    buttonPanel.add(button5);

    masterPanel.add(buttonPanel);
    masterPanel.add(fieldPanel);
    masterPanel.add(labelPanel);

    JFrame frame = new JFrame("Node Properties");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    fieldPanel.setOpaque(true);
    frame.setContentPane(masterPanel);
    frame.pack();
    frame.setLocation(windowWidth, verticalWindowPlacement);
    frame.setVisible(true);

    verticalWindowPlacement += frame.getBounds().height;
}

From source file:edu.gsgp.utils.Utils.java

/**
 * Generates an array with a number of folds defined by the user. Each fold
 * contains dataset.size() / numFolds instances.
 * @param numFolds Number of folds/* w  w  w.  j  a  v  a 2s.  com*/
 * @param dataset Input datase
 * @param rnd Random number generator
 * @return An array of folds
 */
public static Dataset[] getFoldSampling(int numFolds, Dataset dataset, MersenneTwister rnd) {
    Dataset[] folds = new Dataset[numFolds];
    ArrayList<Instance> dataCopy = dataset.softClone();
    int foldIndex = 0;
    if (rnd == null) {
        Iterator<Instance> it = dataCopy.iterator();
        while (it.hasNext()) {
            if (folds[foldIndex] == null)
                folds[foldIndex] = new Dataset();
            folds[foldIndex].add(it.next());
            it.remove();
            if (foldIndex < numFolds - 1)
                foldIndex++;
            else
                foldIndex = 0;
        }
    } else {
        while (!dataCopy.isEmpty()) {
            if (folds[foldIndex] == null)
                folds[foldIndex] = new Dataset();
            folds[foldIndex].add(dataCopy.remove(rnd.nextInt(dataCopy.size())));
            if (foldIndex < numFolds - 1)
                foldIndex++;
            else
                foldIndex = 0;
        }
    }
    return folds;
}

From source file:AntColonyPDP.Environment.java

private static void registerCentralizedSimulator(final long endTime, final Simulator simulator,
        final RandomGenerator rng, final RoadModel roadModel) {

    //Adding and register the colonies in the environment
    for (int i = 0; i < NUM_COLONIES; i++) {
        Colony colony = new Colony(roadModel.getRandomPosition(rng), 0);
        simulator.register(colony);/*from  www  . ja va2  s  . com*/
        register(colony);
    }

    //Adding and register the ants in the environment
    for (int i = 0; i < NUM_ANTS; i++) {
        CentralizedAnt nca = new CentralizedAnt(roadModel.getRandomPosition(rng), ANT_CAPACITY);
        simulator.register(nca);
        register(nca);
    }

    //Adding and register the food sources in the environment
    for (int i = 0; i < NUM_FOOD_SOURCE; i++) {
        generateFoodSource(simulator, rng, roadModel);
    }

    simulator.addTickListener(new TickListener() {
        @Override
        public void tick(TimeLapse time) {

            if (time.getStartTime() > endTime) {
                simulator.stop();
            } else {

                // 1: Generate new food sources
                if (rng.nextDouble() < NEW_FOOD_SOURCE_PROB * (MAX_SOURCES - SOURCES.size()) / MAX_SOURCES) { //&& SOURCES.size() < MAX_SOURCES) {
                    generateFoodSource(simulator, rng, roadModel);
                }

                // 2: check expiration and empty food sources
                for (FoodSource source : new ArrayList<FoodSource>(SOURCES)) {
                    if (source.isExpired()) {
                        SOURCES.remove(source);
                    }
                }

                assignments = new HashMap<CentralizedAnt, FoodSource>();

                // 3: get the positions
                HashMap<FoodSource, Point> fsPositions = new HashMap<FoodSource, Point>();
                for (FoodSource fs : SOURCES)
                    fsPositions.put(fs, fs.getPickupLocation());
                HashMap<CentralizedAnt, Point> caPositions = new HashMap<CentralizedAnt, Point>();
                for (CentralizedAnt ca : CENTRALIZED_ANTS)
                    caPositions.put(ca, ca.getPosition().get());

                // 4: extract closest pair and find next
                ArrayList<CentralizedAnt> remainingAnts = new ArrayList<CentralizedAnt>(CENTRALIZED_ANTS);
                for (CentralizedAnt ant : CENTRALIZED_ANTS) {
                    if (ant.isTaken())
                        remainingAnts.remove(ant);
                }

                // 5: Assign food elements with ants when it is possible
                ArrayList<FoodSource> remainingSources = new ArrayList<FoodSource>(SOURCES);
                Map<Pair, Double> shortestFound = new HashMap<Pair, Double>();

                while (!remainingSources.isEmpty() && !remainingAnts.isEmpty()) {
                    for (FoodSource fs : remainingSources) {
                        Point pos = fsPositions.get(fs);
                        Map<Pair, Double> distances = new HashMap<Pair, Double>();
                        for (CentralizedAnt ca : remainingAnts) {
                            Point antPos = caPositions.get(ca);
                            distances.put(new Pair(ca, fs), Point.distance(antPos, pos));
                        }
                        distances = MapUtil.sortByValue(distances);
                        Pair first = null;
                        double firstDist = 10;
                        for (Map.Entry<Pair, Double> entry : distances.entrySet()) {
                            //this for loop is just a complicated way to extract the first element
                            if (first == null) {
                                first = entry.getKey();
                                firstDist = entry.getValue();
                            }
                        }
                        //found the shortest for current ant
                        shortestFound.put(first, firstDist);
                    }
                    // found the shortest for each customer
                    //now sort again
                    shortestFound = MapUtil.sortByValue(shortestFound);
                    Pair absoluteShortest = null;
                    for (Map.Entry<Pair, Double> entry : shortestFound.entrySet()) {
                        if (absoluteShortest == null) {
                            absoluteShortest = entry.getKey();
                        }
                    }

                    //we found and now use the absolute minimal distance pair found
                    //if the ant can reach it
                    if (canDeliver(absoluteShortest.v, absoluteShortest.c)) {
                        assignments.put(absoluteShortest.v, absoluteShortest.c);
                        remainingSources.remove(absoluteShortest.c);
                    } else
                        absoluteShortest.v.groundAnt();
                    remainingAnts.remove(absoluteShortest.v);
                    shortestFound = new HashMap<Pair, Double>();
                }
                //printAssignments(assignments);   // debug method
            }
        }

        @Override
        public void afterTick(TimeLapse timeLapse) {
            performanceAssessment(simulator, roadModel);
        }
    });
}

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TabularReport generateTabularReportGroupByDate(Properties ctx, String title, String subtitle,
        int account_id, Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    boolean isTaxDue = (account_id == Constants.TAX_DUE.intValue());
    boolean isTaxCredit = (account_id == Constants.TAX_CREDIT.intValue());

    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    String sql = SalesAnalysisReportManager.getTabularDataSetSQL(ctx, account_id, fromDate, toDate, salesGroup);
    ArrayList<Object[]> tmpData = ReportManager.getReportData(ctx, sql, true);
    String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();

    ArrayList<Object[]> reportData = new ArrayList<Object[]>();
    Object[] data = null;//www  .j  av a 2 s  .co  m
    BigDecimal b = null;

    if (isTaxCredit || isTaxDue) {
        reportData.add(tmpData.remove(0));
        Iterator<Object[]> iter = tmpData.iterator();

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length == 1) {
                b = (BigDecimal) data[0];
                data[0] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }
    } else {
        //----------------------------------------------------------------------------------------------------------------------------------------------------------
        TreeMap<String, TabularReportRecordBean> map = new TreeMap<String, TabularReportRecordBean>();

        String productName = null;
        BigDecimal price = null;
        BigDecimal qty = null;

        TabularReportRecordBean bean = null;

        ArrayList<Object[]> reportData2 = new ArrayList<Object[]>();
        Object[] headers = tmpData.remove(0);

        //adding headers
        reportData2.add(new Object[] { headers[0],
                //headers[1],
                headers[2] + "(" + currency + ")", headers[3] });

        double totalAmt = 0.0d;
        int totalQty = 0;

        for (Object[] record : tmpData) {
            productName = (String) record[0];
            price = (BigDecimal) record[2];
            qty = (BigDecimal) record[3];

            totalAmt += price.doubleValue();
            totalQty += qty.intValue();

            bean = map.get(productName);

            if (bean == null) {
                bean = new TabularReportRecordBean();

                bean.setProductName(productName);
                bean.setDate("");
                bean.setPrice(price);
                bean.setQty(qty);
            } else {
                bean.setPrice(bean.getPrice().add(price));
                bean.setQty(bean.getQty().add(qty));
            }

            map.put(productName, bean);

        } //for 

        Collection<TabularReportRecordBean> c = map.values();

        for (TabularReportRecordBean tbean : c) {
            Object[] obj = new Object[] { tbean.getProductName(), tbean.getPrice(), tbean.getQty() };

            reportData2.add(obj);
        }

        reportData.add(reportData2.remove(0));

        Iterator<Object[]> iter = reportData2.iterator();

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length > 2) {
                b = (BigDecimal) data[1];
                data[1] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }

        reportData.add(new Object[] { "Total", "" + formatter.format(totalAmt), totalQty + "" });

    }

    //style for table
    String tableStyle = "display";
    //style for columns        
    String[] styles = new String[] { "string", "currency", "numeric" };

    if (isTaxCredit || isTaxDue) {
        styles = new String[] { "numeric" };
    }

    //constructing the table
    TabularReport tReport = new TabularReport(reportData);
    //tReport.setSortable(true);
    tReport.setHeaderStyle(styles);
    tReport.setStyle(tableStyle);
    tReport.setTitle(title);
    tReport.setSubtitle(subtitle);
    tReport.createReport();

    return tReport;
}

From source file:fr.fg.server.core.TerritoryManager.java

private static BufferedImage createTerritoryMap(int idSector) {
    List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector));

    float[][] points = new float[areas.size()][2];
    int[] dominatingAllies = new int[areas.size()];
    int i = 0;//www . j a  v a2 s. c  o m
    for (Area area : areas) {
        points[i][0] = area.getX() * MAP_SCALE;
        points[i][1] = area.getY() * MAP_SCALE;
        dominatingAllies[i] = area.getIdDominatingAlly();
        i++;
    }

    Hull hull = new Hull(points);
    MPolygon hullPolygon = hull.getRegion();
    float[][] newPoints = new float[points.length + hullPolygon.count()][2];
    System.arraycopy(points, 0, newPoints, 0, points.length);

    float[][] hullCoords = hullPolygon.getCoords();

    for (i = 0; i < hullPolygon.count(); i++) {
        double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]);
        double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]);

        newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE));
        newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE));
    }

    points = newPoints;

    Voronoi voronoi = new Voronoi(points);
    Delaunay delaunay = new Delaunay(points);

    // Dcoupage en rgions
    MPolygon[] regions = voronoi.getRegions();

    // Calcule le rayon de la galaxie
    int radius = 0;

    for (Area area : areas) {
        radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY());
    }

    radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE;
    int diameter = 2 * radius + 1;

    // Construit l'image avec les quadrants
    BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = (Graphics2D) territoriesImage.getGraphics();

    // Affecte une couleur  chaque alliance
    HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>();

    for (Area area : areas) {
        int idDominatingAlly = area.getIdDominatingAlly();
        if (idDominatingAlly != 0)
            alliesColors.put(idDominatingAlly,
                    Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]);
    }

    Polygon[] polygons = new Polygon[regions.length];
    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] != 0) {
            polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3);
        }
    }

    // Dessine tous les secteurs
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        Polygon p = polygons[i];

        // Dessine le polygone
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.fill(p);

        // Rempli les espaces entre les polygones adjacents qui
        // correspondent au territoire d'une mme alliance
        int[] linkedRegions = delaunay.getLinked(i);
        for (int j = 0; j < linkedRegions.length; j++) {
            int linkedRegion = linkedRegions[j];

            if (linkedRegion >= areas.size())
                continue;

            if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                if (linkedRegion <= i)
                    continue;

                float[][] coords1 = regions[i].getCoords();
                float[][] coords2 = regions[linkedRegion].getCoords();

                int junctionIndex = 0;
                int[][] junctions = new int[2][2];

                search: for (int k = 0; k < coords1.length; k++) {
                    for (int l = 0; l < coords2.length; l++) {
                        if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) {
                            junctions[junctionIndex][0] = k;
                            junctions[junctionIndex][1] = l;

                            junctionIndex++;

                            if (junctionIndex == 2) {
                                int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]],
                                        polygons[linkedRegion].xpoints[junctions[0][1]],
                                        polygons[linkedRegion].xpoints[junctions[1][1]],
                                        polygons[i].xpoints[junctions[1][0]], };
                                int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]],
                                        polygons[linkedRegion].ypoints[junctions[0][1]],
                                        polygons[linkedRegion].ypoints[junctions[1][1]],
                                        polygons[i].ypoints[junctions[1][0]], };

                                Polygon border = new Polygon(xpts, ypts, 4);
                                g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
                                g.fill(border);
                                g.draw(border);
                                break search;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    // Dessine des lignes de contours des territoires
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        g.setStroke(new BasicStroke(1.5f));
        g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter());

        float[][] coords1 = regions[i].getCoords();

        lines: for (int j = 0; j < coords1.length; j++) {
            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]
                                && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1)
                                        % coords2.length][0]
                                        && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1)
                                                % coords2.length][1])
                                        || (coords1[(j + 1)
                                                % coords1.length][0] == coords2[(m - 1 + coords2.length)
                                                        % coords2.length][0]
                                                && coords1[(j + 1)
                                                        % coords1.length][1] == coords2[(m - 1 + coords2.length)
                                                                % coords2.length][1]))) {
                            continue lines;
                        }
                    }
                }
            }

            g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                    Math.round(polygons[i].xpoints[(j + 1) % coords1.length]),
                    Math.round(polygons[i].ypoints[(j + 1) % coords1.length]));
        }

        for (int j = 0; j < coords1.length; j++) {
            int neighbours = 0;
            int lastNeighbourRegion = -1;
            int neighbourCoordsIndex = -1;

            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) {
                            neighbours++;
                            lastNeighbourRegion = linkedRegion;
                            neighbourCoordsIndex = m;
                            break;
                        }
                    }
                }
            }

            if (neighbours == 1) {
                g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                        Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]),
                        Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex]));
            }
        }
    }

    BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    g = (Graphics2D) finalImage.getGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f));
    g.drawImage(territoriesImage, 0, 0, null);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f));

    // Charge la police pour afficher le nom des alliances
    try {
        Font textFont = Font.createFont(Font.TRUETYPE_FONT,
                Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf"));
        textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD);
        g.setFont(textFont);
    } catch (Exception e) {
        LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e);
    }
    FontMetrics fm = g.getFontMetrics();

    ArrayList<Integer> closedRegions = new ArrayList<Integer>();

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0 || closedRegions.contains(i))
            continue;

        ArrayList<Integer> allyRegions = new ArrayList<Integer>();
        ArrayList<Integer> openRegions = new ArrayList<Integer>();

        openRegions.add(i);

        while (openRegions.size() > 0) {
            int currentRegion = openRegions.remove(0);
            allyRegions.add(currentRegion);
            closedRegions.add(currentRegion);

            int[] linkedRegions = delaunay.getLinked(currentRegion);

            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion)
                        || allyRegions.contains(linkedRegion))
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion])
                    openRegions.add(linkedRegion);
            }
        }

        Area area = areas.get(i);
        long xsum = 0;
        long ysum = 0;

        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);
            area = areas.get(allyRegion);

            xsum += area.getX();
            ysum += area.getY();
        }

        int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1;
        int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1;
        ;

        Point point = new Point(x, y);
        boolean validLocation = false;
        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);

            if (polygons[allyRegion].contains(point)) {
                validLocation = true;
                break;
            }
        }

        if (validLocation) {
            if (allyRegions.size() == 1)
                y -= 14;
        } else {
            int xmid = (int) (xsum / allyRegions.size());
            int ymid = (int) (ysum / allyRegions.size());

            area = areas.get(i);
            int dx = area.getX() - xmid;
            int dy = area.getY() - ymid;
            int distance = dx * dx + dy * dy;

            int nearestAreaIndex = i;
            int nearestDistance = distance;

            for (int k = 0; k < allyRegions.size(); k++) {
                int allyRegion = allyRegions.get(k);

                area = areas.get(allyRegion);
                dx = area.getX() - xmid;
                dy = area.getY() - ymid;
                distance = dx * dx + dy * dy;

                if (distance < nearestDistance) {
                    nearestAreaIndex = allyRegion;
                    nearestDistance = distance;
                }
            }

            area = areas.get(nearestAreaIndex);
            x = area.getX() * MAP_SCALE + radius + 1;
            y = -area.getY() * MAP_SCALE + radius - 13;
        }

        // Dessine le tag de l'alliance
        String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]";
        g.setColor(Color.BLACK);
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y);
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y);
    }

    return finalImage;
}

From source file:dk.statsbiblioteket.doms.licensemodule.validation.LicenseValidator.java

public static GetUserQueryOutputDTO getUserQuery(GetUserQueryInputDTO input) throws Exception {
    //validate// w ww . j  a v  a 2s .c  om
    if (input.getAttributes() == null) {
        log.error("No attributes defined in input.");
        input.setAttributes(new ArrayList<UserObjAttributeDTO>());

    }

    if (input.getPresentationType() == null) {
        log.error("No presentationtype defined in input.");
        throw new IllegalArgumentException("No presentationtype defined in input.");
    }

    //Will throw exception if not matched      
    matchPresentationtype(input.getPresentationType());

    // First filter by valid date
    ArrayList<License> allLicenses = LicenseCache.getAllLicense();
    ArrayList<License> dateFilteredLicenses = filterLicenseByValidDate(allLicenses, System.currentTimeMillis());

    //Find licenses that give access (not checking groups) for the dateFiltered licenses
    ArrayList<License> accessLicenses = findLicensesValidatingAccess(input.getAttributes(),
            dateFilteredLicenses);

    ArrayList<String> types = new ArrayList<String>();
    types.add(input.getPresentationType());

    ArrayList<String> filterGroups = filterGroups(accessLicenses, types);

    //Now we have to find all MUST-groups the user is missing 
    ArrayList<ConfiguredDomLicenseGroupType> configuredMUSTDomLicenseGroupTypes = LicenseCache
            .getConfiguredMUSTDomLicenseGroupTypes();
    GetUserQueryOutputDTO output = new GetUserQueryOutputDTO();
    output.setUserLicenseGroups(filterGroups);

    ArrayList<String> missingMustGroups = new ArrayList<String>();
    //First add all must groups then remove those that user has access too
    for (ConfiguredDomLicenseGroupType current : configuredMUSTDomLicenseGroupTypes) {
        missingMustGroups.add(current.getKey());
    }

    for (String current : filterGroups) {
        missingMustGroups.remove(current);
    }
    output.setUserNotInMustGroups(missingMustGroups);

    String query = generateQueryString(filterGroups, missingMustGroups);
    output.setQuery(query);
    return output;
}

From source file:com.genentech.application.calcProps.SDFCalcProps.java

/**
 * Sort commands by dependencies ex. Solubility_Index requires cLogD7.4
 * Need to calculate cLogD7.4 before calculating solubility_index
 * cLogD7.4 command line need to appear before solubility_index command line
 *//*  ww w . j av  a2  s  .  c  o  m*/
private static List<Calculator> sortByDependencies(ArrayList<Calculator> calculators,
        int noCalculatorSizeChangeCount) {
    int oldCalculatorsSize = calculators.size();
    List<Calculator> sorted = new ArrayList<Calculator>();

    if (!calculators.isEmpty()) {
        Calculator calc = calculators.remove(0); //get first element in list

        Set<String> reqCalculators = calc.getRequiredCalculators();
        if (reqCalculators.size() == 0) {
            // no dependencies, add to beginning
            sorted.add(0, calc);
        } else { //there are dependencies
            // are any dependencies left in the list of calculators to be sorted
            if (anyDependenciesInList(reqCalculators, calculators)) {
                calculators.add(calc); //add calc back to the end of the list to be sorted later
            } else {
                //they must be in the sorted list, add calc to the end of sorted list
                sorted.add(calc); //append to end of sorted calculators
            }
        }
    }
    if (calculators.size() == oldCalculatorsSize)
        noCalculatorSizeChangeCount = noCalculatorSizeChangeCount + 1;
    else
        noCalculatorSizeChangeCount = 0;

    /*If the number of calculators in the list has not going down within
      calculators.size() times*/
    if (noCalculatorSizeChangeCount == calculators.size() && calculators.size() > 0) {
        StringBuffer calculatorText = new StringBuffer();
        for (Calculator calc : calculators)
            calculatorText = calculatorText.append(calc.getName()).append(" ");
        throw new Error("There is a circular dependencies amongst following calculators: "
                + calculatorText.substring(0, calculatorText.length()));
    }

    //recursively sort remaining calculators
    if (calculators.size() > 0) {
        //append rest to sorted
        sorted.addAll(sortByDependencies(calculators, noCalculatorSizeChangeCount));
    }
    return sorted;
}

From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java

public static ArrayList<String> updateProjectJobFiles(File projectFile, File projectConfigDirectory,
        ArrayList<String> receivedJobNames) throws IOException {

    Scanner scanner = new Scanner(projectFile);

    ArrayList<String> updatedJobs = new ArrayList<String>();
    ArrayList<String> newJobs = new ArrayList<String>();
    ArrayList<String> deletedJobs = new ArrayList<String>();

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (receivedJobNames.contains(line)) {
            updatedJobs.add(line);/*w ww . ja v  a 2  s  .  co m*/
            receivedJobNames.remove(line);
        } else {
            deletedJobs.add(line);
        }
    }
    logger.info("There are " + receivedJobNames.size() + " new jobs");
    logger.info("There are " + deletedJobs.size() + " deleted jobs");
    logger.info("There are " + updatedJobs.size() + " updated jobs");
    for (String s : receivedJobNames) {
        newJobs.add(s);
    }

    scanner.close();
    FileWriter writer = new FileWriter(projectFile, false);
    for (String s : updatedJobs) {
        writer.write(s);
        writer.write("\n");
    }
    for (String s : newJobs) {
        writer.write(s);
        writer.write("\n");
    }
    writer.close();
    return deletedJobs;
}

From source file:at.ait.dme.yuma.server.annotation.builder.RdfXmlAnnotationBuilder.java

/**
* create a mpeg21 fragment URI using a media pointer
* 
* @param annotation/*w  ww.  j a v a2s  . co  m*/
* @return URI
*/
private static String createMpeg21FragmentURI(ImageAnnotation annotation) {
    // TODO zoom level has still to be considered here
    String mpeg21URI = annotation.getImageUrl() + "#";
    ImageFragment fragment = annotation.getFragment();
    Shape shape = fragment.getShape();

    mpeg21URI += MPEG21_MEDIA_POINTER + "(~" + MPEG21_REGION_NODE + "(";
    // for polygons the first pair of coordinates use absolute values, the subsequent coords
    // are relative to the corresponding previous coordinate
    if (shape instanceof Polygon) {
        mpeg21URI += MPEG21_REGION_POLYGON + "(";
        Polygon polygon = (Polygon) shape;
        ArrayList<Point> points = new ArrayList<Point>(polygon.getPoints());
        Point firstPoint = points.remove(0);
        mpeg21URI += String.valueOf(polygon.getLeft() + firstPoint.getX()) + ","
                + String.valueOf(polygon.getTop() + firstPoint.getY());
        Point previousPoint = firstPoint;
        for (Point point : points) {
            mpeg21URI += "," + String.valueOf(point.getX() - previousPoint.getX()) + ","
                    + String.valueOf(((Point) point).getY() - previousPoint.getY());
            previousPoint = point;
        }
        mpeg21URI += ")";

    } else if (shape instanceof Ellipse) {
        mpeg21URI += MPEG21_REGION_ELLIPSE + "(";
        Ellipse ellipse = (Ellipse) shape;
        mpeg21URI += String.valueOf(ellipse.getCx()) + "," + String.valueOf(ellipse.getCy()) + ",";
        mpeg21URI += String.valueOf(ellipse.getCx() + ellipse.getRx()) + "," + String.valueOf(ellipse.getRy())
                + ",";
        mpeg21URI += String.valueOf(ellipse.getCx() + ellipse.getRx()) + ","
                + String.valueOf(ellipse.getCy() + ellipse.getRy());
        mpeg21URI += ")";

        // in case of all other shapes we use rectangles   
    } else {
        mpeg21URI += MPEG21_REGION_RECT + "(";
        mpeg21URI += String.valueOf(shape.getLeft()) + "," + String.valueOf(shape.getTop()) + ",";
        mpeg21URI += String.valueOf(shape.getLeft() + shape.getWidth()) + ","
                + String.valueOf(shape.getTop() + shape.getHeight());
        mpeg21URI += ")";
    }
    mpeg21URI += "))";

    return mpeg21URI;
}