Example usage for java.util SortedSet first

List of usage examples for java.util SortedSet first

Introduction

In this page you can find the example usage for java.util SortedSet first.

Prototype

E first();

Source Link

Document

Returns the first (lowest) element currently in this set.

Usage

From source file:org.onebusaway.nyc.vehicle_tracking.impl.particlefilter.ParticleFilter.java

/**
 * Finds the most likely/occurring trip & phase combination among the
 * particles, then chooses the particle with highest likelihood of that pair. <br>
 * //  w w w  .  ja  v  a  2  s  .  c  o m
 * FIXME violates generic particle contract by assuming data is of type
 * VehicleState
 * 
 * @param particles
 */
private void computeBestState(Multiset<Particle> particles) {
    /**
     * We choose the "most likely" particle over the entire distribution w.r.t
     * the inferred trip.
     */
    final TObjectDoubleMap<String> tripPhaseToProb = new TObjectDoubleHashMap<String>();

    final HashMultimap<String, Particle> particlesIdMap = HashMultimap.create();
    final SortedSet<Particle> bestParticles = new TreeSet<Particle>();
    String bestId = null;

    if (!_maxLikelihoodParticle) {
        double highestTripProb = Double.MIN_VALUE;
        int index = 0;
        for (final Multiset.Entry<Particle> pEntry : particles.entrySet()) {
            final Particle p = pEntry.getElement();
            p.setIndex(index++);

            final double w = FastMath.exp(p.getLogWeight() + FastMath.log(pEntry.getCount()));

            if (Double.isInfinite(w))
                continue;

            final VehicleState vs = p.getData();
            final String tripId = vs.getBlockState() == null ? "NA"
                    : vs.getBlockState().getBlockLocation().getActiveTrip().getTrip().toString();
            final String phase = vs.getJourneyState().toString();
            final String id = tripId + "." + phase;

            final double newProb = tripPhaseToProb.adjustOrPutValue(id, w, w);

            particlesIdMap.put(id, p);

            /**
             * Check most likely new trip & phase pairs, then find the most likely
             * particle(s) within those.
             */
            if (bestId == null || newProb > highestTripProb) {
                bestId = id;
                highestTripProb = newProb;
            }
        }
        bestParticles.addAll(particlesIdMap.get(bestId));
    } else {
        bestParticles.addAll(particles);
    }

    /**
     * after we've found the best trip & phase pair, we choose the highest
     * likelihood particle among those.
     */
    final Particle bestParticle = bestParticles.first();

    _mostLikelyParticle = bestParticle.cloneParticle();

}

From source file:org.wso2.carbon.apimgt.impl.AbstractAPIManagerTestCase.java

@Test
public void testSearchPaginatedAPIs()
        throws APIManagementException, org.wso2.carbon.user.api.UserStoreException, RegistryException {
    Map<String, Object> subContextResult = new HashMap<String, Object>();
    subContextResult.put("1", new Object());
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapperExtended(null, registryService,
            registry, tenantManager);//from   w  w w  . j a  v  a  2  s  . co  m
    Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenReturn(-1234);
    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt()))
            .thenThrow(RegistryException.class).thenReturn(registry);

    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString()))
            .thenAnswer((Answer<String>) invocation -> {
                Object[] args = invocation.getArguments();
                return (String) args[0];
            });

    try {
        abstractAPIManager.searchPaginatedAPIs("search", API_PROVIDER, 0, 5, false);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to Search APIs"));
    }
    API api = new API(getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION));
    Documentation documentation = new Documentation(DocumentationType.HOWTO, "DOC1");
    Map<Documentation, API> documentationAPIMap = new HashMap<>();
    BDDMockito.when(APIUtil.searchAPIsByDoc(Mockito.any(), Mockito.anyInt(), Mockito.anyString(),
            Mockito.anyString(), Mockito.anyString())).thenReturn(documentationAPIMap);
    Assert.assertEquals(abstractAPIManager
            .searchPaginatedAPIs("doc=search", SAMPLE_TENANT_DOMAIN_1, 0, 5, false).get("length"), 0);
    documentationAPIMap.put(documentation, api);
    Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("doc=search", null, 0, 5, false).get("length"),
            5);
    Map<String, Object> contextApis = new HashMap<>();
    contextApis.put("api2", new Object());
    BDDMockito.when(APIUtil.searchAPIsByURLPattern(Mockito.any(), Mockito.anyString(), Mockito.anyInt(),
            Mockito.anyInt())).thenReturn(contextApis);
    Assert.assertTrue(
            abstractAPIManager.searchPaginatedAPIs("subcontext=search", null, 0, 5, false).containsKey("api2"));

    // Test related with searches with custom properties
    Map<String, Object> actualAPIs = abstractAPIManager.searchPaginatedAPIs("secured=*true*",
            SAMPLE_TENANT_DOMAIN_1, 0, 5, false);
    List<API> retrievedAPIs = (List<API>) actualAPIs.get("apis");
    Assert.assertEquals("Searching with additional property failed", 1, actualAPIs.get("length"));
    Assert.assertNotNull("Search with additional property failed", retrievedAPIs);
    Assert.assertEquals("Search with additional property failed", 1, retrievedAPIs.size());
    Assert.assertEquals("Search with additional property failed", "sxy",
            retrievedAPIs.get(0).getId().getApiName());

    actualAPIs = abstractAPIManager.searchPaginatedAPIs("name=*test*&secured=*true*", SAMPLE_TENANT_DOMAIN_1, 0,
            5, false);
    retrievedAPIs = (List<API>) actualAPIs.get("apis");
    Assert.assertEquals("Searching with additional property failed", 1, actualAPIs.get("length"));
    Assert.assertNotNull("Search with additional property failed", retrievedAPIs);
    Assert.assertEquals("Search with additional property failed", 1, retrievedAPIs.size());
    Assert.assertEquals("Search with additional property failed", "sxy12",
            retrievedAPIs.get(0).getId().getApiName());

    TestUtils.mockAPIMConfiguration(APIConstants.API_STORE_APIS_PER_PAGE, null, -1234);
    Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("search", null, 0, 5, false).get("length"), 0);
    TestUtils.mockAPIMConfiguration(APIConstants.API_STORE_APIS_PER_PAGE, "5", -1234);
    GovernanceArtifact governanceArtifact = getGenericArtifact(SAMPLE_API_NAME, API_PROVIDER,
            SAMPLE_API_VERSION, "qname");
    List<GovernanceArtifact> governanceArtifactList = new ArrayList<GovernanceArtifact>();
    governanceArtifactList.add(governanceArtifact);
    Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("search", null, 0, 5, false).get("length"), 0);
    Assert.assertEquals(abstractAPIManager
            .searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false).get("length"), 0);
    BDDMockito
            .when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(), Mockito.any(Registry.class),
                    Mockito.anyString(), Mockito.anyBoolean()))
            .thenThrow(RegistryException.class).thenReturn(governanceArtifactList);
    try {
        abstractAPIManager.searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false);
        Assert.fail("APIM exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to Search APIs"));
    }
    API api1 = new API(getAPIIdentifier("api1", API_PROVIDER, "v1"));
    BDDMockito.when(APIUtil.getAPI((GovernanceArtifact) Mockito.any(), (Registry) Mockito.any()))
            .thenReturn(api1);
    SortedSet<API> apiSet = (SortedSet<API>) abstractAPIManager
            .searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false).get("apis");
    Assert.assertEquals(apiSet.size(), 1);
    Assert.assertEquals(apiSet.first().getId().getApiName(), "api1");
    Assert.assertEquals(abstractAPIManager
            .searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, true).get("length"), 0);
    PowerMockito.when(paginationContext.getLength()).thenReturn(12);
    Assert.assertTrue((Boolean) abstractAPIManager
            .searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, true).get("isMore"));
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlPage.java

/**
 * {@inheritDoc}/*from  w  w w  .  ja  v a  2s  . c o m*/
 */
@Override
public DomElement getElementById(final String elementId) {
    final SortedSet<DomElement> elements = idMap_.get(elementId);
    if (elements != null) {
        return elements.first();
    }
    return null;
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlPage.java

/**
 * Returns the element with the specified name. If more than one element
 * has this name, then this method returns the first one.
 *
 * @param name the name value to search for
 * @param <E> the element type//  www  . j  a v  a 2s .  c o  m
 * @return the element with the specified name
 * @throws ElementNotFoundException if no element was found matching the specified name
 */
@SuppressWarnings("unchecked")
public <E extends DomElement> E getElementByName(final String name) throws ElementNotFoundException {
    final SortedSet<DomElement> elements = nameMap_.get(name);
    if (elements != null) {
        return (E) elements.first();
    }
    throw new ElementNotFoundException("*", "name", name);
}

From source file:org.apache.atlas.hive.hook.HiveHookIT.java

@Test
public void testInsertIntoTable() throws Exception {
    String inputTable1Name = createTable();
    String inputTable2Name = createTable();
    String insertTableName = createTable();
    assertTableIsRegistered(DEFAULT_DB, inputTable1Name);
    assertTableIsRegistered(DEFAULT_DB, insertTableName);

    String query = "insert into " + insertTableName + " select t1.id, t1.name from " + inputTable2Name
            + " as t2, " + inputTable1Name + " as t1 where t1.id=t2.id";

    runCommand(query);//from  w w w.j a  v  a 2s  .  c o m
    final Set<ReadEntity> inputs = getInputs(inputTable1Name, Entity.Type.TABLE);
    inputs.addAll(getInputs(inputTable2Name, Entity.Type.TABLE));

    Set<WriteEntity> outputs = getOutputs(insertTableName, Entity.Type.TABLE);
    (outputs.iterator().next()).setWriteType(WriteEntity.WriteType.INSERT);

    HiveHook.HiveEventContext event = constructEvent(query, HiveOperation.QUERY, inputs, outputs);

    Set<ReadEntity> expectedInputs = new TreeSet<ReadEntity>(entityComparator) {
        {
            addAll(inputs);
        }
    };
    assertTableIsRegistered(DEFAULT_DB, insertTableName);
    Referenceable processRef1 = validateProcess(event, expectedInputs, outputs);

    //Test sorting of tbl names
    SortedSet<String> sortedTblNames = new TreeSet<>();
    sortedTblNames.add(inputTable1Name.toLowerCase());
    sortedTblNames.add(inputTable2Name.toLowerCase());

    //Verify sorted order of inputs in qualified name
    Assert.assertEquals(processRef1.get(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME),

            Joiner.on(SEP).join("QUERY", getQualifiedTblName(sortedTblNames.first()),
                    HiveMetaStoreBridge.getTableCreatedTime(
                            hiveMetaStoreBridge.hiveClient.getTable(DEFAULT_DB, sortedTblNames.first()))
                            .getTime(),
                    getQualifiedTblName(sortedTblNames.last()),
                    HiveMetaStoreBridge
                            .getTableCreatedTime(
                                    hiveMetaStoreBridge.hiveClient.getTable(DEFAULT_DB, sortedTblNames.last()))
                            .getTime())
                    + IO_SEP + SEP
                    + Joiner.on(SEP).join(WriteEntity.WriteType.INSERT.name(),
                            getQualifiedTblName(insertTableName),
                            HiveMetaStoreBridge.getTableCreatedTime(
                                    hiveMetaStoreBridge.hiveClient.getTable(DEFAULT_DB, insertTableName))
                                    .getTime()));

    //Rerun same query. Should result in same process
    runCommandWithDelay(query, 1000);
    Referenceable processRef2 = validateProcess(event, expectedInputs, outputs);
    Assert.assertEquals(processRef1.getId()._getId(), processRef2.getId()._getId());

}

From source file:org.torproject.ernie.web.DescriptorServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    /* Measure how long it takes to process this request. */
    long started = System.currentTimeMillis();

    /* Get print writer and start writing response. */
    PrintWriter out = response.getWriter();
    writeHeader(out);//  www.  java 2 s  .c o m

    /* Check desc-id parameter. */
    String descIdParameter = request.getParameter("desc-id");
    String descId = null;
    if (descIdParameter != null && descIdParameter.length() >= 8 && descIdParameter.length() <= 40) {
        Pattern descIdPattern = Pattern.compile("^[0-9a-f]{8,40}$");
        if (descIdPattern.matcher(descIdParameter.toLowerCase()).matches()) {
            descId = descIdParameter.toLowerCase();
        }
    }
    if (descId == null) {
        out.write("    <br/><p>Sorry, \"" + descIdParameter + "\" is not a "
                + "valid descriptor identifier. Please provide at least the "
                + "first 8 hex characters of a descriptor identifier.</p>\n");
        writeFooter(out);
        return;
    }

    /* If we were only given a partial descriptor identifier, look up all
     * descriptor identifiers starting with that part to see if it's
     * unique. */
    if (descId.length() < 40) {
        SortedSet<String> allDescIds = new TreeSet<String>();
        try {
            Connection conn = this.ds.getConnection();
            Statement statement = conn.createStatement();
            String query = "SELECT DISTINCT descriptor FROM statusentry " + "WHERE descriptor LIKE '" + descId
                    + "%'";
            ResultSet rs = statement.executeQuery(query);
            while (rs.next()) {
                allDescIds.add(rs.getString(1));
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            out.println("<p><font color=\"red\"><b>Warning: </b></font>We "
                    + "experienced an unknown database problem while looking up "
                    + "descriptors with identifier starting with " + descId
                    + ". If this problem persists, please "
                    + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
            writeFooter(out);
            return;
        }
        if (allDescIds.size() == 0) {
            out.write("<p>No descriptor found " + (descId.length() < 40 ? "starting " : "") + "with identifier "
                    + descId + ".</p>");
            writeFooter(out);
            return;
        } else if (allDescIds.size() > 1) {
            out.println("<p>The descriptor identifier part " + descIdParameter
                    + " is not unique. Please choose one of the following " + "descriptors:</p><ul>");
            for (String f : allDescIds) {
                out.println("<li><a href=\"descriptor.html?desc-id=" + f + "\">" + f + "</a></li>");
            }
            out.write("</ul><br/>");
            writeFooter(out);
            return;
        } else {
            descId = allDescIds.first();
        }
    }

    /* Look up descriptor in the database. */
    String descriptor = null, nickname = null, published = null, extrainfo = null;
    byte[] rawDescriptor = null, rawExtrainfo = null;
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT descriptor, nickname, published, extrainfo, "
                + "rawdesc FROM descriptor WHERE descriptor = '" + descId + "'";
        ResultSet rs = statement.executeQuery(query);
        if (rs.next()) {
            descriptor = rs.getString(1);
            nickname = rs.getString(2);
            published = rs.getTimestamp(3).toString().substring(0, 19);
            extrainfo = rs.getString(4);
            rawDescriptor = rs.getBytes(5);
        }
        query = "SELECT rawdesc FROM extrainfo WHERE extrainfo = '" + extrainfo + "'";
        rs = statement.executeQuery(query);
        if (rs.next()) {
            rawExtrainfo = rs.getBytes(1);
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        out.write("<br/><p><font color=\"red\"><b>Warning: </b></font>"
                + "Internal server error when looking up descriptor. If this " + "problem persists, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
        writeFooter(out);
        return;
    }

    /* If no descriptor was found, stop here. */
    if (descriptor == null) {
        out.write("<p>No descriptor found " + (descIdParameter.length() < 40 ? "starting " : "")
                + "with identifier " + descIdParameter + ".</p>");
        writeFooter(out);
        return;
    }

    /* Print out both server and extra-info descriptor. */
    out.write("<br/><p>The following server descriptor was published by " + "relay " + nickname + " at "
            + published + " UTC:</p>");
    BufferedReader br = new BufferedReader(new StringReader(new String(rawDescriptor, "US-ASCII")));
    String line = null;
    while ((line = br.readLine()) != null) {
        out.println("        <tt>" + line + "</tt><br/>");
    }
    br.close();
    if (rawExtrainfo != null) {
        out.println("<br/><p>Together with this server descriptor, the "
                + "relay published the following extra-info descriptor:</p>");
        br = new BufferedReader(new StringReader(new String(rawExtrainfo, "US-ASCII")));
        line = null;
        while ((line = br.readLine()) != null) {
            out.println("        <tt>" + line + "</tt><br/>");
        }
    }

    /* Print out in which consensuses this descriptor is referenced. */
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT validafter, rawdesc FROM statusentry " + "WHERE descriptor = '" + descriptor
                + "' ORDER BY validafter " + "DESC";
        ResultSet rs = statement.executeQuery(query);
        boolean printedDescription = false;
        while (rs.next()) {
            if (!printedDescription) {
                out.println("<br/><p>This server descriptor is referenced from "
                        + "the following network status consensuses:</p>");
                printedDescription = true;
            }
            String validAfter = rs.getTimestamp(1).toString().substring(0, 19);
            out.println("        <br/><tt>valid-after " + "<a href=\"consensus?valid-after="
                    + validAfter.replaceAll(":", "-").replaceAll(" ", "-") + "\" target=\"_blank\">"
                    + validAfter + "</a></tt><br/>");
            byte[] rawStatusEntry = rs.getBytes(2);
            br = new BufferedReader(new StringReader(new String(rawStatusEntry, "US-ASCII")));
            line = null;
            while ((line = br.readLine()) != null) {
                out.println("        <tt>" + line + "</tt><br/>");
            }
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        out.println("<p><font color=\"red\"><b>Warning: </b></font>We "
                + "experienced an unknown database problem while looking up "
                + "the network status consensuses referencing descriptor " + descId
                + ". If this problem persists, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
    }

    /* Provide links to raw descriptors, too. */
    out.println("<br/><p>Note that the descriptor" + (rawExtrainfo != null ? "s have" : " has")
            + " been converted to ASCII and reformatted "
            + "for display purposes. You may also download the raw " + "<a href=\"serverdesc?desc-id="
            + descriptor + "\" target=\"_blank\">server " + "descriptor</a>"
            + (extrainfo != null
                    ? " and <a href=\"extrainfodesc?desc-id=" + extrainfo
                            + "\" target=\"_blank\">extra-info descriptor</a>"
                    : "")
            + " as " + (extrainfo != null ? "they were" : "it was")
            + " published to the directory authorities.</p>");

    /* Display total lookup time on the results page. */
    long searchTime = System.currentTimeMillis() - started;
    out.write("        <br/><p>Looking up this descriptor took us "
            + String.format("%d.%03d", searchTime / 1000, searchTime % 1000) + " seconds.</p>\n");

    /* Finish writing response. */
    writeFooter(out);
}

From source file:org.pharmgkb.Subject.java

public String getBreastCancerFreeInterval() {
    SortedSet<Integer> freeIntervals = Sets.newTreeSet();

    if (getCauseOfDeath() != null && getCauseOfDeath().equals("1")) {
        freeIntervals.add(parseDays(getDaysDiagtoDeath()));
    }//from  w w  w  . ja v a2 s . c  o  m

    if (!ItpcUtils.isBlank(getAddCxIpsilateral())) {
        Integer ipsiDays = parseDays(getAddCxIpsilateral());
        if (ipsiDays > 0) {
            freeIntervals.add(ipsiDays);
        }
    }
    if (!ItpcUtils.isBlank(getAddCxDistantRecur())) {
        Integer days = parseDays(getAddCxDistantRecur());
        if (days > 0) {
            freeIntervals.add(days);
        }
    }
    if (!ItpcUtils.isBlank(getAddCxContralateral())) {
        Integer days = parseDays(getAddCxContralateral());
        if (days > 0) {
            freeIntervals.add(days);
        }
    }

    if (!freeIntervals.isEmpty()) {
        return Integer.toString(freeIntervals.first());
    } else {
        return "";
    }
}

From source file:org.apache.pulsar.broker.admin.impl.NamespacesBase.java

protected BundlesData validateBundlesData(BundlesData initialBundles) {
    SortedSet<String> partitions = new TreeSet<String>();
    for (String partition : initialBundles.getBoundaries()) {
        Long partBoundary = Long.decode(partition);
        partitions.add(String.format("0x%08x", partBoundary));
    }/*from w ww  . j  av a  2 s. c  om*/
    if (partitions.size() != initialBundles.getBoundaries().size()) {
        log.debug("Input bundles included repeated partition points. Ignored.");
    }
    try {
        NamespaceBundleFactory.validateFullRange(partitions);
    } catch (IllegalArgumentException iae) {
        throw new RestException(Status.BAD_REQUEST, "Input bundles do not cover the whole hash range. first:"
                + partitions.first() + ", last:" + partitions.last());
    }
    List<String> bundles = Lists.newArrayList();
    bundles.addAll(partitions);
    return new BundlesData(bundles);
}

From source file:cerrla.Performance.java

/**
 * Outputs performance information and estimates convergence.
 * /*from ww w  . j  a  v a  2  s  . c o m*/
 * @param convergence
 *            The convergence as given by the rule distributions.
 * @param numElites
 *            The minimum number of elites.
 * @param elites
 *            The current elites.
 * @param numSlots
 *            The number of slots in the distribution.
 * @param goalCondition
 *            The goal condition this performance is concerned with.
 */
public void estimateETA(double convergence, int numElites, SortedSet<PolicyValue> elites, int numSlots,
        GoalCondition goalCondition) {
    if (!ProgramArgument.SYSTEM_OUTPUT.booleanValue())
        return;

    boolean mainGoal = goalCondition.isMainGoal();

    if (mainGoal) {
        long currentTime = System.currentTimeMillis();
        long elapsedTime = currentTime - trainingStartTime_;
        String elapsed = "Elapsed: " + RRLExperiment.toTimeFormat(elapsedTime);
        System.out.println(elapsed);
    }

    boolean noUpdates = false;
    if (convergence == PolicyGenerator.NO_UPDATES_CONVERGENCE) {
        noUpdates = true;
        convergence = 0;
    }
    double totalRunComplete = (1.0 * runIndex_ + convergence) / Config.getInstance().getNumRepetitions();
    if (frozen_)
        totalRunComplete = 1.0 * (runIndex_ + 1) / Config.getInstance().getNumRepetitions();

    DecimalFormat formatter = new DecimalFormat("#0.0000");
    String modular = "";
    if (!goalCondition.isMainGoal())
        modular = "MODULAR: [" + goalCondition + "] ";
    // No updates yet, convergence unknown
    String percentStr = null;
    if (noUpdates) {
        percentStr = "Unknown convergence; No updates yet.";
    } else if (!frozen_) {
        percentStr = "~" + formatter.format(100 * convergence) + "% " + modular + "converged (" + numSlots
                + " slots).";
    } else {
        if (convergence <= 1)
            percentStr = formatter.format(100 * convergence) + "% " + modular + "test complete.";
        else
            percentStr = "---FULLY CONVERGED---";
    }
    System.out.println(percentStr);

    if (!frozen_) {
        // Adjust numElites if using bounded elites
        String best = (!elites.isEmpty()) ? "" + formatter.format(elites.first().getValue()) : "?";
        String worst = (!elites.isEmpty()) ? "" + formatter.format(elites.last().getValue()) : "?";
        String eliteString = "N_E: " + numElites + ", |E|: " + elites.size() + ", E_best: " + best
                + ", E_worst: " + worst;
        System.out.println(eliteString);
    }

    if (mainGoal) {
        String totalPercentStr = formatter.format(100 * totalRunComplete) + "% experiment complete.";
        System.out.println(totalPercentStr);
    }
}

From source file:net.sf.jasperreports.engine.fill.DefaultChartTheme.java

/**
 *
 */// w w  w .j  a v  a  2 s  . c om
protected void configurePlot(Plot plot) {
    plot.setOutlinePaint(null);

    if (getPlot().getOwnBackcolor() == null)// in a way, plot backcolor inheritence from chart is useless
    {
        plot.setBackgroundPaint(null);
    } else {
        plot.setBackgroundPaint(getPlot().getBackcolor());
    }

    float backgroundAlpha = getPlot().getBackgroundAlphaFloat() == null ? 1f
            : getPlot().getBackgroundAlphaFloat();
    float foregroundAlpha = getPlot().getForegroundAlphaFloat() == null ? 1f
            : getPlot().getForegroundAlphaFloat();
    plot.setBackgroundAlpha(backgroundAlpha);
    plot.setForegroundAlpha(foregroundAlpha);

    if (plot instanceof CategoryPlot) {
        // Handle rotation of the category labels.
        CategoryAxis axis = ((CategoryPlot) plot).getDomainAxis();
        // it's OK to use deprecated method here; avoiding it means attempting cast operations  
        double labelRotation = getLabelRotation();
        if (labelRotation == 90) {
            axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);
        } else if (labelRotation == -90) {
            axis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        } else if (labelRotation < 0) {
            axis.setCategoryLabelPositions(
                    CategoryLabelPositions.createUpRotationLabelPositions((-labelRotation / 180.0) * Math.PI));
        } else if (labelRotation > 0) {
            axis.setCategoryLabelPositions(
                    CategoryLabelPositions.createDownRotationLabelPositions((labelRotation / 180.0) * Math.PI));
        }
    }

    // Set any color series
    SortedSet<JRSeriesColor> seriesColors = getPlot().getSeriesColors();
    if (seriesColors != null && seriesColors.size() > 0) {
        if (seriesColors.size() == 1) {
            // Add the single color to the beginning of the color cycle, using all the default
            // colors.  To replace the defaults you have to specify at least two colors.
            Paint[] colors = new Paint[DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length + 1];
            colors[0] = seriesColors.first().getColor();
            System.arraycopy(DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE, 0, colors, 1,
                    DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length);
            plot.setDrawingSupplier(
                    new DefaultDrawingSupplier(colors, DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE));
        } else if (seriesColors.size() > 1) {
            // Set up a custom drawing supplier that cycles through the user's colors
            // instead of the default colors.
            Color[] colors = new Color[seriesColors.size()];
            JRSeriesColor[] colorSequence = new JRSeriesColor[seriesColors.size()];
            seriesColors.toArray(colorSequence);
            for (int i = 0; i < colorSequence.length; i++) {
                colors[i] = colorSequence[i].getColor();
            }

            plot.setDrawingSupplier(
                    new DefaultDrawingSupplier(colors, DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE));
        }
    }
}