Example usage for org.apache.commons.math.util MathUtils round

List of usage examples for org.apache.commons.math.util MathUtils round

Introduction

In this page you can find the example usage for org.apache.commons.math.util MathUtils round.

Prototype

public static float round(float x, int scale, int roundingMethod) 

Source Link

Document

Round the given value to the specified number of decimal places.

Usage

From source file:com.algoTrader.util.RoundUtil.java

public static double roundToNextN(double value, double n, int roundingMethod) {

    return MathUtils.round(value / n, 0, roundingMethod) * n;
}

From source file:ch.algotrader.util.RoundUtil.java

public static double roundToNextN(double value, double n, int roundingMethod) {

    return MathUtils.round((value) / n, 0, roundingMethod) * n;
}

From source file:cc.recommenders.mining.calls.NetworkMathUtils.java

@Deprecated
public static double round(final double value, final int precision) {
    return MathUtils.round(value, precision, BigDecimal.ROUND_HALF_EVEN);

}

From source file:org.apache.jackrabbit.core.query.lucene.JahiaLuceneQueryFactoryImpl.java

/**
 * Override LuceneQueryFactory.execute()
 *//*w ww.ja va 2s  .  c  om*/
@Override
public List<Row> execute(Map<String, PropertyValue> columns, Selector selector, Constraint constraint,
        Sort sort, boolean externalSort, long offsetIn, long limitIn) throws RepositoryException, IOException {
    final IndexReader reader = index.getIndexReader(true);
    final int offset = offsetIn < 0 ? 0 : (int) offsetIn;
    final int limit = limitIn < 0 ? Integer.MAX_VALUE : (int) limitIn;

    QueryHits hits = null;
    try {
        JackrabbitIndexSearcher searcher = new JackrabbitIndexSearcher(session, reader,
                index.getContext().getItemStateManager());
        searcher.setSimilarity(index.getSimilarity());

        Predicate filter = Predicate.TRUE;
        BooleanQuery query = new BooleanQuery();

        QueryPair qp = new QueryPair(query);

        query.add(create(selector), MUST);
        if (constraint != null) {
            String name = selector.getSelectorName();
            NodeType type = ntManager.getNodeType(selector.getNodeTypeName());
            filter = mapConstraintToQueryAndFilter(qp, constraint, Collections.singletonMap(name, type),
                    searcher, reader);
        }

        // Added by jahia
        Set<String> foundIds = new HashSet<String>();
        int hasFacets = FacetHandler.hasFacetFunctions(columns, session);
        CountHandler.CountType countType = CountHandler.hasCountFunction(columns, session);
        boolean isCount = countType != null;
        BitSet bitset = (hasFacets & FacetHandler.FACET_COLUMNS) == 0 ? null : new BitSet();
        // End

        List<Row> rowList = externalSort ? new LinkedList<Row>() : null;
        Map<String, Row> rows = externalSort ? null : new LinkedHashMap<String, Row>();
        hits = searcher.evaluate(qp.mainQuery, sort, offset + limit);
        int currentNode = 0;
        int addedNodes = 0;
        int resultCount = 0;
        int hitsSize = 0;

        ScoreNode node = hits.nextScoreNode();
        Map<String, Boolean> checkedAcls = new HashMap<String, Boolean>();

        while (node != null) {
            if (isCount && countType.isApproxCount()) {
                hitsSize++;
                if (hitsSize > countType.getApproxCountLimit()) {
                    if (hits.getSize() > 0) {
                        hitsSize = hits.getSize();
                        break;
                    } else {
                        node = hits.nextScoreNode();
                        continue;
                    }
                }
            }
            IndexedNodeInfo infos = getIndexedNodeInfo(node, reader, isCount && countType.isSkipChecks());
            if (foundIds.add(infos.getMainNodeUuid())) { // <-- Added by jahia
                if (isCount && countType.isSkipChecks()) {
                    resultCount++;
                } else {
                    try {
                        boolean canRead = true;
                        if (isAclUuidInIndex()) {
                            canRead = checkIndexedAcl(checkedAcls, infos);
                        }
                        boolean checkVisibility = "1".equals(infos.getCheckVisibility())
                                && Constants.LIVE_WORKSPACE.equals(session.getWorkspace().getName());

                        if (canRead && (!Constants.LIVE_WORKSPACE.equals(session.getWorkspace().getName())
                                || ((infos.getPublished() == null || "true".equals(infos.getPublished()))
                                        && (infos.getCheckInvalidLanguages() == null || getLocale() == null
                                                || !infos.getCheckInvalidLanguages()
                                                        .contains(getLocale().toString()))))) {
                            if (filter == Predicate.TRUE) { // <-- Added by jahia
                                if ((hasFacets & FacetHandler.ONLY_FACET_COLUMNS) == 0) {
                                    Row row = null;

                                    if (checkVisibility || !isAclUuidInIndex()) {
                                        NodeImpl objectNode = getNodeWithAclAndVisibilityCheck(node,
                                                checkVisibility);
                                        if (isCount) {
                                            resultCount++;
                                        } else {
                                            row = new LazySelectorRow(columns, evaluator,
                                                    selector.getSelectorName(), objectNode, node.getScore());
                                        }
                                    } else {
                                        if (isCount) {
                                            resultCount++;
                                        } else {
                                            row = new LazySelectorRow(columns, evaluator,
                                                    selector.getSelectorName(), node.getNodeId(),
                                                    node.getScore());
                                        }
                                    }

                                    if (row == null) {
                                        continue;
                                    }

                                    if (externalSort) {
                                        rowList.add(row);
                                    } else {
                                        // apply limit and offset rules locally
                                        if (currentNode >= offset && currentNode - offset < limit) {
                                            rows.put(node.getNodeId().toString(), row);
                                            addedNodes++;
                                        }
                                        currentNode++;
                                        // end the loop when going over the limit
                                        if (addedNodes == limit) {
                                            break;
                                        }
                                    }
                                }
                                if ((hasFacets & FacetHandler.FACET_COLUMNS) == FacetHandler.FACET_COLUMNS) {
                                    //Added by Jahia
                                    //can be added to bitset when ACL checked and not in live mode or no visibility rule to check
                                    if (isAclUuidInIndex() && !checkVisibility) {
                                        bitset.set(infos.getDocNumber());
                                    } else { //try to load nodeWrapper to check the visibility rules
                                        NodeImpl objectNode = getNodeWithAclAndVisibilityCheck(node,
                                                checkVisibility);
                                        bitset.set(infos.getDocNumber());
                                    }
                                    //!Added by Jahia
                                }
                            } else {
                                NodeImpl objectNode = session.getNodeById(node.getNodeId());
                                if (objectNode.isNodeType("jnt:translation")) {
                                    objectNode = (NodeImpl) objectNode.getParent();
                                }
                                if (isCount) {
                                    resultCount++;
                                } else {
                                    Row row = new SelectorRow(columns, evaluator, selector.getSelectorName(),
                                            objectNode, node.getScore());
                                    if (filter.evaluate(row)) {
                                        if ((hasFacets & FacetHandler.ONLY_FACET_COLUMNS) == 0) {
                                            if (externalSort) {
                                                rowList.add(row);
                                            } else {
                                                // apply limit and offset rules locally
                                                if (currentNode >= offset && currentNode - offset < limit) {
                                                    rows.put(node.getNodeId().toString(), row);
                                                    addedNodes++;
                                                }
                                                currentNode++;
                                                // end the loop when going over the limit
                                                if (addedNodes == limit) {
                                                    break;
                                                }
                                            }
                                        }
                                        if ((hasFacets
                                                & FacetHandler.FACET_COLUMNS) == FacetHandler.FACET_COLUMNS) {
                                            bitset.set(infos.getDocNumber()); // <-- Added by jahia
                                        }
                                    }
                                }
                            }
                        }
                    } catch (PathNotFoundException e) {
                    } catch (ItemNotFoundException e) {
                        // skip the node
                    }
                }
            } else {
                if (((hasFacets & FacetHandler.ONLY_FACET_COLUMNS) == 0) && !isCount && !externalSort
                        && !infos.getMainNodeUuid().equals(node.getNodeId().toString())
                        && rows.containsKey(infos.getMainNodeUuid())) {
                    // we've got the translation node -> adjusting the position of the original node in the result list
                    rows.put(infos.getMainNodeUuid(), rows.remove(infos.getMainNodeUuid()));
                }
            } // <-- Added by jahia
            node = hits.nextScoreNode();
        }

        if (rowList == null) {
            if (rows != null) {
                rowList = new LinkedList<Row>(rows.values());
            } else {
                rowList = new LinkedList<Row>();
            }
        }
        // Added by jahia
        if ((hasFacets & FacetHandler.FACET_COLUMNS) == FacetHandler.FACET_COLUMNS) {
            OpenBitSet docIdSet = new OpenBitSetDISI(new DocIdBitSet(bitset).iterator(), bitset.size());

            FacetHandler h = new FacetHandler(columns, selector, docIdSet, index, session, nsMappings);
            h.handleFacets(reader);
            rowList.add(0, h.getFacetsRow());
        } else if (isCount) {
            boolean wasApproxLimitReached = false;
            if (countType.isApproxCount() && hitsSize > countType.getApproxCountLimit()) {
                resultCount = hitsSize * resultCount / countType.getApproxCountLimit();
                resultCount = (int) Math.ceil(MathUtils.round(resultCount,
                        resultCount < 1000 ? -1 : (resultCount < 10000 ? -2 : -3), BigDecimal.ROUND_UP));
                wasApproxLimitReached = true;
            }
            rowList.add(0, CountHandler.createCountRow(resultCount, wasApproxLimitReached));
        }
        // End

        return rowList;
    } finally {
        if (hits != null) {
            hits.close();
        }
        Util.closeOrRelease(reader);
    }
}

From source file:org.jahia.services.search.jcr.JahiaJCRSearchProvider.java

public SearchResponse search(SearchCriteria criteria, RenderContext context) {
    SearchResponse response = new SearchResponse();
    List<Hit<?>> results = new ArrayList<Hit<?>>();
    response.setResults(results);//w ww  .  j av a2s.co m

    try {
        JCRSessionWrapper session = ServicesRegistry.getInstance().getJCRStoreService().getSessionFactory()
                .getCurrentUserSession(context.getMainResource().getWorkspace(),
                        context.getMainResource().getLocale(), context.getFallbackLocale());
        Query query = buildQuery(criteria, session);
        final int offset = criteria.getOffset() < 0 ? 0 : (int) criteria.getOffset();
        final int limit = criteria.getLimit() <= 0 ? Integer.MAX_VALUE : (int) criteria.getLimit();
        response.setOffset(offset);
        response.setLimit(limit);
        int count = 0;
        if (query != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Executing search query [{}]", query.getStatement());
            }
            QueryResult queryResult = query.execute();
            RowIterator it = queryResult.getRows();
            Set<String> languages = new HashSet<String>();
            if (it.hasNext()) {
                if (!criteria.getLanguages().isEmpty()) {
                    for (String languageCode : criteria.getLanguages().getValues()) {
                        if (!StringUtils.isEmpty(languageCode)) {
                            languages.add(languageCode);
                        }
                    }
                } else {
                    if (session.getLocale() != null) {
                        languages.add(session.getLocale().toString());
                    }
                }
            }

            Set<String> usageFilterSites = !criteria.getSites().isEmpty()
                    && !criteria.getSites().getValue().equals("-all-")
                    && !criteria.getSitesForReferences().isEmpty()
                            ? Sets.newHashSet(criteria.getSites().getValues())
                            : null;

            Set<String> addedNodes = new HashSet<String>();
            Map<String, JCRNodeHit> addedHits = new HashMap<String, JCRNodeHit>();
            List<JCRNodeHit> hitsToAdd = new ArrayList<JCRNodeHit>();
            final int requiredHits = limit + offset;

            boolean displayableNodeCompat = Boolean.valueOf(
                    SettingsBean.getInstance().getPropertiesFile().getProperty("search.displayableNodeCompat"));

            while (it.hasNext()) {
                count++;
                Row row = it.nextRow();
                try {
                    JCRNodeWrapper node = (JCRNodeWrapper) row.getNode();
                    if (node != null && (node.isNodeType(Constants.JAHIANT_TRANSLATION)
                            || Constants.JCR_CONTENT.equals(node.getName()))) {
                        node = node.getParent();
                    }
                    if (node != null && node.isNodeType("jnt:vanityUrl")) {
                        node = node.getParent().getParent();
                    }
                    if (node != null && addedNodes.add(node.getIdentifier())) {
                        boolean skipNode = isNodeToSkip(node, criteria, languages);

                        JCRNodeHit hit = !skipNode ? buildHit(row, node, context, usageFilterSites) : null;

                        if (!skipNode && !displayableNodeCompat) {
                            //check if node is invisible (or don't have a displayable parent or reference)
                            skipNode = hit.getDisplayableNode() == null;
                        }
                        if (!skipNode && usageFilterSites != null
                                && !usageFilterSites.contains(node.getResolveSite().getName())) {
                            skipNode = hit.getUsages().isEmpty();
                        }
                        if (!skipNode) {
                            hitsToAdd.add(hit);

                            if (hitsToAdd.size() + addedHits.size() >= requiredHits) {
                                SearchServiceImpl.executeURLModificationRules(hitsToAdd, context);
                                addHitsToResults(hitsToAdd, results, addedHits, offset);
                                hitsToAdd.clear();

                                if (addedHits.size() >= requiredHits) {
                                    response.setHasMore(true);
                                    if (it.getSize() > 0) {
                                        int approxCount = ((int) it.getSize() * addedHits.size() / count);
                                        approxCount = (int) Math.ceil(MathUtils.round(approxCount,
                                                approxCount < 1000 ? -1 : (approxCount < 10000 ? -2 : -3),
                                                BigDecimal.ROUND_UP));
                                        response.setApproxCount(approxCount);
                                    }
                                    return response;
                                }
                            }
                        }
                    }
                } catch (ItemNotFoundException e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Found node is not visible or published: " + row.getPath(), e);
                    }
                } catch (PathNotFoundException e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Found node is not visible or published: " + row.getPath(), e);
                    }
                } catch (Exception e) {
                    logger.warn("Error resolving search hit", e);
                }
            }
            if (hitsToAdd.size() > 0) {
                SearchServiceImpl.executeURLModificationRules(hitsToAdd, context);
                addHitsToResults(hitsToAdd, results, addedHits, offset);
            }
        }
    } catch (RepositoryException e) {
        if (e.getMessage() != null && e.getMessage().contains(ParseException.class.getName())) {
            logger.warn(e.getMessage());
            if (logger.isDebugEnabled()) {
                logger.debug(e.getMessage(), e);
            }
        } else {
            logger.error("Error while trying to perform a search", e);
        }
    } catch (Exception e) {
        logger.error("Error while trying to perform a search", e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Search query has {} results", results.size());
    }
    return response;
}

From source file:org.netxilia.functions.MathFunctions.java

/**
 * Rounds the given number to a certain number of decimal places according to valid mathematical criteria. Count
 * (optional) is the number of the places to which the value is to be rounded. If the count parameter is negative,
 * only the whole number portion is rounded. It is rounded to the place indicated by the count.
 * //from  w  w w  .ja  va2 s  .co  m
 * @param number
 * @return
 */
public double ROUND(double number, int count) {
    return MathUtils.round(number, count, BigDecimal.ROUND_FLOOR);
}

From source file:org.netxilia.functions.MathFunctions.java

public double ROUNDDOWN(double number, int count) {
    return MathUtils.round(number, count, BigDecimal.ROUND_DOWN);
}

From source file:org.netxilia.functions.MathFunctions.java

public double ROUNDUP(double number, int count) {
    return MathUtils.round(number, count, BigDecimal.ROUND_UP);
}

From source file:org.netxilia.functions.MathFunctions.java

public double TRUNC(double number, int count) {
    return MathUtils.round(number, count, BigDecimal.ROUND_DOWN);
}

From source file:org.skfiy.typhon.spi.atlasloot.SingleAtlasloot.java

@Override
void prepare() {
    p_prob = MathUtils.round((1 - getProb()) / factor, 3, BigDecimal.ROUND_UP);
}