Example usage for org.apache.commons.lang3 Range between

List of usage examples for org.apache.commons.lang3 Range between

Introduction

In this page you can find the example usage for org.apache.commons.lang3 Range between.

Prototype

public static <T extends Comparable<T>> Range<T> between(final T fromInclusive, final T toInclusive) 

Source Link

Document

Obtains a range with the specified minimum and maximum values (both inclusive).

The range uses the natural ordering of the elements to determine where values lie in the range.

The arguments may be passed in the order (min,max) or (max,min).

Usage

From source file:com.googlecode.jsendnsca.NagiosSettings.java

private static boolean validPortRange(int port) {
    return Range.between(MIN_PORT, MAX_PORT).contains(port);
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step6GraphTransitivityCleaner.java

public GraphCleaningResults processSingleFile(File file, File outputDir, String prefix,
        Boolean collectGeneratedArgumentPairs) throws Exception {
    GraphCleaningResults result = new GraphCleaningResults();

    File outFileTable = new File(outputDir, prefix + file.getName() + "_table.csv");
    File outFileInfo = new File(outputDir, prefix + file.getName() + "_info.txt");

    PrintStream psTable = new PrintStream(new FileOutputStream(outFileTable));
    PrintStream psInfo = new PrintStream(new FileOutputStream(outFileInfo));

    // load one topic/side
    List<AnnotatedArgumentPair> pairs = new ArrayList<>(
            (List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file));

    int fullDataSize = pairs.size();

    // filter out missing gold data
    Iterator<AnnotatedArgumentPair> iterator = pairs.iterator();
    while (iterator.hasNext()) {
        AnnotatedArgumentPair pair = iterator.next();
        if (pair.getGoldLabel() == null) {
            iterator.remove();/*from   w  w  w  .  j a v  a 2s. c om*/
        }
        // or we want to completely remove equal edges in advance!
        else if (this.removeEqualEdgesParam && "equal".equals(pair.getGoldLabel())) {
            iterator.remove();
        }
    }

    // sort pairs by their weight
    this.argumentPairListSorter.sortArgumentPairs(pairs);

    int preFilteredDataSize = pairs.size();

    // compute correlation between score threshold and number of removed edges
    double[] correlationEdgeWeights = new double[pairs.size()];
    double[] correlationRemovedEdges = new double[pairs.size()];

    // only cycles of length 0 to 5 are interesting (5+ are too big)
    Range<Integer> range = Range.between(0, 5);

    psTable.print(
            "EdgeWeightThreshold\tPairs\tignoredEdgesCount\tIsDAG\tTransitivityScoreMean\tTransitivityScoreMax\tTransitivityScoreSamples\tEdges\tNodes\t");
    for (int j = range.getMinimum(); j <= range.getMaximum(); j++) {
        psTable.print("Cycles_" + j + "\t");
    }
    psTable.println();

    // store the indices of all pairs (edges) that have been successfully added without
    // generating cycles
    TreeSet<Integer> addedPairsIndices = new TreeSet<>();

    // number of edges ignored as they generated cycles
    int ignoredEdgesCount = 0;

    Graph lastGraph = null;

    // flag that the first cycle was already processed
    boolean firstCycleAlreadyHit = false;

    for (int i = 1; i < pairs.size(); i++) {
        // now filter the finalArgumentPairList and add only pairs that have not generated cycles
        List<AnnotatedArgumentPair> subList = new ArrayList<>();

        for (Integer index : addedPairsIndices) {
            subList.add(pairs.get(index));
        }

        // and add the current at the end
        subList.add(pairs.get(i));

        // what is the current lowest value of a pair weight?
        double weakestEdgeWeight = computeEdgeWeight(subList.get(subList.size() - 1), LAMBDA_PENALTY);

        //            Graph graph = buildGraphFromArgumentPairs(finalArgumentPairList);
        int numberOfLoops;

        // map for storing cycles by their length
        TreeMap<Integer, TreeSet<String>> lengthCyclesMap = new TreeMap<>();

        Graph graph = buildGraphFromArgumentPairs(subList);

        lastGraph = graph;

        List<List<Object>> cyclesInGraph = findCyclesInGraph(graph);

        DescriptiveStatistics transitivityScore = new DescriptiveStatistics();

        if (cyclesInGraph.isEmpty()) {
            // we have DAG
            transitivityScore = computeTransitivityScores(graph);

            // update results
            result.maxTransitivityScore = (int) transitivityScore.getMax();
            result.avgTransitivityScore = transitivityScore.getMean();
        }

        numberOfLoops = cyclesInGraph.size();

        // initialize map
        for (int r = range.getMinimum(); r <= range.getMaximum(); r++) {
            lengthCyclesMap.put(r, new TreeSet<String>());
        }

        // we hit a loop
        if (numberOfLoops > 0) {
            // let's update the result

            if (!firstCycleAlreadyHit) {
                result.graphSizeEdgesBeforeFirstCycle = graph.getEdgeCount();
                result.graphSizeNodesBeforeFirstCycle = graph.getNodeCount();

                // find the shortest cycle
                int shortestCycleLength = Integer.MAX_VALUE;

                for (List<Object> cycle : cyclesInGraph) {
                    shortestCycleLength = Math.min(shortestCycleLength, cycle.size());
                }
                result.lengthOfFirstCircle = shortestCycleLength;

                result.pairsBeforeFirstCycle = i;

                firstCycleAlreadyHit = true;
            }

            // ignore this edge further
            ignoredEdgesCount++;

            // update counts of different cycles lengths
            for (List<Object> cycle : cyclesInGraph) {
                int currentSize = cycle.size();

                // convert to sorted set of nodes
                List<String> cycleAsSortedIDs = new ArrayList<>();
                for (Object o : cycle) {
                    cycleAsSortedIDs.add(o.toString());
                }
                Collections.sort(cycleAsSortedIDs);

                if (range.contains(currentSize)) {
                    lengthCyclesMap.get(currentSize).add(cycleAsSortedIDs.toString());
                }
            }
        } else {
            addedPairsIndices.add(i);
        }

        // we hit the first cycle

        // collect loop sizes
        StringBuilder loopsAsString = new StringBuilder();
        for (int j = range.getMinimum(); j <= range.getMaximum(); j++) {
            //                    loopsAsString.append(j).append(":");
            loopsAsString.append(lengthCyclesMap.get(j).size());
            loopsAsString.append("\t");
        }

        psTable.printf(Locale.ENGLISH, "%.4f\t%d\t%d\t%b\t%.2f\t%d\t%d\t%d\t%d\t%s%n", weakestEdgeWeight, i,
                ignoredEdgesCount, numberOfLoops == 0,
                Double.isNaN(transitivityScore.getMean()) ? 0d : transitivityScore.getMean(),
                (int) transitivityScore.getMax(), transitivityScore.getN(), graph.getEdgeCount(),
                graph.getNodeCount(), loopsAsString.toString().trim());

        // update result
        result.finalGraphSizeEdges = graph.getEdgeCount();
        result.finalGraphSizeNodes = graph.getNodeCount();
        result.ignoredEdgesThatBrokeDAG = ignoredEdgesCount;

        // update stats for correlation
        correlationEdgeWeights[i] = weakestEdgeWeight;
        //            correlationRemovedEdges[i] =  (double) ignoredEdgesCount;
        // let's try: if we keep = 0, if we remove = 1
        correlationRemovedEdges[i] = numberOfLoops == 0 ? 0.0 : 1.0;
    }

    psInfo.println("Original: " + fullDataSize + ", removed by MACE: " + (fullDataSize - preFilteredDataSize)
            + ", final: " + (preFilteredDataSize - ignoredEdgesCount) + " (removed: " + ignoredEdgesCount
            + ")");

    double[][] matrix = new double[correlationEdgeWeights.length][];
    for (int i = 0; i < correlationEdgeWeights.length; i++) {
        matrix[i] = new double[2];
        matrix[i][0] = correlationEdgeWeights[i];
        matrix[i][1] = correlationRemovedEdges[i];
    }

    PearsonsCorrelation pearsonsCorrelation = new PearsonsCorrelation(matrix);

    double pValue = pearsonsCorrelation.getCorrelationPValues().getEntry(0, 1);
    double correlation = pearsonsCorrelation.getCorrelationMatrix().getEntry(0, 1);

    psInfo.printf(Locale.ENGLISH, "Correlation: %.3f, p-Value: %.4f%n", correlation, pValue);
    if (lastGraph == null) {
        throw new IllegalStateException("Graph is null");
    }

    // close
    psInfo.close();
    psTable.close();

    // save filtered final gold data
    List<AnnotatedArgumentPair> finalArgumentPairList = new ArrayList<>();

    for (Integer index : addedPairsIndices) {
        finalArgumentPairList.add(pairs.get(index));
    }
    XStreamTools.toXML(finalArgumentPairList, new File(outputDir, prefix + file.getName()));

    // TODO: here, we can add newly generated edges from graph transitivity
    if (collectGeneratedArgumentPairs) {
        Set<GeneratedArgumentPair> generatedArgumentPairs = new HashSet<>();
        // collect all arguments
        Map<String, Argument> allArguments = new HashMap<>();
        for (ArgumentPair argumentPair : pairs) {
            allArguments.put(argumentPair.getArg1().getId(), argumentPair.getArg1());
            allArguments.put(argumentPair.getArg2().getId(), argumentPair.getArg2());
        }

        Graph finalGraph = buildGraphFromArgumentPairs(finalArgumentPairList);
        for (Edge e : finalGraph.getEdgeSet()) {
            e.setAttribute(WEIGHT, 1.0);
        }

        for (Node j : finalGraph) {
            for (Node k : finalGraph) {
                if (j != k) {
                    // is there a path between?
                    BellmanFord bfShortest = new BellmanFord(WEIGHT, j.getId());
                    bfShortest.init(finalGraph);
                    bfShortest.compute();

                    Path shortestPath = bfShortest.getShortestPath(k);

                    if (shortestPath.size() > 0) {
                        // we have a path
                        GeneratedArgumentPair ap = new GeneratedArgumentPair();
                        Argument arg1 = allArguments.get(j.getId());

                        if (arg1 == null) {
                            throw new IllegalStateException("Cannot find argument " + j.getId());
                        }
                        ap.setArg1(arg1);

                        Argument arg2 = allArguments.get(k.getId());

                        if (arg2 == null) {
                            throw new IllegalStateException("Cannot find argument " + k.getId());
                        }
                        ap.setArg2(arg2);

                        ap.setGoldLabel("a1");
                        generatedArgumentPairs.add(ap);
                    }
                }
            }
        }
        // and now add the reverse ones
        Set<GeneratedArgumentPair> generatedReversePairs = new HashSet<>();
        for (GeneratedArgumentPair pair : generatedArgumentPairs) {
            GeneratedArgumentPair ap = new GeneratedArgumentPair();
            ap.setArg1(pair.getArg2());
            ap.setArg2(pair.getArg1());
            ap.setGoldLabel("a2");
            generatedReversePairs.add(ap);
        }
        generatedArgumentPairs.addAll(generatedReversePairs);
        // and save it
        XStreamTools.toXML(generatedArgumentPairs, new File(outputDir, "generated_" + prefix + file.getName()));
    }

    result.fullPairsSize = fullDataSize;
    result.removedApriori = (fullDataSize - preFilteredDataSize);
    result.finalPairsRetained = finalArgumentPairList.size();

    // save the final graph
    Graph outGraph = cleanCopyGraph(lastGraph);
    FileSinkDGS dgs1 = new FileSinkDGS();
    File outFile = new File(outputDir, prefix + file.getName() + ".dgs");

    System.out.println("Saved to " + outFile);
    FileWriter w1 = new FileWriter(outFile);

    dgs1.writeAll(outGraph, w1);
    w1.close();

    return result;
}

From source file:fr.inria.atlanmod.instantiator.neoEMF.GenericMetamodelConfig.java

/**
 * Sets the minimum and maximum number of properties allowed for
 * {@link EObject}s created using this {@link ISpecimenConfiguration}
 * //from   w w  w  . j a v a  2 s  . c  o  m
 * @param min
 *            The minimum
 * @param max
 *            The maximum
 */
public void setPropertiesRange(int min, int max) {
    this.propertiesRange = Range.between(min, max);
}

From source file:libepg.epg.section.descriptor.servicedescriptor.SERVICE_TYPE.java

private SERVICE_TYPE(String serviceType, Integer typeId, Integer... typeIds) {
    this.serviceType = serviceType;
    if ((this.serviceType == null) || (this.serviceType.equals(""))) {
        throw new IllegalArgumentException("????????");
    }//  www . j a v a2 s.c om

    Range<Integer> r = Range.between(0x0, 0xFF);

    DeduplicatdeNumberSetFactory<Integer> setf = new DeduplicatdeNumberSetFactory<>();

    this.typeIds = setf.makeSet(r, typeId, typeIds);
}

From source file:libepg.epg.section.descriptor.servicedescriptor.SERVICE_ID.java

private SERVICE_ID(String serviceType, Integer serviceId, Integer... serviceIds) {
    this.serviceType = serviceType;
    if ((this.serviceType == null) || (this.serviceType.equals(""))) {
        throw new IllegalArgumentException("??????");
    }/*  www  . j a  v  a  2 s. com*/

    List<Integer> t = new ArrayList<>();
    if (serviceId != null) {
        t.add(serviceId);
    } else {
        throw new NullPointerException("ID??????");
    }
    if (serviceIds != null) {
        t.addAll(Arrays.asList(serviceIds));
    }
    Range<Integer> r = Range.between(0x0, 0xFF);
    for (Integer i : t) {
        if (!r.contains(i)) {
            MessageFormat msg = new MessageFormat(
                    "ID????ID={0}");
            Object[] parameters = { Integer.toHexString(i) };
            throw new IllegalArgumentException(msg.format(parameters));
        }
    }

    Set<Integer> temp = Collections.synchronizedSet(new HashSet<Integer>());
    temp.addAll(t);
    this.serviceIds = Collections.unmodifiableSet(temp);
}

From source file:libepg.epg.section.descriptor.DESCRIPTOR_TAG.java

private DESCRIPTOR_TAG(String tagName, Class<? extends Descriptor> dataType, Integer tag, Integer... tags) {

    this.tagName = tagName;
    if ((this.tagName == null) || ("".equals(this.tagName))) {
        throw new IllegalArgumentException("???????????");
    }//  w  w w. ja  va2 s.c o  m

    List<Integer> t = new ArrayList<>();
    if (tag != null) {
        t.add(tag);
    } else {
        throw new NullPointerException("??????");
    }
    if (tags != null) {
        t.addAll(Arrays.asList(tags));
    }
    Range<Integer> r = Range.between(0x0, 0xFF);
    for (Integer i : t) {
        if (!r.contains(i)) {
            MessageFormat msg = new MessageFormat("????={0}");
            Object[] parameters = { Integer.toHexString(i) };
            throw new IllegalArgumentException(msg.format(parameters));
        }
    }
    Set<Integer> temp = Collections.synchronizedSet(new HashSet<Integer>());
    temp.addAll(t);
    this.tags = Collections.unmodifiableSet(temp);
    this.dataType = dataType;
}

From source file:de.tor.tribes.util.report.ReportRule.java

public ReportRule(Element pElm) throws IllegalArgumentException {
    try {/*from ww w.  ja va  2  s .  c o  m*/
        type = RuleType.valueOf(pElm.getChildText("type"));
        targetSet = pElm.getChildText("targetSet");
        Element settings = pElm.getChild("settings");

        //check arguments and throw Exception if illigal
        switch (type) {
        case AGE:
            Long maxAge = Long.parseLong(settings.getText());
            filterComponent = maxAge;
            break;
        case ATTACKER_ALLY:
            List<Ally> attAllyList = new ArrayList<>();
            for (Element e : settings.getChildren("ally")) {
                int id = Integer.parseInt(e.getText());
                attAllyList.add(DataHolder.getSingleton().getAllies().get(id));
            }
            filterComponent = attAllyList;
            break;
        case ATTACKER_TRIBE:
            List<Tribe> attTribeList = new ArrayList<>();
            for (Element e : settings.getChildren("tribe")) {
                int id = Integer.parseInt(e.getText());
                attTribeList.add(DataHolder.getSingleton().getTribes().get(id));
            }
            filterComponent = attTribeList;
            break;
        case COLOR:
            Integer color = Integer.parseInt(settings.getText());
            filterComponent = color;
            break;
        case DATE:
            String dates[] = settings.getText().split("-");
            Long start = Long.parseLong(dates[0]);
            Long end = Long.parseLong(dates[1]);
            Range<Long> dateSpan = Range.between(start, end);
            filterComponent = dateSpan;
            break;
        case DEFENDER_ALLY:
            List<Ally> defAllyList = new ArrayList<>();
            for (Element e : settings.getChildren("ally")) {
                int id = Integer.parseInt(e.getText());
                defAllyList.add(DataHolder.getSingleton().getAllies().get(id));
            }
            filterComponent = defAllyList;
            break;
        case DEFENDER_TRIBE:
            List<Tribe> defTribeList = new ArrayList<>();
            for (Element e : settings.getChildren("tribe")) {
                int id = Integer.parseInt(e.getText());
                defTribeList.add(DataHolder.getSingleton().getTribes().get(id));
            }
            filterComponent = defTribeList;
            break;
        case CATA:
        case CONQUERED:
        case FAKE:
        case FARM:
        case OFF:
        case WALL:
            filterComponent = null;
            break;
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:de.tor.tribes.types.TimeSpan.java

public boolean intersects(TimeSpan pSpan) {
    if (!this.getDirection().equals(pSpan.getDirection())) {
        //different directions
        return false;
    }//from  w w  w.  ja  v a2 s  . c om

    //one of the spans uses manual Time (new intersect)
    Range<Long> thisSpan = this.getSpan();
    Range<Long> theOtherSpan = pSpan.getSpan();

    if (this.isValidAtEveryDay() || pSpan.isValidAtEveryDay()) {
        if (this.isValidAtSpecificDay() || pSpan.isValidAtSpecificDay()) {
            //remove day Information
            Long thisStart = DateUtils.getFragmentInMilliseconds(new Date(thisSpan.getMinimum()),
                    Calendar.DATE);
            Long thisEnd = DateUtils.getFragmentInMilliseconds(new Date(thisSpan.getMaximum()), Calendar.DATE);
            thisSpan = Range.between(thisStart, thisEnd);

            Long otherStart = DateUtils.getFragmentInMilliseconds(new Date(theOtherSpan.getMinimum()),
                    Calendar.DATE);
            Long otherEnd = DateUtils.getFragmentInMilliseconds(new Date(theOtherSpan.getMaximum()),
                    Calendar.DATE);

            theOtherSpan = Range.between(otherStart, otherEnd);

            return thisSpan.isOverlappedBy(theOtherSpan);
        } else if (this.isValidAtEveryDay() && pSpan.isValidAtEveryDay()) {
            //both valid at every Day - just compare spans
            return thisSpan.isOverlappedBy(theOtherSpan);
        } else {
            //one span is for everyDay the other is over multiple Days
            //manual intersect
            Range<Long> always;
            Range<Long> manual;
            if (this.isValidAtEveryDay()) {
                always = thisSpan;
                manual = theOtherSpan;
            } else {
                always = theOtherSpan;
                manual = thisSpan;
            }

            long manualDate = DateUtils.truncate(new Date(manual.getMinimum()), Calendar.DATE).getTime();
            long manualStart = manual.getMinimum() - manualDate;
            long manualEnd = manual.getMaximum() - manualDate;

            if (manualEnd - manualStart > DateUtils.MILLIS_PER_DAY) {
                //must intersect somehow because span is longer than 1 Day
                return true;
            }
            //direct intersection
            manual = Range.between(manualStart, manualEnd);
            if (always.isOverlappedBy(manual))
                return true;

            //should not be possible, because it should be handeld by isValidAtSpecificDay
            if (manualEnd <= DateUtils.MILLIS_PER_DAY)
                return false;

            //maybe intersection at next day
            manual = Range.between(new Long(0), manualEnd - DateUtils.MILLIS_PER_DAY);
            return always.isOverlappedBy(manual);
        }
    }

    return thisSpan.isOverlappedBy(theOtherSpan);
}

From source file:fr.inria.atlanmod.instantiator.neoEMF.GenericMetamodelConfig.java

/**
 * Sets the minimum and maximum number of references allowed for
 * {@link EObject}s created using this {@link ISpecimenConfiguration}
 * //from   w w w. ja  v  a  2  s .  com
 * @param min
 *            The minimum
 * @param max
 *            The maximum
 */
public void setReferencesRange(int min, int max) {
    this.referencesRange = Range.between(min, max);
}

From source file:fr.inria.atlanmod.instantiator.neoEMF.GenericMetamodelConfig.java

/**
 * Sets the minimum and maximum length of non-fixed-sized properties (e.g.,
 * {@link String}s, arrays, etc).//from w  w w . jav  a2  s  .com
 * 
 * @param min
 *            The minimum
 * @param max
 *            The maximum
 */
public void setValuesRange(int min, int max) {
    this.valuesRange = Range.between(min, max);
}