Example usage for java.lang Double compare

List of usage examples for java.lang Double compare

Introduction

In this page you can find the example usage for java.lang Double compare.

Prototype

public static int compare(double d1, double d2) 

Source Link

Document

Compares the two specified double values.

Usage

From source file:org.esa.s1tbx.calibration.gpf.calibrators.ERSCalibrator.java

/**
 * Compute the UK-PAF ERS-1 antenna pattern (Appendix H) for given look angle.
 *
 * @param lookAngle The look angle (in degree)
 * @return The antenna pattern gain (in linear scale)
 */// w w w  .  ja  va2s. c om
private double ec(final double lookAngle) {

    final int numRows = appendixH.length;
    final int numCols = appendixH[0].length;
    if (numRows < 2 || numCols < 2) {
        throw new OperatorException("Not enough antenna pattern data");
    }

    final double boreSightAngle = lookAngle - relativeLookAngle;

    int row1 = 0;
    int row2 = 0;
    if (sceneCentreLatitude < appendixH[1][0]) {
        row1 = 1;
        row2 = 2;
    } else if (sceneCentreLatitude > appendixH[numRows - 1][0]) {
        row1 = numRows - 2;
        row2 = numRows - 1;
    } else {
        for (int i = 2; i < numRows; i++) {
            if (sceneCentreLatitude < appendixH[i][0]) {
                row1 = i - 1;
                row2 = i;
                break;
            }
        }
    }

    int col1 = 0;
    int col2 = 0;
    if (boreSightAngle < appendixH[0][1]) {
        col1 = 1;
        col2 = 2;
    } else if (boreSightAngle > appendixH[numCols - 1][0]) {
        col1 = numCols - 2;
        col2 = numCols - 1;
    } else {
        for (int j = 2; j < numCols; j++) {
            if (boreSightAngle < appendixH[0][j]) {
                col1 = j - 1;
                col2 = j;
                break;
            }
        }
    }

    final double lat1 = appendixH[row1][0];
    final double lat2 = appendixH[row2][0];
    final double delTheta1 = appendixH[0][col1];
    final double delTheta2 = appendixH[0][col2];
    if (Double.compare(lat1, lat2) == 0 || Double.compare(delTheta1, delTheta2) == 0) {
        throw new OperatorException("Incorrect latitude or look angle data");
    }

    final double gain11 = appendixH[row1][col1];
    final double gain12 = appendixH[row1][col2];
    final double gain21 = appendixH[row2][col1];
    final double gain22 = appendixH[row2][col2];
    final double lambda1 = (sceneCentreLatitude - lat1) / (lat2 - lat1);
    final double lambda2 = (boreSightAngle - delTheta1) / (delTheta2 - delTheta1);
    double gain = (1 - lambda2) * ((1 - lambda1) * gain11 + lambda1 * gain21)
            + lambda2 * ((1 - lambda1) * gain12 + lambda1 * gain22);
    gain = FastMath.pow(10, gain / 10); // dB to linear scale

    return gain;
}

From source file:org.openecomp.sdc.be.model.operations.impl.ArtifactOperation.java

@Override
public Either<ArtifactData, StorageOperationStatus> getLatestArtifactDataByArtifactUUID(String artifactUUID,
        boolean inTransaction) {
    Either<ArtifactData, StorageOperationStatus> result = null;
    try {//  w ww .j a v  a 2  s .c  om
        NodeTypeEnum nodeType = NodeTypeEnum.ArtifactRef;
        Map<String, Object> propertiesToMatch = new HashMap<>();
        propertiesToMatch.put(GraphPropertiesDictionary.ARTIFACT_UUID.getProperty(), artifactUUID);
        Either<List<ArtifactData>, TitanOperationStatus> getArtifactEither = titanGenericDao
                .getByCriteria(nodeType, propertiesToMatch, ArtifactData.class);
        if (getArtifactEither.isRight()) {
            log.debug("Couldn't fetch artifact data for artifact with uuid {}, error: {}", nodeType,
                    getArtifactEither.right().value());
            result = Either.right(
                    DaoStatusConverter.convertTitanStatusToStorageStatus(getArtifactEither.right().value()));
        } else {
            List<ArtifactData> artifacts = getArtifactEither.left().value();
            ArtifactData latestArtifact = artifacts.size() == 1 ? artifacts.get(0)
                    : artifacts.stream()
                            .max((a1, a2) -> Double.compare(
                                    Double.parseDouble(a1.getArtifactDataDefinition().getArtifactVersion()),
                                    Double.parseDouble(a2.getArtifactDataDefinition().getArtifactVersion())))
                            .get();
            result = Either.left(latestArtifact);
        }
        return result;
    } finally {
        if (!inTransaction) {
            if (result == null || result.isRight()) {
                this.titanGenericDao.rollback();
            } else {
                this.titanGenericDao.commit();
            }
        }
    }
}

From source file:com.net2plan.libraries.GraphUtils.java

/** Returns the K minimum cost service chains between two nodes (summing costs of links and resources traversed), traversing a given set of resource types, satisfying some user-defined constraints.
 * If only <i>n</i> shortest path are found (n&lt;K), those are returned. If none is found an empty list is returned. 
 * The subpaths (the set of links between two resources, or the first(last) resource and the origin (destination) node, are constrained to be loopless 
 * (the algorithm uses Yen's scheme for subpaths enumeration).
 * @param links The set of links which can be used for the chain
 * @param originNode The origin node of the chain
 * @param destinationNode The destination node of the chain (could be the same as the origin node)
 * @param sequenceOfResourceTypesToTraverse the types of the sequence of resources to traverse
 * @param linkCost the cost of each link (if null, all links have cost one), all numbers must be strictly positive
 * @param resourceCost a map with the cost of each resource (if null, all resources have cost zero). A resources with Double.MAX_VALUE cost cannot be traversed (as if it was not there). All costs must be nonnegative. If a resource is not present in the map, its cost is zero.  
 * @param K The maximum number of service chains to return (less than K may be returned if there are no different paths).
 * @param maxCostServiceChain Service chains with a cost higher than this are not enumerated
 * @param maxLengthInKmPerSubpath The maximum length in km in each subpath. Service chains not satisfying this are not enumerated
 * @param maxNumHopsPerSubpath The maximum number of traversed links in each subpath. Service chains not satisfying this are not enumerated
 * @param maxPropDelayInMsPerSubpath The propagation delay summing the links in each subpath. Service chains not satisfying this are not enumerated
 * @param cacheSubpathLists A map which associated to node pairs, the k-shortest paths (only considering links) already computed to be used. 
 * The algorithm will add new entries here for those pairs of nodes for which no per-computed values exist, and that are needed in the algorithm 
 * (e.g. for origin node to all nodes of the first resource type, nodes of the first resource type to the second...). If null, then no entries are 
 * precomputed AND also no new entries are returned.   
 * @return the (at most) K minimum cost service chains.
 *//*from   w ww .  j  a v a  2 s.  c o m*/
public static List<Pair<List<NetworkElement>, Double>> getKMinimumCostServiceChains(List<Link> links,
        Node originNode, Node destinationNode, List<String> sequenceOfResourceTypesToTraverse,
        DoubleMatrix1D linkCost, Map<Resource, Double> resourceCost, int K, double maxCostServiceChain,
        double maxLengthInKmPerSubpath, int maxNumHopsPerSubpath, double maxPropDelayInMsPerSubpath,
        Map<Pair<Node, Node>, List<Pair<List<Link>, Double>>> cacheSubpathLists) {
    if (maxLengthInKmPerSubpath <= 0)
        maxLengthInKmPerSubpath = Double.MAX_VALUE;
    if (maxNumHopsPerSubpath <= 0)
        maxNumHopsPerSubpath = Integer.MAX_VALUE;
    if (maxPropDelayInMsPerSubpath <= 0)
        maxPropDelayInMsPerSubpath = Double.MAX_VALUE;
    if (maxCostServiceChain < 0)
        maxCostServiceChain = Double.MAX_VALUE;
    final int E = links.size();
    if (E == 0)
        return new LinkedList<Pair<List<NetworkElement>, Double>>();
    final NetPlan netPlan = links.get(0).getNetPlan();
    if (linkCost == null)
        linkCost = DoubleFactory1D.dense.make(E, 1.0);
    if (linkCost.size() != E)
        throw new Net2PlanException("Wrong size of cost array");
    if (linkCost.getMinLocation()[0] <= 0)
        throw new Net2PlanException("All link costs must be strictly positive");
    if (resourceCost != null)
        for (Double val : resourceCost.values())
            if (val < 0)
                throw new Net2PlanException("All resource costs must be non-negative");

    /* initialize the link cost map */
    Map<Link, Double> linkCostMap = new HashMap<Link, Double>();
    for (int cont = 0; cont < E; cont++)
        linkCostMap.put(links.get(cont), linkCost.get(cont));

    /* initialize the nodes per phase. One element per resource type to traverse, plus one for the last node  */
    List<Set<Node>> nodesPerPhase = new ArrayList<Set<Node>>();
    for (String resourceType : sequenceOfResourceTypesToTraverse) {
        Set<Resource> resourcesNotInfiniteCostThisType = netPlan.getResources(resourceType);
        if (resourceCost != null)
            resourcesNotInfiniteCostThisType.removeIf(e -> resourceCost.get(e) == Double.MAX_VALUE);
        if (resourcesNotInfiniteCostThisType.isEmpty())
            return new LinkedList<Pair<List<NetworkElement>, Double>>();
        final Set<Node> nodesWithResourcesNotInfiniteCostThisType = resourcesNotInfiniteCostThisType.stream()
                .map(e -> e.getHostNode()).collect(Collectors.toCollection(HashSet::new));
        nodesPerPhase.add(nodesWithResourcesNotInfiniteCostThisType);
    }
    nodesPerPhase.add(Collections.singleton(destinationNode));

    /* initialize the path lists. This includes (n,n) pairs with one path of empty seq links and zero cost */
    if (cacheSubpathLists == null)
        cacheSubpathLists = new HashMap<Pair<Node, Node>, List<Pair<List<Link>, Double>>>();
    for (int contPhase = 0; contPhase < nodesPerPhase.size(); contPhase++) {
        final Set<Node> outputNodes = nodesPerPhase.get(contPhase);
        final Set<Node> inputNodes = contPhase == 0 ? Collections.singleton(originNode)
                : nodesPerPhase.get(contPhase - 1);
        for (Node nIn : inputNodes)
            for (Node nOut : outputNodes)
                if (!cacheSubpathLists.containsKey(Pair.of(nIn, nOut)))
                    if (nIn != nOut) {
                        List<List<Link>> kPaths = getKLooplessShortestPaths(netPlan.getNodes(), links, nIn,
                                nOut, linkCostMap, K, maxLengthInKmPerSubpath, maxNumHopsPerSubpath,
                                maxPropDelayInMsPerSubpath, -1, -1, -1);
                        List<Pair<List<Link>, Double>> pathsInfo = new ArrayList<Pair<List<Link>, Double>>();
                        double previousCost = 0;
                        for (List<Link> path : kPaths) {
                            final double thisCost = path.stream().mapToDouble(e -> linkCostMap.get(e)).sum();
                            if (previousCost > thisCost + 0.001)
                                throw new RuntimeException(
                                        "thisCost: " + thisCost + ", previousCost: " + previousCost + ", Bad");
                            if (thisCost > maxCostServiceChain)
                                break; // the maximum cost is exceeded, do not add this as subpath
                            pathsInfo.add(Pair.of(path, thisCost));
                            previousCost = thisCost;
                        }
                        cacheSubpathLists.put(Pair.of(nIn, nOut), pathsInfo);
                    } else
                        cacheSubpathLists.put(Pair.of(nIn, nIn),
                                Collections.singletonList(Pair.of(new LinkedList<Link>(), 0.0)));
    }

    /* Start the main loop */

    /* Initialize the SCs per out node, with those from origin node, to each node with resources of the first type (or end node if this is not a SC) */
    Map<Node, List<Pair<List<NetworkElement>, Double>>> outNodeToKSCsMap = new HashMap<Node, List<Pair<List<NetworkElement>, Double>>>();
    for (Node outNode : nodesPerPhase.get(0)) {
        List<Pair<List<NetworkElement>, Double>> thisFirstStageNodeSCs = new ArrayList<Pair<List<NetworkElement>, Double>>();
        for (Pair<List<Link>, Double> path : cacheSubpathLists.get(Pair.of(originNode, outNode)))
            if (path.getSecond() <= maxCostServiceChain)
                thisFirstStageNodeSCs
                        .add(Pair.of(new LinkedList<NetworkElement>(path.getFirst()), path.getSecond()));
        outNodeToKSCsMap.put(outNode, thisFirstStageNodeSCs);
    }

    final Comparator<Pair<List<NetworkElement>, Double>> scComparator = new Comparator<Pair<List<NetworkElement>, Double>>() {
        public int compare(Pair<List<NetworkElement>, Double> t1, Pair<List<NetworkElement>, Double> t2) {
            return Double.compare(t1.getSecond(), t2.getSecond());
        }
    };

    for (int nextPhase = 1; nextPhase < nodesPerPhase.size(); nextPhase++) {
        final Set<Node> thisPhaseNodes = nodesPerPhase.get(nextPhase - 1);
        final Set<Node> nextPhaseNodes = nodesPerPhase.get(nextPhase);
        final String intermediateNodeResourceType = sequenceOfResourceTypesToTraverse.get(nextPhase - 1);
        Map<Node, List<Pair<List<NetworkElement>, Double>>> new_outNodeToKSCsMap = new HashMap<Node, List<Pair<List<NetworkElement>, Double>>>();
        for (Node newOutNode : nextPhaseNodes) {
            List<Pair<List<NetworkElement>, Double>> kSCsToThisOutNode = new ArrayList<Pair<List<NetworkElement>, Double>>();
            for (Node intermediateNode : thisPhaseNodes) {
                for (Pair<List<NetworkElement>, Double> scOriginToIntermediateInfo : outNodeToKSCsMap
                        .get(intermediateNode)) {
                    final List<NetworkElement> scOriginToIntermediate = scOriginToIntermediateInfo.getFirst();
                    final double scOriginToIntermediateCost = scOriginToIntermediateInfo.getSecond();
                    for (Pair<List<Link>, Double> scIntermediateToOutInfo : cacheSubpathLists
                            .get(Pair.of(intermediateNode, newOutNode))) {
                        final List<NetworkElement> scIntermediateToOut = (List<NetworkElement>) (List<?>) scIntermediateToOutInfo
                                .getFirst();
                        final double scIntermediateToOutCost = scIntermediateToOutInfo.getSecond();
                        if (scOriginToIntermediateCost + scIntermediateToOutCost > maxCostServiceChain)
                            break; // do not add this SC, and no more interm->out paths: all are worse
                        if (kSCsToThisOutNode.size() == K)
                            if (kSCsToThisOutNode.get(K - 1).getSecond() <= scOriginToIntermediateCost
                                    + scIntermediateToOutCost)
                                break; // do not add this SC (already full), and no more interm->out paths: all are worse
                        /* Add as many concatenated SCs as resources here, but do not exceed maximum size k of total list. Resource costs may not be ordered  */
                        for (Resource intermediateResource : intermediateNode
                                .getResources(intermediateNodeResourceType)) {
                            final Double intermediateResourceCost = resourceCost == null ? 0.0
                                    : resourceCost.get(intermediateResource);
                            if (intermediateResourceCost == Double.MAX_VALUE)
                                continue; // resources with infinite cost cannot be used
                            final double totalSCCost = scOriginToIntermediateCost + scIntermediateToOutCost
                                    + ((intermediateResourceCost == null) ? 0.0 : intermediateResourceCost);
                            if (totalSCCost > maxCostServiceChain)
                                continue; // do not add this, but maybe other resources later are cheaper
                            if ((kSCsToThisOutNode.size() == K)
                                    && (totalSCCost > kSCsToThisOutNode.get(K - 1).getSecond()))
                                continue; // do not add this, but maybe other resources later are cheaper 
                            /* Add this SC */
                            List<NetworkElement> newSC = new LinkedList<NetworkElement>(scOriginToIntermediate);
                            newSC.add(intermediateResource);
                            newSC.addAll(scIntermediateToOut);
                            kSCsToThisOutNode
                                    .add(Pair.of(newSC, scOriginToIntermediateCost + scIntermediateToOutCost));
                            /* One SC was added, sort again, and remove the last SCs (higher cost), keep up to K */
                            Collections.sort(kSCsToThisOutNode, scComparator);
                            if (kSCsToThisOutNode.size() > K)
                                kSCsToThisOutNode = kSCsToThisOutNode.subList(0, K);
                        }
                    }
                }
            }
            new_outNodeToKSCsMap.put(newOutNode, kSCsToThisOutNode);
        }
        outNodeToKSCsMap = new_outNodeToKSCsMap;
    }
    if (!outNodeToKSCsMap.keySet().equals(Collections.singleton(destinationNode)))
        throw new RuntimeException("Bad");
    return outNodeToKSCsMap.get(destinationNode);
}

From source file:org.chromium.chrome.browser.payments.PaymentRequestImpl.java

/**
 * Compares two payment instruments by frecency.
 * Return negative value if a has strictly lower frecency score than b.
 * Return zero if a and b have the same frecency score.
 * Return positive value if a has strictly higher frecency score than b.
 *//*  w w w. j a v a  2  s.  co m*/
private static int compareInstrumentsByFrecency(PaymentInstrument a, PaymentInstrument b) {
    int aCount = PaymentPreferencesUtil.getPaymentInstrumentUseCount(a.getIdentifier());
    int bCount = PaymentPreferencesUtil.getPaymentInstrumentUseCount(b.getIdentifier());
    long aDate = PaymentPreferencesUtil.getPaymentInstrumentLastUseDate(a.getIdentifier());
    long bDate = PaymentPreferencesUtil.getPaymentInstrumentLastUseDate(a.getIdentifier());

    return Double.compare(getFrecencyScore(aCount, aDate), getFrecencyScore(bCount, bDate));
}

From source file:org.unitime.timetable.solver.course.ui.ClassInfoModel.java

public String getRoomTable() {
    try {//from   w  ww . j a  va2s  .  c  o m
        Vector<ClassRoomInfo> rooms = getRooms();
        ClassAssignment ClassAssignment = (iChange == null ? null : iChange.getCurrent(iClass));
        Collection<ClassRoomInfo> assigned = (ClassAssignment != null ? ClassAssignment.getRooms()
                : isClassAssigned() ? getClassAssignment().getRooms() : null);
        Collection<ClassRoomInfo> original = (getClassOldAssignment() != null
                ? getClassOldAssignment().getRooms()
                : null);
        if (rooms == null || rooms.isEmpty())
            return "";
        Collections.sort(rooms, new Comparator<ClassRoomInfo>() {
            public int compare(ClassRoomInfo r1, ClassRoomInfo r2) {
                int cmp = 0;
                if (ClassInfoForm.sRoomOrdNameAsc.equals(iForm.getRoomOrder())) {
                    cmp = r1.getName().compareTo(r2.getName());
                } else if (ClassInfoForm.sRoomOrdNameDesc.equals(iForm.getRoomOrder())) {
                    cmp = -r1.getName().compareTo(r2.getName());
                } else if (ClassInfoForm.sRoomOrdSizeAsc.equals(iForm.getRoomOrder())) {
                    cmp = Double.compare(r1.getCapacity(), r2.getCapacity());
                } else if (ClassInfoForm.sRoomOrdSizeDesc.equals(iForm.getRoomOrder())) {
                    cmp = -Double.compare(r1.getCapacity(), r2.getCapacity());
                } else {
                    cmp = r1.getName().compareTo(r2.getName());
                }
                if (cmp != 0)
                    return cmp;
                cmp = r1.getName().compareTo(r2.getName());
                ;
                if (cmp != 0)
                    return cmp;
                return r1.getLocationId().compareTo(r2.getLocationId());
            }
        });
        String ret = "";
        ret += "<script language='javascript'>";
        ret += "function roomOver(source, id) { ";
        ret += "    document.getElementById('r'+id).style.backgroundColor='rgb(223,231,242)';";
        ret += "    document.getElementById('c'+id).style.backgroundColor='rgb(223,231,242)';";
        ret += "    source.style.cursor='hand';source.style.cursor='pointer';";
        ret += "}";
        ret += "var sCap = -1;";
        ret += "var sRooms = '";
        if (assigned != null && assigned.size() > 0) {
            for (ClassRoomInfo room : assigned) {
                ret += ":" + room.getLocationId() + "@" + room.getCapacity();
            }
        }
        ret += "';";
        ret += "var sNrRooms = " + (assigned != null ? assigned.size() : 0) + ";";
        ret += "function roomSelected(id) {";
        ret += "    return sRooms.indexOf(':'+id+'@')>=0;";
        ret += "}";
        ret += "function roomOut(id) { ";
        ret += "    var bg = 'transparent';";
        ret += "    if (roomSelected(id)) bg='rgb(168,187,225)';";
        ret += "    document.getElementById('r'+id).style.backgroundColor=bg;";
        ret += "    document.getElementById('c'+id).style.backgroundColor=bg;";
        ret += "}";
        ret += "function roomClick(source, id, cap) { ";
        ret += "    if (sCap<0) {";
        ret += "        sCap = 0; sRooms=''; sNrRooms=0;";
        if (assigned != null && assigned.size() > 0) {
            for (ClassRoomInfo room : assigned)
                ret += "        roomOut(" + room.getLocationId() + ");";
        }
        ret += "    }";
        ret += "    var i = sRooms.indexOf(':'+id+'@');";
        ret += "    if (i>=0) {";
        ret += "        var j = sRooms.indexOf(':',i+1);";
        ret += "        sRooms = sRooms.substring(0, i)+(j>=0?sRooms.substring(j):'');";
        ret += "        sCap -= cap; sNrRooms--;";
        ret += "    } else {";
        ret += "        sRooms = sRooms + ':' + id + '@' + cap;";
        ret += "        sCap += cap; sNrRooms++;";
        ret += "        if (sNrRooms>" + getClazz().getNumberOfRooms() + ") {";
        ret += "            var fid = sRooms.substring(1, sRooms.indexOf('@'));";
        ret += "            var fcap = sRooms.substring(sRooms.indexOf('@')+1, sRooms.indexOf(':',1));";
        ret += "            sRooms = sRooms.substring(sRooms.indexOf(':',1));";
        ret += "            sCap -= fcap; sNrRooms--; roomOut(fid);";
        ret += "        };";
        ret += "    }";
        ret += "    roomOut(id);";
        ret += "    if (sNrRooms==" + getClazz().getNumberOfRooms()
                + ") {displayLoading(); document.location='classInfo.do?op=Select&room='+sRooms+'&noCacheTS="
                + new Date().getTime() + "';}";
        ret += "    var c = document.getElementById('roomCapacityCounter');";
        ret += "    if (c!=null) c.innerHTML = (sCap<" + getClazz().getClassLimit()
                + "?'<font color=\"red\">'+sCap+'</font>':''+sCap);";
        ret += "}";
        ret += "</script>";
        ret += "<table border='0' cellspacing='0' cellpadding='3'>";
        int idx = 0;
        int step = 6;
        for (ClassRoomInfo room : rooms) {
            if ((idx % step) == 0) {
                if (idx > 0)
                    ret += "</tr>";
                ret += "<tr>";
            }
            String style = "";
            if (assigned != null && assigned.contains(room))
                style += "background-color:rgb(168,187,225);";
            if (original != null && original.contains(room))
                style += "text-decoration:underline;";
            String mouse = "onMouseOver=\"roomOver(this," + room.getLocationId() + ");\" "
                    + "onMouseOut=\"roomOut(" + room.getLocationId() + ");\" " + "onClick=\"roomClick(this,"
                    + room.getLocationId() + "," + room.getCapacity() + ");\"";
            ret += "<td nowrap id='r" + room.getLocationId() + "' "
                    + (style.length() > 0 ? "style='" + style + "' " : "") + mouse + ">" + room.toString()
                    + "</td>";
            if ((idx % step) < step - 1)
                style += "border-right: #646464 1px dashed;";
            ret += "<td id='c" + room.getLocationId() + "' "
                    + (style.length() > 0 ? "style='" + style + "' " : "") + mouse + ">" + room.getCapacity()
                    + "</td>";
            idx++;
        }
        while ((idx % step) != 0) {
            ret += "<td colspan='2'>&nbsp;</td>";
            idx++;
        }
        ret += "</tr>";
        ret += "</table>";
        return ret;
    } catch (Exception e) {
        iForm.setMessage(e.getMessage());
        sLog.error(e.getMessage(), e);
        return "";
    }
}

From source file:ml.shifu.shifu.core.processor.TrainModelProcessor.java

private List<Integer> getSubsamplingFeatures(List<Integer> allFeatures,
        FeatureSubsetStrategy featureSubsetStrategy, double featureSubsetRate, int inputNum) {
    if (featureSubsetStrategy == null) {
        if (Double.compare(1d, featureSubsetRate) == 0) {
            return new ArrayList<Integer>();
        } else {/*ww w.  j a  va  2s. c o  m*/
            return sampleFeaturesForNodeStats(allFeatures, (int) (allFeatures.size() * featureSubsetRate));
        }
    } else {
        switch (featureSubsetStrategy) {
        case HALF:
            return sampleFeaturesForNodeStats(allFeatures, allFeatures.size() / 2);
        case ONETHIRD:
            return sampleFeaturesForNodeStats(allFeatures, allFeatures.size() / 3);
        case TWOTHIRDS:
            return sampleFeaturesForNodeStats(allFeatures, allFeatures.size() * 2 / 3);
        case SQRT:
            return sampleFeaturesForNodeStats(allFeatures,
                    (int) (allFeatures.size() * Math.sqrt(inputNum) / inputNum));
        case LOG2:
            return sampleFeaturesForNodeStats(allFeatures,
                    (int) (allFeatures.size() * Math.log(inputNum) / Math.log(2) / inputNum));
        case AUTO:
        case ALL:
        default:
            return new ArrayList<Integer>();
        }
    }
}

From source file:org.apache.carbondata.core.scan.filter.FilterUtil.java

public static int compareFilterKeyBasedOnDataType(String dictionaryVal, String memberVal, DataType dataType) {
    try {/* ww  w.ja  v a  2 s.  c o  m*/
        if (dataType == DataTypes.BOOLEAN) {
            return Boolean.compare((Boolean.parseBoolean(dictionaryVal)), (Boolean.parseBoolean(memberVal)));
        } else if (dataType == DataTypes.SHORT) {
            return Short.compare((Short.parseShort(dictionaryVal)), (Short.parseShort(memberVal)));
        } else if (dataType == DataTypes.INT) {
            return Integer.compare((Integer.parseInt(dictionaryVal)), (Integer.parseInt(memberVal)));
        } else if (dataType == DataTypes.DOUBLE) {
            return Double.compare((Double.parseDouble(dictionaryVal)), (Double.parseDouble(memberVal)));
        } else if (dataType == DataTypes.LONG) {
            return Long.compare((Long.parseLong(dictionaryVal)), (Long.parseLong(memberVal)));
        } else if (dataType == DataTypes.BOOLEAN) {
            return Boolean.compare((Boolean.parseBoolean(dictionaryVal)), (Boolean.parseBoolean(memberVal)));
        } else if (dataType == DataTypes.DATE || dataType == DataTypes.TIMESTAMP) {
            String format = CarbonUtil.getFormatFromProperty(dataType);
            SimpleDateFormat parser = new SimpleDateFormat(format);
            Date dateToStr;
            Date dictionaryDate;
            dateToStr = parser.parse(memberVal);
            dictionaryDate = parser.parse(dictionaryVal);
            return dictionaryDate.compareTo(dateToStr);
        } else if (DataTypes.isDecimal(dataType)) {
            java.math.BigDecimal javaDecValForDictVal = new java.math.BigDecimal(dictionaryVal);
            java.math.BigDecimal javaDecValForMemberVal = new java.math.BigDecimal(memberVal);
            return javaDecValForDictVal.compareTo(javaDecValForMemberVal);
        } else {
            return -1;
        }
    } catch (ParseException | NumberFormatException e) {
        return -1;
    }
}

From source file:netdecoder.NetDecoder.java

public void DFNAnalysis(List<String> controlPaths, List<String> diseasePaths) throws IOException {

    List<Path> diseaseSpecPaths = NetDecoderUtils.getPhenotypeSpecificPaths(diseasePaths, controlPaths);
    List<Path> controlSpecPaths = NetDecoderUtils.getPhenotypeSpecificPaths(controlPaths, diseasePaths);

    System.out.println(diseaseSpecPaths.size());
    System.out.println(diseasePaths.size());
    System.out.println(controlSpecPaths.size());
    System.out.println(controlPaths.size());
    List<String> sDiseasePaths = NetDecoderUtils.transformPaths2String(diseaseSpecPaths);
    List<String> sControlPaths = NetDecoderUtils.transformPaths2String(controlSpecPaths);

    Map<String, Node> diseaseNetwork = NetDecoderUtils.createNetworkFromPaths(sDiseasePaths);
    Map<String, Node> controlNetwork = NetDecoderUtils.createNetworkFromPaths(sControlPaths);
    System.out.println(diseaseNetwork.size());
    System.out.println(controlNetwork.size());
    Set<String> genesDisease = new LinkedHashSet(diseaseNetwork.keySet());
    Set<String> genesControl = new LinkedHashSet(controlNetwork.keySet());
    genesDisease.removeAll(controlNetwork.keySet());
    genesControl.removeAll(diseaseNetwork.keySet());
    System.out.println("GENES: " + genesDisease.size());
    System.out.println("GENES: " + genesControl.size());

    Collections.sort(diseaseSpecPaths, (Path p1, Path p2) -> Double.compare(p1.flow, p2.flow));
    Collections.sort(controlSpecPaths, (Path p1, Path p2) -> Double.compare(p1.flow, p2.flow));

    //NetDecoderUtils.savePaths(diseasePaths, dir+filename+"_DFN_paths_disease.txt");
    //NetDecoderUtils.savePaths(controlPaths, dir+filename+"_DFN_paths_control.txt");
    NetDecoderUtils.savePaths(diseaseSpecPaths, "TEST_DFN_paths_disease.txt");
    NetDecoderUtils.savePaths(controlSpecPaths, "TEST_DFN_paths_control.txt");
}

From source file:com.mesosphere.dcos.cassandra.common.config.CassandraApplicationConfig.java

@Override
public boolean equals(Object o) {
    if (this == o)
        return true;
    if (!(o instanceof CassandraApplicationConfig))
        return false;
    CassandraApplicationConfig that = (CassandraApplicationConfig) o;
    return isHintedHandoffEnabled() == that.isHintedHandoffEnabled()
            && getMaxHintWindowInMs() == that.getMaxHintWindowInMs()
            && getHintedHandoffThrottleInKb() == that.getHintedHandoffThrottleInKb()
            && getMaxHintsDeliveryThreads() == that.getMaxHintsDeliveryThreads()
            && getBatchlogReplayThrottleInKb() == that.getBatchlogReplayThrottleInKb()
            && getRolesValidityInMs() == that.getRolesValidityInMs()
            && getPermissionsValidityInMs() == that.getPermissionsValidityInMs()
            && getKeyCacheSavePeriod() == that.getKeyCacheSavePeriod()
            && getRowCacheSizeInMb() == that.getRowCacheSizeInMb()
            && getRowCacheSavePeriod() == that.getRowCacheSavePeriod()
            && getCounterCacheSavePeriod() == that.getCounterCacheSavePeriod()
            && getCommitlogSyncPeriodInMs() == that.getCommitlogSyncPeriodInMs()
            && getCommitlogSegmentSizeInMb() == that.getCommitlogSegmentSizeInMb()
            && getConcurrentReads() == that.getConcurrentReads()
            && getConcurrentWrites() == that.getConcurrentWrites()
            && getConcurrentCounterWrites() == that.getConcurrentCounterWrites()
            && getIndexSummaryResizeIntervalInMinutes() == that.getIndexSummaryResizeIntervalInMinutes()
            && isTrickleFsync() == that.isTrickleFsync()
            && getTrickleFsyncIntervalInKb() == that.getTrickleFsyncIntervalInKb()
            && getStoragePort() == that.getStoragePort() && getSslStoragePort() == that.getSslStoragePort()
            && isStartNativeTransport() == that.isStartNativeTransport()
            && getNativeTransportPort() == that.getNativeTransportPort() && isStartRpc() == that.isStartRpc()
            && getRpcPort() == that.getRpcPort() && isRpcKeepalive() == that.isRpcKeepalive()
            && getThriftFramedTransportSizeInMb() == that.getThriftFramedTransportSizeInMb()
            && isIncrementalBackups() == that.isIncrementalBackups()
            && isSnapshotBeforeCompaction() == that.isSnapshotBeforeCompaction()
            && isAutoSnapshot() == that.isAutoSnapshot()
            && getTombstoneWarnThreshold() == that.getTombstoneWarnThreshold()
            && getTombstoneFailureThreshold() == that.getTombstoneFailureThreshold()
            && getColumnIndexSizeInKb() == that.getColumnIndexSizeInKb()
            && getBatchSizeWarnThresholdInKb() == that.getBatchSizeWarnThresholdInKb()
            && getBatchSizeFailThresholdInKb() == that.getBatchSizeFailThresholdInKb()
            && getCompactionThroughputMbPerSec() == that.getCompactionThroughputMbPerSec()
            && getCompactionLargePartitionWarningThresholdMb() == that
                    .getCompactionLargePartitionWarningThresholdMb()
            && getSstablePreemptiveOpenIntervalInMb() == that.getSstablePreemptiveOpenIntervalInMb()
            && getReadRequestTimeoutInMs() == that.getReadRequestTimeoutInMs()
            && getRangeRequestTimeoutInMs() == that.getRangeRequestTimeoutInMs()
            && getWriteRequestTimeoutInMs() == that.getWriteRequestTimeoutInMs()
            && getCounterWriteRequestTimeoutInMs() == that.getCounterWriteRequestTimeoutInMs()
            && getCasContentionTimeoutInMs() == that.getCasContentionTimeoutInMs()
            && getTruncateRequestTimeoutInMs() == that.getTruncateRequestTimeoutInMs()
            && getRequestTimeoutInMs() == that.getRequestTimeoutInMs()
            && isCrossNodeTimeout() == that.isCrossNodeTimeout()
            && getDynamicSnitchUpdateIntervalInMs() == that.getDynamicSnitchUpdateIntervalInMs()
            && getDynamicSnitchResetIntervalInMs() == that.getDynamicSnitchResetIntervalInMs()
            && Double.compare(that.getDynamicSnitchBadnessThreshold(), getDynamicSnitchBadnessThreshold()) == 0
            && isInterDcTcpNodelay() == that.isInterDcTcpNodelay()
            && getTracetypeQueryTtl() == that.getTracetypeQueryTtl()
            && getTracetypeRepairTtl() == that.getTracetypeRepairTtl()
            && isEnableUserDefinedFunctions() == that.isEnableUserDefinedFunctions()
            && getWindowsTimerInterval() == that.getWindowsTimerInterval()
            && getRolesUpdateIntervalInMs() == that.getRolesUpdateIntervalInMs()
            && getPermissionsUpdateIntervalInMs() == that.getPermissionsUpdateIntervalInMs()
            && getKeyCacheKeysToSave() == that.getKeyCacheKeysToSave()
            && getRowCacheKeysToSave() == that.getRowCacheKeysToSave()
            && getCounterCacheKeysToSave() == that.getCounterCacheKeysToSave()
            && getFileCacheSizeInMb() == that.getFileCacheSizeInMb()
            && getMemtableHeapSpaceInMb() == that.getMemtableHeapSpaceInMb()
            && getMemtableOffheapSpaceInMb() == that.getMemtableOffheapSpaceInMb()
            && getMetableCleanupThreshold() == that.getMetableCleanupThreshold()
            && getCommitlogTotalSpaceInMb() == that.getCommitlogTotalSpaceInMb()
            && getMemtableFlushWritersKey() == that.getMemtableFlushWritersKey()
            && getListenOnBroadcastAddress() == that.getListenOnBroadcastAddress()
            && getNativeTransportMaxThreads() == that.getNativeTransportMaxThreads()
            && getNativeTransportMaxFrameSizeInMb() == that.getNativeTransportMaxFrameSizeInMb()
            && getNativeTransportMaxConcurrentConnections() == that.getNativeTransportMaxConcurrentConnections()
            && getNativeTransportMaxConcurrentConnectionsPerIpKey() == that
                    .getNativeTransportMaxConcurrentConnectionsPerIpKey()
            && getRpcMinThreads() == that.getRpcMinThreads() && getRpcMaxThreads() == that.getRpcMaxThreads()
            && getRpcSendBuffSizeInBytes() == that.getRpcSendBuffSizeInBytes()
            && getRpcRecvBuffSizeInBytes() == that.getRpcRecvBuffSizeInBytes()
            && getConcurrentCompactors() == that.getConcurrentCompactors()
            && getStreamThroughputOutboundMegabitsPerSec() == that.getStreamThroughputOutboundMegabitsPerSec()
            && getInterDcStreamThroughputOutboundMegabitsPerSec() == that
                    .getInterDcStreamThroughputOutboundMegabitsPerSec()
            && getStreamingSocketTimeoutInMs() == that.getStreamingSocketTimeoutInMs()
            && getPhiConvictThreshold() == that.getPhiConvictThreshold()
            && getGcWarnThresholdInMs() == that.getGcWarnThresholdInMs()
            && getBufferPoolUseHeapIfExhausted() == that.getBufferPoolUseHeapIfExhausted()
            && getUnloggedBatchAcrossPartitionsWarnThreshold() == that
                    .getUnloggedBatchAcrossPartitionsWarnThreshold()
            && getEnableScriptedUserDefinedFunctions() == that.getEnableScriptedUserDefinedFunctions()
            && getMaxValueSizeInMb() == that.getMaxValueSizeInMb()
            && Objects.equals(getInternodeAuthenticator(), that.getInternodeAuthenticator())
            && Objects.equals(getDiskOptimizationStrategy(), that.getDiskOptimizationStrategy())
            && Objects.equals(getClusterName(), that.getClusterName())
            && Objects.equals(getAuthenticator(), that.getAuthenticator())
            && Objects.equals(getAuthorizer(), that.getAuthorizer())
            && Objects.equals(getRoleManager(), that.getRoleManager())
            && Objects.equals(getPartitioner(), that.getPartitioner())
            && Objects.equals(getDiskFailurePolicy(), that.getDiskFailurePolicy())
            && Objects.equals(getCommitFailurePolicy(), that.getCommitFailurePolicy())
            && Objects.equals(getKeyCacheSizeInMb(), that.getKeyCacheSizeInMb())
            && Objects.equals(getCounterCacheSizeInMb(), that.getCounterCacheSizeInMb())
            && Objects.equals(getCommitlogSync(), that.getCommitlogSync())
            && Objects.equals(getMemtableAllocationType(), that.getMemtableAllocationType())
            && Objects.equals(getIndexSummaryCapacityInMb(), that.getIndexSummaryCapacityInMb())
            && Objects.equals(getRpcServerType(), that.getRpcServerType())
            && Objects.equals(getEndpointSnitch(), that.getEndpointSnitch())
            && Objects.equals(getRequestScheduler(), that.getRequestScheduler())
            && Objects.equals(getInternodeCompression(), that.getInternodeCompression())
            && Objects.equals(getInternodeAuthenticator(), that.getInternodeAuthenticator())
            && Objects.equals(getMaxHintsFileSizeInMb(), that.getMaxHintsFileSizeInMb())
            && Objects.equals(getHintsFlushPeriodInMs(), that.getHintsFlushPeriodInMs())
            && Objects.equals(getConcurrentMaterializedViewWrites(), that.getConcurrentMaterializedViewWrites())
            && Objects.equals(getCommitlogTotalSpaceInMb(), that.getCommitlogTotalSpaceInMb());
}

From source file:org.sakaiproject.tool.messageforums.ui.MessageForumStatisticsBean.java

/**
 * Compares two statistics by grades.//from w  w  w  .  j  a  v a2  s .  c  om
 * Higher grades are greater than lower grades.
 * Stats with equal grades are compared by name
 * If one has a grade, and the other doesn't, treat having a grade as greater than not having a grade
 * If neither has a grade, compare by name
 */
private static int compareGradesFromStats(DecoratedCompiledMessageStatistics stat1,
        DecoratedCompiledMessageStatistics stat2) {
    Double grd1 = getGradeFromStat(stat1);
    Double grd2 = getGradeFromStat(stat2);
    // If they're both null, or an equal grade, revert to the name comparator
    if ((grd1 == null && grd2 == null) || (grd1 != null && grd1.equals(grd2))) {
        return nameComparatorAsc.compare(stat1, stat2);
    }
    boolean exists1 = grd1 != null;
    boolean exists2 = grd2 != null;
    if (exists1 && exists2) {
        // Both grades exist, compare them
        return Double.compare(grd1, grd2);
    }
    // One grade exists and the other doesn't, Boolean compare their existence
    return Boolean.compare(exists1, exists2);
}